-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaccount-fetch.ts
96 lines (85 loc) · 2.36 KB
/
account-fetch.ts
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
import { FrameSystemAccountInfo } from "@polkadot/types/lookup.ts";
import { Api, Ss58AccountId } from "./util.ts";
import { AccountId32 } from "@polkadot/types/interfaces/types.ts";
export type BalanceData = {
readonly free: bigint;
readonly reserved: bigint;
readonly miscFrozen: bigint;
readonly feeFrozen: bigint;
};
export type AccountStorageKey = {
accountId: () => Ss58AccountId;
// deno-lint-ignore no-explicit-any
key: any;
};
export abstract class AccountFetcher {
abstract fetchAccounts(
startKey?: AccountStorageKey,
): Promise<[AccountStorageKey, BalanceData][]>;
}
// deno-lint-ignore no-explicit-any
type StartKey = any;
export class ApiAccountFetcher extends AccountFetcher {
constructor(private api: Api) {
super();
}
async fetchAccounts(
startKey?: AccountStorageKey,
): Promise<[AccountStorageKey, BalanceData][]> {
const accounts = await this.api.query.system.account.entriesPaged<
FrameSystemAccountInfo,
[AccountId32]
>({
pageSize: 1000,
args: [],
startKey: startKey?.key,
});
return accounts.map(
([
key,
{
data: { free, reserved, miscFrozen, feeFrozen },
},
]) => {
const mappedKey = {
accountId: () => {
const address = key.args[0].toString();
return new Ss58AccountId(address);
},
key,
};
const mappedData = {
free: free.toBigInt(),
reserved: reserved.toBigInt(),
miscFrozen: miscFrozen.toBigInt(),
feeFrozen: feeFrozen.toBigInt(),
};
return [mappedKey, mappedData] as const;
},
);
}
}
export class LocalAccountFetcher extends AccountFetcher {
constructor(
public accounts: [AccountStorageKey, BalanceData][],
public pageSize = 1000,
) {
super();
}
fetchAccounts(
startKey?: AccountStorageKey,
): Promise<[AccountStorageKey, BalanceData][]> {
if (!startKey) {
return Promise.resolve(this.accounts.slice(0, this.pageSize));
}
if (startKey && typeof startKey.key === "number") {
if (startKey.key + 1 >= this.accounts.length) {
return Promise.resolve([]);
}
return Promise.resolve(
this.accounts.slice(startKey.key + 1, startKey.key + 1 + this.pageSize),
);
}
throw new Error("Invalid startKey " + startKey);
}
}