generated from PolymeshAssociation/typescript-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.ts
491 lines (431 loc) · 14.4 KB
/
index.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
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
import { Option, StorageKey } from '@polkadot/types';
import {
AgentGroup,
Counter,
IdentityId,
SecurityToken as MeshSecurityToken,
Ticker,
} from 'polymesh-types/types';
import {
Context,
controllerTransfer,
ControllerTransferParams,
Entity,
Identity,
modifyPrimaryIssuanceAgent,
ModifyPrimaryIssuanceAgentParams,
modifyToken,
ModifyTokenParams,
redeemToken,
RedeemTokenParams,
removePrimaryIssuanceAgent,
toggleFreezeTransfers,
transferTokenOwnership,
TransferTokenOwnershipParams,
} from '~/internal';
import { eventByIndexedArgs } from '~/middleware/queries';
import { EventIdEnum, ModuleIdEnum, Query } from '~/middleware/types';
import {
Ensured,
EventIdentifier,
ProcedureMethod,
SubCallback,
TokenIdentifier,
UnsubCallback,
} from '~/types';
import { MAX_TICKER_LENGTH } from '~/utils/constants';
import {
assetIdentifierToTokenIdentifier,
assetTypeToString,
balanceToBigNumber,
boolToBoolean,
fundingRoundNameToString,
identityIdToString,
middlewareEventToEventIdentifier,
stringToTicker,
tickerToDid,
u64ToBigNumber,
} from '~/utils/conversion';
import { createProcedureMethod, optionize, padString } from '~/utils/internal';
import { Checkpoints } from './Checkpoints';
import { Compliance } from './Compliance';
import { CorporateActions } from './CorporateActions';
import { Documents } from './Documents';
import { Issuance } from './Issuance';
import { Offerings } from './Offerings';
import { Permissions } from './Permissions';
import { Settlements } from './Settlements';
import { TokenHolders } from './TokenHolders';
import { TransferRestrictions } from './TransferRestrictions';
import { SecurityTokenDetails } from './types';
/**
* Properties that uniquely identify a Security Token
*/
export interface UniqueIdentifiers {
/**
* ticker of the security token
*/
ticker: string;
}
/**
* Class used to manage all the Security Token functionality
*/
export class SecurityToken extends Entity<UniqueIdentifiers, string> {
/**
* @hidden
* Check if a value is of type [[UniqueIdentifiers]]
*/
public static isUniqueIdentifiers(identifier: unknown): identifier is UniqueIdentifiers {
const { ticker } = identifier as UniqueIdentifiers;
return typeof ticker === 'string';
}
/**
* identity id of the Security Token
*/
public did: string;
/**
* ticker of the Security Token
*/
public ticker: string;
// Namespaces
public documents: Documents;
public settlements: Settlements;
public tokenHolders: TokenHolders;
public issuance: Issuance;
public compliance: Compliance;
public transferRestrictions: TransferRestrictions;
public offerings: Offerings;
public checkpoints: Checkpoints;
public corporateActions: CorporateActions;
public permissions: Permissions;
/**
* @hidden
*/
constructor(identifiers: UniqueIdentifiers, context: Context) {
super(identifiers, context);
const { ticker } = identifiers;
this.ticker = ticker;
this.did = tickerToDid(ticker);
this.documents = new Documents(this, context);
this.settlements = new Settlements(this, context);
this.tokenHolders = new TokenHolders(this, context);
this.issuance = new Issuance(this, context);
this.compliance = new Compliance(this, context);
this.transferRestrictions = new TransferRestrictions(this, context);
this.offerings = new Offerings(this, context);
this.checkpoints = new Checkpoints(this, context);
this.corporateActions = new CorporateActions(this, context);
this.permissions = new Permissions(this, context);
this.transferOwnership = createProcedureMethod(
{ getProcedureAndArgs: args => [transferTokenOwnership, { ticker, ...args }] },
context
);
this.modify = createProcedureMethod(
{ getProcedureAndArgs: args => [modifyToken, { ticker, ...args }] },
context
);
this.freeze = createProcedureMethod(
{ getProcedureAndArgs: () => [toggleFreezeTransfers, { ticker, freeze: true }] },
context
);
this.unfreeze = createProcedureMethod(
{ getProcedureAndArgs: () => [toggleFreezeTransfers, { ticker, freeze: false }] },
context
);
this.modifyPrimaryIssuanceAgent = createProcedureMethod(
{ getProcedureAndArgs: args => [modifyPrimaryIssuanceAgent, { ticker, ...args }] },
context
);
this.removePrimaryIssuanceAgent = createProcedureMethod(
{ getProcedureAndArgs: () => [removePrimaryIssuanceAgent, { ticker }] },
context
);
this.redeem = createProcedureMethod(
{ getProcedureAndArgs: args => [redeemToken, { ticker, ...args }] },
context
);
this.controllerTransfer = createProcedureMethod(
{ getProcedureAndArgs: args => [controllerTransfer, { ticker, ...args }] },
context
);
}
/**
* Transfer ownership of the Security Token to another Identity. This generates an authorization request that must be accepted
* by the destinatary
*
* @note this will create [[AuthorizationRequest | Authorization Requests]] which have to be accepted by
* the corresponding [[Account | Accounts]] and/or [[Identity | Identities]]. An Account or Identity can
* fetch its pending Authorization Requests by calling `authorizations.getReceived`
*
* @note required role:
* - Security Token Owner
*/
public transferOwnership: ProcedureMethod<TransferTokenOwnershipParams, SecurityToken>;
/**
* Modify some properties of the Security Token
*
* @throws if the passed values result in no changes being made to the token
*
* @note required role:
* - Security Token Owner
*/
public modify: ProcedureMethod<ModifyTokenParams, SecurityToken>;
/**
* Retrieve the Security Token's name, total supply, whether it is divisible or not and the Identity of the owner
*
* @note can be subscribed to
*/
public details(): Promise<SecurityTokenDetails>;
public details(callback: SubCallback<SecurityTokenDetails>): Promise<UnsubCallback>;
// eslint-disable-next-line require-jsdoc
public async details(
callback?: SubCallback<SecurityTokenDetails>
): Promise<SecurityTokenDetails | UnsubCallback> {
const {
context: {
polymeshApi: {
query: { asset, externalAgents },
},
},
ticker,
context,
} = this;
/* eslint-disable @typescript-eslint/naming-convention */
const assembleResult = (
{ total_supply, divisible, owner_did, asset_type }: MeshSecurityToken,
agentGroups: [StorageKey<[Ticker, IdentityId]>, Option<AgentGroup>][]
): SecurityTokenDetails => {
const primaryIssuanceAgents: Identity[] = [];
const fullAgents: Identity[] = [];
agentGroups.forEach(([storageKey, agentGroup]) => {
const rawAgentGroup = agentGroup.unwrap();
if (rawAgentGroup.isPolymeshV1Pia) {
primaryIssuanceAgents.push(
new Identity({ did: identityIdToString(storageKey.args[1]) }, context)
);
} else if (rawAgentGroup.isFull) {
fullAgents.push(new Identity({ did: identityIdToString(storageKey.args[1]) }, context));
}
});
const owner = new Identity({ did: identityIdToString(owner_did) }, context);
return {
assetType: assetTypeToString(asset_type),
isDivisible: boolToBoolean(divisible),
name: 'placeholder',
owner,
totalSupply: balanceToBigNumber(total_supply),
primaryIssuanceAgents,
fullAgents,
};
};
/* eslint-enable @typescript-eslint/naming-convention */
const rawTicker = stringToTicker(ticker, context);
const groupOfAgentPromise = externalAgents.groupOfAgent.entries(rawTicker);
if (callback) {
const groupOfAgents = await groupOfAgentPromise;
return asset.tokens(rawTicker, securityToken => {
callback(assembleResult(securityToken, groupOfAgents));
});
}
const [token, groupOfAgent] = await Promise.all([asset.tokens(rawTicker), groupOfAgentPromise]);
return assembleResult(token, groupOfAgent);
}
/**
* Retrieve the Security Token's funding round
*
* @note can be subscribed to
*/
public currentFundingRound(): Promise<string>;
public currentFundingRound(callback: SubCallback<string>): Promise<UnsubCallback>;
// eslint-disable-next-line require-jsdoc
public async currentFundingRound(
callback?: SubCallback<string>
): Promise<string | UnsubCallback> {
const {
context: {
polymeshApi: {
query: { asset },
},
},
ticker,
context,
} = this;
const rawTicker = stringToTicker(ticker, context);
if (callback) {
return asset.fundingRound(rawTicker, round => {
callback(fundingRoundNameToString(round));
});
}
const fundingRound = await asset.fundingRound(rawTicker);
return fundingRoundNameToString(fundingRound);
}
/**
* Retrieve the Security Token's asset identifiers list
*
* @note can be subscribed to
*/
public getIdentifiers(): Promise<TokenIdentifier[]>;
public getIdentifiers(callback?: SubCallback<TokenIdentifier[]>): Promise<UnsubCallback>;
// eslint-disable-next-line require-jsdoc
public async getIdentifiers(
callback?: SubCallback<TokenIdentifier[]>
): Promise<TokenIdentifier[] | UnsubCallback> {
const {
context: {
polymeshApi: {
query: { asset },
},
},
ticker,
context,
} = this;
const rawTicker = stringToTicker(ticker, context);
if (callback) {
return asset.identifiers(rawTicker, identifiers => {
callback(identifiers.map(assetIdentifierToTokenIdentifier));
});
}
const assetIdentifiers = await asset.identifiers(rawTicker);
return assetIdentifiers.map(assetIdentifierToTokenIdentifier);
}
/**
* Retrieve the identifier data (block number, date and event index) of the event that was emitted when the token was created
*
* @note uses the middleware
* @note there is a possibility that the data is not ready by the time it is requested. In that case, `null` is returned
*/
public async createdAt(): Promise<EventIdentifier | null> {
const { ticker, context } = this;
const {
data: { eventByIndexedArgs: event },
} = await context.queryMiddleware<Ensured<Query, 'eventByIndexedArgs'>>(
eventByIndexedArgs({
moduleId: ModuleIdEnum.Asset,
eventId: EventIdEnum.AssetCreated,
eventArg1: padString(ticker, MAX_TICKER_LENGTH),
})
);
return optionize(middlewareEventToEventIdentifier)(event);
}
/**
* Freezes transfers and minting of the Security Token
*
* @note required role:
* - Security Token Owner
*/
public freeze: ProcedureMethod<void, SecurityToken>;
/**
* Unfreeze transfers and minting of the Security Token
*
* @note required role:
* - Security Token Owner
*/
public unfreeze: ProcedureMethod<void, SecurityToken>;
/**
* Check whether transfers are frozen for the Security Token
*
* @note can be subscribed to
*/
public isFrozen(): Promise<boolean>;
public isFrozen(callback: SubCallback<boolean>): Promise<UnsubCallback>;
// eslint-disable-next-line require-jsdoc
public async isFrozen(callback?: SubCallback<boolean>): Promise<boolean | UnsubCallback> {
const {
ticker,
context: {
polymeshApi: {
query: { asset },
},
},
context,
} = this;
const rawTicker = stringToTicker(ticker, context);
if (callback) {
return asset.frozen(rawTicker, frozen => {
callback(boolToBoolean(frozen));
});
}
const result = await asset.frozen(rawTicker);
return boolToBoolean(result);
}
/**
* Assign a new primary issuance agent for the Security Token
*
* @note this may create AuthorizationRequest which have to be accepted by
* the corresponding Account. An Account or Identity can
* fetch its pending Authorization Requests by calling `authorizations.getReceived`
*
* @note required role:
* - Security Token Owner
*
* @deprecated in favor of `inviteAgent`
*/
public modifyPrimaryIssuanceAgent: ProcedureMethod<ModifyPrimaryIssuanceAgentParams, void>;
/**
* Remove the primary issuance agent of the Security Token
*
* @note if primary issuance agent is not set, Security Token owner would be used by default
*
* @note required role:
* - Security Token Owner
*
* @deprecated
*/
public removePrimaryIssuanceAgent: ProcedureMethod<void, void>;
/**
* Redeem (burn) an amount of this Security Token
*
* @note Tokens are removed from the Primary Issuance Agent's Default Portfolio.
* If the Security Token has no Primary Issuance Agent, funds are removed from the owner's
* Default Portfolio instead
*
* @note required role:
* - Security Token Primary Issuance Agent
*/
public redeem: ProcedureMethod<RedeemTokenParams, void>;
/**
* Retrieve the amount of unique investors that hold this Security Token
*
* @note this takes into account the Scope ID of Investor Uniqueness Claims. If an investor holds balances
* of this token in two or more different Identities, but they all have Investor Uniqueness Claims with the same
* Scope ID, then they will only be counted once for the purposes of this result
*
* @note can be subscribed to
*/
public investorCount(): Promise<number>;
public investorCount(callback: SubCallback<number>): Promise<UnsubCallback>;
// eslint-disable-next-line require-jsdoc
public async investorCount(callback?: SubCallback<number>): Promise<number | UnsubCallback> {
const {
context: {
polymeshApi: {
query: { statistics },
},
},
context,
ticker,
} = this;
const rawTicker = stringToTicker(ticker, context);
const assembleResult = (value: Counter): number => u64ToBigNumber(value).toNumber();
if (callback) {
return statistics.investorCountPerAsset(rawTicker, count => {
callback(assembleResult(count));
});
}
const result = await statistics.investorCountPerAsset(stringToTicker(ticker, context));
return u64ToBigNumber(result).toNumber();
}
/**
* Force a transfer from a given Portfolio to the PIA’s default Portfolio
*
* @note required role:
* - Security Token Primary Issuance Agent
*/
public controllerTransfer: ProcedureMethod<ControllerTransferParams, void>;
/**
* Return the Token's ticker
*/
public toJson(): string {
return this.ticker;
}
}