generated from PolymeshAssociation/typescript-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.ts
368 lines (321 loc) · 10.9 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
import BigNumber from 'bignumber.js';
import { SecurityToken as MeshSecurityToken } from 'polymesh-types/types';
import { redeemToken, RedeemTokenParams } from '~/api/procedures/redeemToken';
import {
Context,
Entity,
Identity,
modifyPrimaryIssuanceAgent,
ModifyPrimaryIssuanceAgentParams,
modifyToken,
ModifyTokenParams,
removePrimaryIssuanceAgent,
toggleFreezeTransfers,
TransactionQueue,
transferTokenOwnership,
TransferTokenOwnershipParams,
} from '~/internal';
import { eventByIndexedArgs } from '~/middleware/queries';
import { EventIdEnum, ModuleIdEnum, Query } from '~/middleware/types';
import { Ensured, EventIdentifier, SubCallback, TokenIdentifier, UnsubCallback } from '~/types';
import { MAX_TICKER_LENGTH } from '~/utils/constants';
import {
assetIdentifierToTokenIdentifier,
assetNameToString,
assetTypeToString,
balanceToBigNumber,
boolToBoolean,
fundingRoundNameToString,
identityIdToString,
stringToTicker,
tickerToDid,
} from '~/utils/conversion';
import { padString } from '~/utils/internal';
import { Compliance } from './Compliance';
import { Documents } from './Documents';
import { Issuance } from './Issuance';
import { Settlements } from './Settlements';
import { TokenHolders } from './TokenHolders';
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> {
/**
* @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;
/**
* @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);
}
/**
* Transfer ownership of the Security Token to another Identity. This generates an authorization request that must be accepted
* by the destinatary
*
* @param args.expiry - date at which the authorization request for transfer expires (optional)
*
* @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`
*/
public transferOwnership(
args: TransferTokenOwnershipParams
): Promise<TransactionQueue<SecurityToken>> {
const { ticker } = this;
return transferTokenOwnership.prepare({ ticker, ...args }, this.context);
}
/**
* Modify some properties of the Security Token
*
* @param args.makeDivisible - makes an indivisible token divisible
* @throws if the passed values result in no changes being made to the token
*/
public modify(args: ModifyTokenParams): Promise<TransactionQueue<SecurityToken>> {
const { ticker } = this;
return modifyToken.prepare({ ticker, ...args }, this.context);
}
/**
* 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 },
},
},
ticker,
context,
} = this;
/* eslint-disable @typescript-eslint/camelcase */
const assembleResult = ({
name,
total_supply,
divisible,
owner_did,
asset_type,
primary_issuance_agent,
}: MeshSecurityToken): SecurityTokenDetails => ({
assetType: assetTypeToString(asset_type),
isDivisible: boolToBoolean(divisible),
name: assetNameToString(name),
owner: new Identity({ did: identityIdToString(owner_did) }, context),
totalSupply: balanceToBigNumber(total_supply),
primaryIssuanceAgent: primary_issuance_agent.isSome
? new Identity({ did: identityIdToString(primary_issuance_agent.unwrap()) }, context)
: null,
});
/* eslint-enable @typescript-eslint/camelcase */
const rawTicker = stringToTicker(ticker, context);
if (callback) {
return asset.tokens(rawTicker, securityToken => {
callback(assembleResult(securityToken));
});
}
const token = await asset.tokens(rawTicker);
return assembleResult(token);
}
/**
* 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);
}
/**
* Retrive 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 result = await context.queryMiddleware<Ensured<Query, 'eventByIndexedArgs'>>(
eventByIndexedArgs({
moduleId: ModuleIdEnum.Asset,
eventId: EventIdEnum.AssetCreated,
eventArg1: padString(ticker, MAX_TICKER_LENGTH),
})
);
if (result.data.eventByIndexedArgs) {
// TODO remove null check once types fixed
return {
blockNumber: new BigNumber(result.data.eventByIndexedArgs.block_id),
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
blockDate: result.data.eventByIndexedArgs.block!.datetime,
eventIndex: result.data.eventByIndexedArgs.event_idx,
};
}
return null;
}
/**
* Freezes transfers and minting of the Security Token
*/
public freeze(): Promise<TransactionQueue<SecurityToken>> {
const { ticker, context } = this;
return toggleFreezeTransfers.prepare({ ticker, freeze: true }, context);
}
/**
* Unfreeze transfers and minting of the Security Token
*/
public unfreeze(): Promise<TransactionQueue<SecurityToken>> {
const { ticker, context } = this;
return toggleFreezeTransfers.prepare({ ticker, freeze: false }, context);
}
/**
* 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
*
* @param args.target - identity to be set as primary issuance agent
* @param args.requestExpiry - date at which the authorization request to modify the primary issuance agent expires (optional, never expires if a date is not provided)
*
* @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`
*/
public modifyPrimaryIssuanceAgent(
args: ModifyPrimaryIssuanceAgentParams
): Promise<TransactionQueue<void>> {
const { ticker, context } = this;
return modifyPrimaryIssuanceAgent.prepare({ ticker, ...args }, context);
}
/**
* 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
*/
public removePrimaryIssuanceAgent(): Promise<TransactionQueue<void>> {
const { ticker, context } = this;
return removePrimaryIssuanceAgent.prepare({ ticker }, context);
}
/**
* Redeem the Security Tokens
*/
public redeem(args: RedeemTokenParams): Promise<TransactionQueue<void>> {
const { ticker, context } = this;
const { balance } = args;
return redeemToken.prepare({ ticker, balance }, context);
}
}