generated from PolymeshAssociation/typescript-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.ts
566 lines (488 loc) · 14.8 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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
import { ApiPromise, Keyring } from '@polkadot/api';
import { getTypeDef } from '@polkadot/types';
import { AccountInfo } from '@polkadot/types/interfaces';
import { CallBase, TypeDef, TypeDefInfo } from '@polkadot/types/types';
import stringToU8a from '@polkadot/util/string/toU8a';
import { NormalizedCacheObject } from 'apollo-cache-inmemory';
import ApolloClient from 'apollo-client';
import BigNumber from 'bignumber.js';
import { polymesh } from 'polymesh-types/definitions';
import { DidRecord, IdentityId, ProtocolOp, TxTag } from 'polymesh-types/types';
import { Identity } from '~/api/entities';
import { PolymeshError } from '~/base';
import {
AccountBalance,
ArrayTransactionArgument,
CommonKeyring,
ComplexTransactionArgument,
ErrorCode,
KeyringPair,
PlainTransactionArgument,
Signer,
SimpleEnumTransactionArgument,
SubCallback,
TransactionArgument,
TransactionArgumentType,
UnsubCallback,
} from '~/types';
import {
balanceToBigNumber,
identityIdToString,
posRatioToBigNumber,
signatoryToSigner,
stringToAccountKey,
stringToIdentityId,
textToString,
txTagToProtocolOp,
valueToDid,
} from '~/utils';
import { ROOT_TYPES } from '~/utils/constants';
interface SignerData {
currentPair: KeyringPair;
did: IdentityId;
}
interface ConstructorParams {
polymeshApi: ApiPromise;
middlewareApi: ApolloClient<NormalizedCacheObject> | null;
keyring: CommonKeyring;
pair?: SignerData;
}
interface AccountData {
address: string;
name?: string;
}
/**
* Context in which the SDK is being used
*
* - Holds the current low level API
* - Holds the current keyring pair
* - Holds the current Identity
*/
export class Context {
private keyring: CommonKeyring;
public polymeshApi: ApiPromise;
public currentPair?: KeyringPair;
private currentIdentity?: Identity;
private _middlewareApi: ApolloClient<NormalizedCacheObject> | null;
/**
* @hidden
*/
private constructor(params: ConstructorParams) {
const { polymeshApi, middlewareApi, keyring, pair } = params;
this._middlewareApi = middlewareApi;
this.polymeshApi = new Proxy(polymeshApi, {
get: (target, prop: keyof ApiPromise): ApiPromise[keyof ApiPromise] => {
if (prop === 'tx' && !this.currentPair) {
throw new PolymeshError({
code: ErrorCode.FatalError,
message: 'Cannot perform transactions without an active account',
});
}
return target[prop];
},
});
this.keyring = keyring;
if (pair) {
this.currentPair = pair.currentPair;
this.currentIdentity = new Identity({ did: pair.did.toString() }, this);
}
}
static async create(params: {
polymeshApi: ApiPromise;
middlewareApi: ApolloClient<NormalizedCacheObject> | null;
seed: string;
}): Promise<Context>;
static async create(params: {
polymeshApi: ApiPromise;
middlewareApi: ApolloClient<NormalizedCacheObject> | null;
keyring: CommonKeyring;
}): Promise<Context>;
static async create(params: {
polymeshApi: ApiPromise;
middlewareApi: ApolloClient<NormalizedCacheObject> | null;
uri: string;
}): Promise<Context>;
static async create(params: {
polymeshApi: ApiPromise;
middlewareApi: ApolloClient<NormalizedCacheObject> | null;
}): Promise<Context>;
/**
* Create the Context instance
*/
static async create(params: {
polymeshApi: ApiPromise;
middlewareApi: ApolloClient<NormalizedCacheObject> | null;
seed?: string;
keyring?: CommonKeyring;
uri?: string;
}): Promise<Context> {
const { polymeshApi, middlewareApi, seed, keyring: passedKeyring, uri } = params;
let keyring: CommonKeyring = new Keyring({ type: 'sr25519' });
let currentPair: KeyringPair | undefined;
if (passedKeyring) {
keyring = passedKeyring;
currentPair = keyring.getPairs()[0];
} else if (seed) {
if (seed.length !== 32) {
throw new PolymeshError({
code: ErrorCode.ValidationError,
message: 'Seed must be 32 characters in length',
});
}
currentPair = keyring.addFromSeed(stringToU8a(seed));
} else if (uri) {
currentPair = keyring.addFromUri(uri);
}
if (currentPair) {
try {
const identityIds = await polymeshApi.query.identity.keyToIdentityIds(
currentPair.publicKey
);
const did = identityIds.unwrap().asUnique;
return new Context({
polymeshApi,
middlewareApi,
keyring,
pair: { currentPair, did },
});
} catch (err) {
throw new PolymeshError({
code: ErrorCode.IdentityNotPresent,
message: 'There is no Identity associated to this account',
});
}
}
return new Context({ polymeshApi, middlewareApi, keyring });
}
/**
* Retrieve a list of addresses associated with the account
*/
public getAccounts(): Array<AccountData> {
const { keyring } = this;
return keyring.getPairs().map(({ address, meta }) => {
return { address, name: meta.name as string };
});
}
/**
* Set a pair as the current account keyring pair
*/
public async setPair(address: string): Promise<void> {
const {
keyring,
polymeshApi: {
query: { identity },
},
} = this;
let newCurrentPair;
let identityIds;
let did;
try {
newCurrentPair = keyring.getPair(address);
} catch (e) {
throw new PolymeshError({
code: ErrorCode.FatalError,
message: 'The address is not present in the keyring set',
});
}
try {
identityIds = await identity.keyToIdentityIds(
stringToAccountKey(newCurrentPair.address, this)
);
did = identityIds.unwrap().asUnique;
} catch (e) {
throw new PolymeshError({
code: ErrorCode.IdentityNotPresent,
message: 'There is no Identity associated to this account',
});
}
this.currentPair = newCurrentPair;
this.currentIdentity = new Identity({ did: identityIdToString(did) }, this);
}
public accountBalance(accountId?: string): Promise<AccountBalance>;
public accountBalance(
accountId: string | undefined,
callback: SubCallback<AccountBalance>
): Promise<UnsubCallback>;
/**
* Retrieve the account level POLYX balance
*
* @note can be subscribed to
*/
public async accountBalance(
accountId?: string,
callback?: SubCallback<AccountBalance>
): Promise<AccountBalance | UnsubCallback> {
const {
currentPair,
polymeshApi: {
query: { system },
},
} = this;
let address: string;
if (accountId) {
address = accountId;
} else if (currentPair) {
address = currentPair.address;
} else {
throw new PolymeshError({
code: ErrorCode.FatalError,
message: 'There is no account associated with the SDK',
});
}
const assembleResult = ({
data: { free, miscFrozen, feeFrozen },
}: AccountInfo): AccountBalance => {
return {
free: balanceToBigNumber(free),
locked: BigNumber.max(balanceToBigNumber(miscFrozen), balanceToBigNumber(feeFrozen)),
};
};
if (callback) {
return system.account(address, info => {
callback(assembleResult(info));
});
}
const accountInfo = await this.polymeshApi.query.system.account(address);
return assembleResult(accountInfo);
}
/**
* Retrieve current Identity
*
* @throws if there is no identity associated to the current account (or there is no current account associated to the SDK instance)
*/
public getCurrentIdentity(): Identity {
const { currentIdentity } = this;
if (!currentIdentity) {
throw new PolymeshError({
code: ErrorCode.IdentityNotPresent,
message: 'The current account does not have an associated identity',
});
}
return currentIdentity;
}
/**
* Retrieve current Keyring Pair
*
* @throws if there is no account associated to the SDK instance
*/
public getCurrentPair(): KeyringPair {
const { currentPair } = this;
if (!currentPair) {
throw new PolymeshError({
code: ErrorCode.FatalError,
message: 'There is no account associated with the current SDK instance',
});
}
return currentPair;
}
/**
* Check whether identities exist
*/
public async getInvalidDids(identities: (string | Identity)[]): Promise<string[]> {
const dids = identities.map(valueToDid);
const rawIdentities = dids.map(did => stringToIdentityId(did, this));
const records = await this.polymeshApi.query.identity.didRecords.multi<DidRecord>(
rawIdentities
);
const invalidDids: string[] = [];
records.forEach((record, index) => {
if (record.isEmpty) {
invalidDids.push(dids[index]);
}
});
return invalidDids;
}
/**
* Retrieve the protocol fees associated with running a specific transaction
*
* @param tag - transaction tag (i.e. TxTags.asset.CreateAsset or "asset.createAsset")
*/
public async getTransactionFees(tag: TxTag): Promise<BigNumber> {
const {
polymeshApi: {
query: { protocolFee },
},
} = this;
let protocolOp: ProtocolOp;
try {
protocolOp = txTagToProtocolOp(tag, this);
} catch (err) {
return new BigNumber(0);
}
const [baseFee, coefficient] = await Promise.all([
protocolFee.baseFees(protocolOp),
protocolFee.coefficient(),
]);
return balanceToBigNumber(baseFee).multipliedBy(posRatioToBigNumber(coefficient));
}
/**
* Retrieve the types of arguments that a certain transaction requires to be run
*
* @param args.tag - tag associated with the transaction that will be executed if the proposal passes
*/
public getTransactionArguments(args: { tag: TxTag }): TransactionArgument[] {
const {
polymeshApi: { tx },
} = this;
const { types } = polymesh;
const [section, method] = args.tag.split('.');
const getRootType = (
type: string
):
| PlainTransactionArgument
| ArrayTransactionArgument
| SimpleEnumTransactionArgument
| ComplexTransactionArgument => {
const rootType = ROOT_TYPES[type];
if (rootType) {
return {
type: rootType,
};
}
if (type === 'Null') {
return {
type: TransactionArgumentType.Null,
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const definition = (types as any)[type];
if (!definition) {
return {
type: TransactionArgumentType.Unknown,
};
}
const typeDef = getTypeDef(JSON.stringify(definition));
if (typeDef.info === TypeDefInfo.Plain) {
return getRootType(definition);
}
// eslint-disable-next-line @typescript-eslint/no-use-before-define
return processType(typeDef, '');
};
const processType = (rawType: TypeDef, name: string): TransactionArgument => {
const { type, info, sub } = rawType;
const arg = {
name,
optional: false,
_rawType: rawType,
};
switch (info) {
case TypeDefInfo.Plain: {
return {
...getRootType(type),
...arg,
};
}
case TypeDefInfo.Compact: {
return {
...processType(sub as TypeDef, name),
...arg,
};
}
case TypeDefInfo.Option: {
return {
...processType(sub as TypeDef, name),
...arg,
optional: true,
};
}
case TypeDefInfo.Tuple: {
return {
type: TransactionArgumentType.Tuple,
...arg,
internal: (sub as TypeDef[]).map((def, index) => processType(def, `${index}`)),
};
}
case TypeDefInfo.Vec: {
return {
type: TransactionArgumentType.Array,
...arg,
internal: processType(sub as TypeDef, ''),
};
}
case TypeDefInfo.VecFixed: {
return {
type: TransactionArgumentType.Text,
...arg,
};
}
case TypeDefInfo.Enum: {
const subTypes = sub as TypeDef[];
const isSimple = subTypes.every(({ type: subType }) => subType === 'Null');
if (isSimple) {
return {
type: TransactionArgumentType.SimpleEnum,
...arg,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
internal: subTypes.map(({ name: subName }) => subName!),
};
}
return {
type: TransactionArgumentType.RichEnum,
...arg,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
internal: subTypes.map(def => processType(def, def.name!)),
};
}
case TypeDefInfo.Struct: {
return {
type: TransactionArgumentType.Object,
...arg,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
internal: (sub as TypeDef[]).map(def => processType(def, def.name!)),
};
}
default: {
return {
type: TransactionArgumentType.Unknown,
...arg,
};
}
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return ((tx as any)[section][method] as CallBase).meta.args.map(({ name, type }) => {
const typeDef = getTypeDef(type.toString());
const argName = textToString(name);
return processType(typeDef, argName);
});
}
/**
* Retrieve the list of signing keys related to the account
*
* @note can be subscribed to
*/
public async getSigningKeys(): Promise<Signer[]>;
public async getSigningKeys(callback: SubCallback<Signer[]>): Promise<UnsubCallback>;
// eslint-disable-next-line require-jsdoc
public async getSigningKeys(callback?: SubCallback<Signer[]>): Promise<Signer[] | UnsubCallback> {
const {
polymeshApi: {
query: { identity },
},
} = this;
const { did } = this.getCurrentIdentity();
const assembleResult = ({ signing_items: signingItems }: DidRecord): Signer[] => {
return signingItems.map(({ signer: rawSigner }) => signatoryToSigner(rawSigner));
};
if (callback) {
return identity.didRecords(did, records => callback(assembleResult(records)));
}
const didRecords = await identity.didRecords(did);
return assembleResult(didRecords);
}
/**
* Retrieve the middleware client
*
* @throws if credentials are not set
*/
public get middlewareApi(): ApolloClient<NormalizedCacheObject> {
const { _middlewareApi } = this;
if (!_middlewareApi) {
throw new PolymeshError({
code: ErrorCode.FatalError,
message: 'Cannot perform this action without an active middleware connection',
});
}
return _middlewareApi;
}
}