-
Notifications
You must be signed in to change notification settings - Fork 0
/
assets.tsx
391 lines (312 loc) · 11.8 KB
/
assets.tsx
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
import { createStore, produce } from "solid-js/store";
import { useMsqClient } from "./global";
import { Accessor, Setter, createContext, createSignal, onCleanup, onMount, useContext } from "solid-js";
import {
DEFAULT_PRINCIPAL,
IAssetMetadata,
IChildren,
ONE_MIN_MS,
getAssetMetadata,
makeAgent,
makeAnonymousAgent,
makeIcrc1Salt,
} from "../utils";
import { IcrcLedgerCanister } from "@dfinity/ledger-icrc";
import { Principal } from "@dfinity/principal";
import { MsqIdentity } from "@fort-major/msq-client";
import { PRE_LISTED_TOKENS, TAccountId, delay, unreacheable } from "@fort-major/msq-shared";
import { AnonymousIdentity } from "@dfinity/agent";
import { ISendPageProps } from "../pages/cabinet/my-assets/send";
import { IPaymentCheckoutPageProps } from "../pages/integration/payment/checkout";
import { ITxnHistoryPageProps } from "../pages/cabinet/my-assets/txn-history";
import { useNavigate } from "@solidjs/router";
export type IAssetDataExt = {
accounts: {
name: string;
principal?: string | undefined;
balance: bigint | undefined;
}[];
metadata?: IAssetMetadata | undefined;
totalBalance: bigint;
};
// undefined == not loaded yet, null == erroed
export type AllAssetData = Record<string, IAssetDataExt | undefined | null>;
export type SendPagePropsStore = [Accessor<ISendPageProps | undefined>, Setter<ISendPageProps | undefined>];
export type TxnHistoryPropsStore = [
Accessor<ITxnHistoryPageProps | undefined>,
Setter<ITxnHistoryPageProps | undefined>,
];
type PaymentCheckoutPageStore = [
Accessor<IPaymentCheckoutPageProps | undefined>,
Setter<IPaymentCheckoutPageProps | undefined>,
];
export interface IAssetDataStore {
assets: AllAssetData;
init: (assetIds?: string[]) => Promise<void>;
fetch: (assetIds?: string[]) => Promise<boolean[] | undefined>;
refresh: (assetIds?: string[]) => Promise<void>;
addAccount: (assetId: string, assetName: string, symbol: string) => Promise<void>;
editAccount: (assetId: string, accountId: TAccountId, newName: string) => Promise<void>;
addAsset: (assetId: string) => Promise<void>;
removeAssetLogo: (assetId: string) => void;
sendPageProps: SendPagePropsStore;
paymentCheckoutPageProps: PaymentCheckoutPageStore;
txnHistoryPageProps: TxnHistoryPropsStore;
}
const AssetDataContext = createContext<IAssetDataStore>();
export function useAssetData(): IAssetDataStore {
const c = useContext(AssetDataContext);
if (!c) {
unreacheable("Asset context is uninitialized");
}
return c;
}
export function useSendPageProps(): SendPagePropsStore {
const c = useContext(AssetDataContext);
if (!c) {
unreacheable("Cabinet context is uninitialized");
}
return c.sendPageProps;
}
export function usePaymentCheckoutPageProps() {
const ctx = useContext(AssetDataContext);
if (!ctx) {
unreacheable("Integration context is uninitialized");
}
return ctx.paymentCheckoutPageProps;
}
export function useTxnHistoryPageProps() {
const ctx = useContext(AssetDataContext);
if (!ctx) {
unreacheable("Integration context is uninitialized");
}
return ctx.txnHistoryPageProps;
}
const PRE_DEFINED_ASSETS: { assetId: string; name: string; symbol: string; decimals: number; fee: bigint }[] =
Object.values(PRE_LISTED_TOKENS).map((it) => ({
assetId: it.assetId,
name: it.name,
symbol: it.symbol,
decimals: it.decimals,
fee: it.fee,
}));
export function AssetsStore(props: IChildren) {
const [allAssetData, setAllAssetData] = createStore<AllAssetData>();
const [sendPageProps, setSendPageProps] = createSignal<ISendPageProps | undefined>(undefined);
const [paymentCheckoutPageProps, setPaymentCheckoutPageProps] = createSignal<IPaymentCheckoutPageProps | undefined>();
const [txnHistoryPageProps, setTxnHistoryPageProps] = createSignal<ITxnHistoryPageProps | undefined>();
const [refreshPeriodically, setRefreshPeriodically] = createSignal(true);
const [initialized, setInitialized] = createSignal(false);
const _msq = useMsqClient();
const navigate = useNavigate();
onMount(async () => {
while (refreshPeriodically()) {
await delay(ONE_MIN_MS);
if (_msq()) await refresh();
}
});
onCleanup(() => {
setRefreshPeriodically(false);
});
const init = async () => {
if (initialized()) return;
await addPredefinedAssets();
await fetch();
await refresh();
setInitialized(true);
};
const addPredefinedAssets = async () => {
const msq = _msq()!;
let fetchedAllAssetData = await msq.getAllAssetData();
const assetsToCreate = [];
for (let asset of PRE_DEFINED_ASSETS) {
if (fetchedAllAssetData[asset.assetId]) continue;
assetsToCreate.push(asset);
}
if (assetsToCreate.length > 0) {
await msq.addAsset({ assets: assetsToCreate });
}
};
const fetch = async (assetIds?: string[]): Promise<boolean[] | undefined> => {
const msq = _msq()!;
let fetchedAllAssetData = await msq.getAllAssetData(assetIds);
// trap, if it is proposed for payment, but not listed in user's wallet
if (assetIds) {
for (let assetId of assetIds) {
if (fetchedAllAssetData[assetId]) continue;
navigate("/token-not-found");
}
}
const allAssetDataKeys = Object.keys(fetchedAllAssetData);
const allAssetData = fetchedAllAssetData as unknown as AllAssetData;
const result: boolean[] | undefined = assetIds?.map((_) => false);
for (let idx = 0; idx < allAssetDataKeys.length; idx++) {
const key = allAssetDataKeys[idx];
if (result && assetIds!.includes(key)) result[idx] = true;
allAssetData[key]!.accounts = fetchedAllAssetData[key]!.accounts.map((it) => ({
name: it,
balance: undefined,
}));
allAssetData[key]!.totalBalance = BigInt(0);
}
setAllAssetData(allAssetData);
return result;
};
const refresh = async (assetIds?: string[]) => {
const msq = _msq()!;
const agent = await makeAnonymousAgent();
if (!assetIds) assetIds = Object.keys(allAssetData);
for (let assetId of assetIds) {
const ledger = IcrcLedgerCanister.create({ agent, canisterId: Principal.fromText(assetId) });
getAssetMetadata(ledger, false)
.then((metadata) => {
// if we're queried for the first time, or the data is different - send an update to verify
if (!metadataIsEqual(metadata, allAssetData[assetId]?.metadata)) {
setAllAssetData(assetId, { metadata, totalBalance: 0n });
getAssetMetadata(ledger, true).then((metadata) => setAllAssetData(assetId, "metadata", metadata));
}
for (let idx = 0; idx < allAssetData[assetId]!.accounts.length; idx++) {
MsqIdentity.create(msq.getInner(), makeIcrc1Salt(assetId, idx)).then((identity) => {
const principal = identity.getPrincipal();
setAllAssetData(assetId, "accounts", idx, "principal", principal.toText());
updateBalanceOf(ledger, assetId, idx);
});
}
})
.catch((e) => {
console.error(e);
setAllAssetData(assetId, null);
});
}
};
const addAccount = async (assetId: string) => {
const msq = _msq()!;
const name = await msq.addAssetAccount(assetId);
if (name === null) return;
const accountId = allAssetData[assetId]!.accounts.length;
setAllAssetData(assetId, "accounts", accountId, { name, balance: BigInt(0), principal: DEFAULT_PRINCIPAL });
const identity = await MsqIdentity.create(msq.getInner(), makeIcrc1Salt(assetId, accountId));
const principal = identity.getPrincipal();
setAllAssetData(assetId, "accounts", accountId, "principal", principal.toText());
const agent = await makeAnonymousAgent();
const ledger = IcrcLedgerCanister.create({ agent, canisterId: Principal.fromText(assetId) });
try {
await updateBalanceOf(ledger, assetId, accountId);
} catch {
setAllAssetData(assetId, null);
}
};
const addAsset = async (assetId: string) => {
const msq = _msq()!;
const anonIdentity = new AnonymousIdentity();
const agent = await makeAgent(anonIdentity);
const ledger = IcrcLedgerCanister.create({ agent, canisterId: Principal.fromText(assetId) });
// first we query to be fast
let metadata = await getAssetMetadata(ledger, false);
setAllAssetData(
produce((state) => {
state[assetId] = {
metadata,
totalBalance: 0n,
accounts: [
{
name: "Creating...",
balance: BigInt(0),
principal: DEFAULT_PRINCIPAL,
},
],
};
}),
);
// then we update to be sure
metadata = await getAssetMetadata(ledger, true);
const assetData = await msq.addAsset({
assets: [
{
assetId,
name: metadata.name,
symbol: metadata.symbol,
decimals: metadata.decimals,
fee: metadata.fee,
},
],
});
if (assetData === null) {
setAllAssetData(assetId, undefined);
return;
}
setAllAssetData(
produce((state) => {
state[assetId]!.metadata = metadata;
state[assetId]!.accounts[0].name = assetData[0].accounts[0];
}),
);
const identity = await MsqIdentity.create(msq.getInner(), makeIcrc1Salt(assetId, 0));
const principal = identity.getPrincipal();
setAllAssetData(assetId, "accounts", 0, "principal", principal.toText());
updateBalanceOf(ledger, assetId, 0);
};
const editAccount = async (assetId: string, accountId: TAccountId, newName: string) => {
const msq = _msq()!;
setAllAssetData(assetId, "accounts", accountId, "name", newName);
await msq.editAssetAccount(assetId, accountId, newName);
};
const updateBalanceOf = async (ledger: IcrcLedgerCanister, assetId: string, accountId: number) => {
// first we query to be fast
let balance = await ledger.balance({
certified: false,
owner: Principal.fromText(allAssetData[assetId]!.accounts[accountId].principal!),
});
// if balance is the same as we were observing the last time - skip the update call
if (balance === allAssetData[assetId]?.accounts[accountId].balance) return;
setAllAssetData(
produce((state) => {
state[assetId]!.accounts[accountId].balance = balance;
const totalBalance = state[assetId]!.accounts!.reduce((prev, cur) => prev + (cur.balance || 0n), 0n);
state[assetId]!.totalBalance = totalBalance;
}),
);
// then we update to be sure
balance = await ledger.balance({
certified: true,
owner: Principal.fromText(allAssetData[assetId]!.accounts[accountId].principal!),
});
setAllAssetData(
produce((state) => {
state[assetId]!.accounts[accountId].balance = balance;
const totalBalance = state[assetId]!.accounts!.reduce((prev, cur) => prev + (cur.balance || 0n), 0n);
state[assetId]!.totalBalance = totalBalance;
}),
);
};
const removeAssetLogo = (assetId: string) => {
setAllAssetData(assetId, "metadata", "logoSrc", undefined);
};
return (
<AssetDataContext.Provider
value={{
assets: allAssetData,
init,
fetch,
refresh,
addAccount,
editAccount,
addAsset,
removeAssetLogo,
sendPageProps: [sendPageProps, setSendPageProps],
paymentCheckoutPageProps: [paymentCheckoutPageProps, setPaymentCheckoutPageProps],
txnHistoryPageProps: [txnHistoryPageProps, setTxnHistoryPageProps],
}}
>
{props.children}
</AssetDataContext.Provider>
);
}
function metadataIsEqual(a: IAssetMetadata, b?: IAssetMetadata): boolean {
if (!b) return false;
if (a.decimals !== b.decimals) return false;
if (a.fee !== b.fee) return false;
if (a.symbol !== b.symbol) return false;
if (a.name !== b.name) return false;
return true;
}