generated from PolymeshAssociation/typescript-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Checkpoint.ts
273 lines (236 loc) · 8.1 KB
/
Checkpoint.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
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
import { u64 } from '@polkadot/types';
import { PolymeshPrimitivesIdentityId, PolymeshPrimitivesTicker } from '@polkadot/types/lookup';
import BigNumber from 'bignumber.js';
import { Context, Entity, FungibleAsset, Identity } from '~/internal';
import { IdentityBalance, PaginationOptions, ResultSet } from '~/types';
import { tuple } from '~/types/utils';
import {
balanceToBigNumber,
bigNumberToU64,
identityIdToString,
momentToDate,
stringToIdentityId,
stringToTicker,
u64ToBigNumber,
} from '~/utils/conversion';
import { getIdentity, requestPaginated, toHumanReadable } from '~/utils/internal';
export interface UniqueIdentifiers {
id: BigNumber;
ticker: string;
}
export interface HumanReadable {
id: string;
ticker: string;
}
/**
* Represents a snapshot of the Asset's holders and their respective balances
* at a certain point in time
*/
export class Checkpoint extends Entity<UniqueIdentifiers, HumanReadable> {
/**
* @hidden
* Check if a value is of type {@link UniqueIdentifiers}
*/
public static override isUniqueIdentifiers(identifier: unknown): identifier is UniqueIdentifiers {
const { id, ticker } = identifier as UniqueIdentifiers;
return id instanceof BigNumber && typeof ticker === 'string';
}
/**
* Checkpoint identifier number
*/
public id: BigNumber;
/**
* Asset whose balances are being recorded in this Checkpoint
*/
public asset: FungibleAsset;
/**
* @hidden
*/
public constructor(identifiers: UniqueIdentifiers, context: Context) {
super(identifiers, context);
const { id, ticker } = identifiers;
this.id = id;
this.asset = new FungibleAsset({ ticker }, context);
}
/**
* Retrieve the Asset's total supply at this checkpoint
*/
public async totalSupply(): Promise<BigNumber> {
const {
context,
asset: { ticker },
id,
} = this;
const rawSupply = await context.polymeshApi.query.checkpoint.totalSupply(
stringToTicker(ticker, context),
bigNumberToU64(id, context)
);
return balanceToBigNumber(rawSupply);
}
/**
* Retrieve this Checkpoint's creation date
*/
public async createdAt(): Promise<Date> {
const {
context,
asset: { ticker },
id,
} = this;
const creationTime = await context.polymeshApi.query.checkpoint.timestamps(
stringToTicker(ticker, context),
bigNumberToU64(id, context)
);
return momentToDate(creationTime);
}
/**
* Retrieve all Asset Holder balances at this Checkpoint
*
* @note supports pagination
* @note current Asset holders who didn't hold any tokens when the Checkpoint was created will be listed with a balance of 0.
* This arises from a chain storage optimization and pagination. @see {@link balance} for a more detailed explanation of the logic
*/
public async allBalances(
paginationOpts?: PaginationOptions
): Promise<ResultSet<IdentityBalance>> {
const {
context: {
polymeshApi: {
query: { checkpoint, asset },
},
},
context,
asset: { ticker },
id,
} = this;
const rawTicker = stringToTicker(ticker, context);
// Get one page of current Asset balances
const { entries, lastKey: next } = await requestPaginated(asset.balanceOf, {
arg: rawTicker,
paginationOpts,
});
const currentDidBalances: { did: string; balance: BigNumber }[] = [];
const balanceUpdatesMultiParams: [PolymeshPrimitivesTicker, PolymeshPrimitivesIdentityId][] =
[];
// Prepare the query for balance updates. Push to currentDidBalances to be used if there are no updates for the balance
entries.forEach(([storageKey, balance]) => {
const {
args: [, identityId],
} = storageKey;
currentDidBalances.push({
did: identityIdToString(identityId),
balance: balanceToBigNumber(balance),
});
balanceUpdatesMultiParams.push(tuple(rawTicker, identityId));
});
// Query for balance updates
const rawBalanceUpdates = await checkpoint.balanceUpdates.multi(balanceUpdatesMultiParams);
const checkpointBalanceMultiParams: {
did: string;
params: [(PolymeshPrimitivesTicker | u64)[], PolymeshPrimitivesIdentityId];
}[] = [];
const currentIdentityBalances: IdentityBalance[] = [];
rawBalanceUpdates.forEach((rawCheckpointIds, index) => {
const firstUpdatedCheckpoint = rawCheckpointIds.find(checkpointId =>
u64ToBigNumber(checkpointId).gte(id)
);
const { did, balance } = currentDidBalances[index];
if (firstUpdatedCheckpoint) {
// If a balance update has occurred for the Identity since the desired Checkpoint, then query Checkpoint storage directly
checkpointBalanceMultiParams.push({
did,
params: tuple([rawTicker, firstUpdatedCheckpoint], stringToIdentityId(did, context)),
});
} else {
// Otherwise use the current balance
currentIdentityBalances.push({
identity: new Identity({ did }, context),
balance,
});
}
});
// Query for Identities with balance updates
const checkpointBalances = await checkpoint.balance.multi(
checkpointBalanceMultiParams.map(({ params }) => params)
);
return {
data: [
...checkpointBalanceMultiParams.map(({ did }, index) => ({
identity: new Identity({ did }, context),
balance: balanceToBigNumber(checkpointBalances[index]),
})),
...currentIdentityBalances,
],
next,
};
}
/**
* Retrieve the balance of a specific Asset Holder Identity at this Checkpoint
*
* @param args.identity - defaults to the signing Identity
* @note A checkpoint only records balances when they change. The implementation is to query for all balance updates for [ticker, did] pair.
* If no balance updates have happened since the Checkpoint has been created, then the storage will not have an entry for the user. Instead the current balance should be used.
* The balance is stored only when the Identity makes a transaction after a Checkpoint is created. This helps keep storage usage to a minimum
*/
public async balance(args?: { identity: string | Identity }): Promise<BigNumber> {
const {
context,
context: {
polymeshApi: {
query: { checkpoint },
},
},
asset: { ticker },
id,
} = this;
const identity = await getIdentity(args?.identity, context);
const rawTicker = stringToTicker(ticker, context);
const rawIdentityId = stringToIdentityId(identity.did, context);
const balanceUpdates = await checkpoint.balanceUpdates(rawTicker, rawIdentityId);
const firstUpdatedCheckpoint = balanceUpdates.find(checkpointId =>
u64ToBigNumber(checkpointId).gte(id)
);
/*
* If there has been a balance change since the Checkpoint was created, then query the Checkpoint storage.
* Otherwise, the storage will not have an entry for the Identity. The current balance should be queried instead.
*/
let balance: BigNumber;
if (firstUpdatedCheckpoint) {
const rawBalance = await checkpoint.balance(
tuple(rawTicker, firstUpdatedCheckpoint),
rawIdentityId
);
balance = balanceToBigNumber(rawBalance);
} else {
// if no balanceUpdate has occurred since the Checkpoint has been created, then the current balance should be used. The Checkpoint storage will not have an entry
balance = await identity.getAssetBalance({ ticker });
}
return balance;
}
/**
* Determine whether this Checkpoint exists on chain
*/
public async exists(): Promise<boolean> {
const {
context: {
polymeshApi: {
query: { checkpoint },
},
},
context,
asset: { ticker },
id,
} = this;
const rawCheckpointId = await checkpoint.checkpointIdSequence(stringToTicker(ticker, context));
return id.lte(u64ToBigNumber(rawCheckpointId));
}
/**
* Return the Checkpoint's ticker and identifier
*/
public toHuman(): HumanReadable {
const { asset, id } = this;
return toHumanReadable({
ticker: asset,
id,
});
}
}