forked from dfinity/pic-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathledger.ts
More file actions
94 lines (83 loc) · 2.41 KB
/
ledger.ts
File metadata and controls
94 lines (83 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { AnonymousIdentity, Identity } from '@dfinity/agent';
import { Principal } from '@dfinity/principal';
import { Actor, PocketIc } from 'pic-js-mops';
import {
_SERVICE as LedgerService,
SubAccount,
idlFactory as ledgerIdlFactory,
} from '../canisters/ledger';
import { minterIdentity } from './identity';
const ICP_LEDGER_CANISTER_ID = Principal.fromText(
'ryjl3-tyaaa-aaaaa-aaaba-cai',
);
const E8S_PER_ICP = 100_000_000;
const DEFAULT_FEE = 10_000n;
export function icpToE8s(icp: number): bigint {
return BigInt(icp * E8S_PER_ICP);
}
export class Ledger {
private readonly actor: Actor<LedgerService>;
private readonly defaultIdentity = new AnonymousIdentity();
constructor(pic: PocketIc) {
this.actor = pic.createActor<LedgerService>(
ledgerIdlFactory,
ICP_LEDGER_CANISTER_ID,
);
}
public async mint(
amountE8s: bigint,
toAccount: Principal,
toSubAccount?: SubAccount,
memo?: Uint8Array | number[],
): Promise<void> {
return await this.transfer(
minterIdentity,
amountE8s,
toAccount,
toSubAccount,
memo,
);
}
public async transfer(
identity: Identity,
amountE8s: bigint,
toAccount: Principal,
toSubAccount?: SubAccount,
memo?: Uint8Array | number[],
): Promise<void> {
this.actor.setIdentity(identity);
const subaccount: [] | [SubAccount] = toSubAccount ? [toSubAccount] : [];
const optMemo: [] | [Uint8Array | number[]] = memo ? [memo] : [];
const fromBalance = await this.actor.icrc1_balance_of({
owner: identity.getPrincipal(),
subaccount: [],
});
const toBalance = await this.actor.icrc1_balance_of({
owner: toAccount,
subaccount,
});
const result = await this.actor.icrc1_transfer({
amount: amountE8s,
to: {
owner: toAccount,
subaccount,
},
memo: optMemo,
fee: [DEFAULT_FEE],
created_at_time: [],
from_subaccount: [],
});
expect('Ok' in result).toBe(true);
const updatedFromBalance = await this.actor.icrc1_balance_of({
owner: identity.getPrincipal(),
subaccount: [],
});
expect(updatedFromBalance).toBe(fromBalance - amountE8s - DEFAULT_FEE);
const updatedToBalance = await this.actor.icrc1_balance_of({
owner: toAccount,
subaccount,
});
expect(updatedToBalance).toBe(toBalance + amountE8s);
this.actor.setIdentity(this.defaultIdentity);
}
}