generated from PolymeshAssociation/typescript-boilerplate
/
internal.ts
1063 lines (958 loc) · 28.1 KB
/
internal.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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
AugmentedEvent,
AugmentedQuery,
AugmentedQueryDoubleMap,
DropLast,
ObsInnerType,
} from '@polkadot/api/types';
import { StorageKey } from '@polkadot/types';
import { BlockHash } from '@polkadot/types/interfaces/chain';
import { AnyFunction, AnyTuple, IEvent, ISubmittableResult } from '@polkadot/types/types';
import { stringUpperFirst } from '@polkadot/util';
import { decodeAddress, encodeAddress } from '@polkadot/util-crypto';
import BigNumber from 'bignumber.js';
import P from 'bluebird';
import stringify from 'json-stable-stringify';
import { differenceWith, flatMap, isEqual, mapValues, noop, padEnd, uniq } from 'lodash';
import {
IdentityId,
ModuleName,
PortfolioName,
PortfolioNumber,
TxTag,
} from 'polymesh-types/types';
import { satisfies } from 'semver';
import { w3cwebsocket as W3CWebSocket } from 'websocket';
import {
Asset,
Checkpoint,
CheckpointSchedule,
Context,
Identity,
PolymeshError,
PostTransactionValue,
TransactionQueue,
} from '~/internal';
import { Scope as MiddlewareScope } from '~/middleware/types';
import {
CaCheckpointType,
CalendarPeriod,
CalendarUnit,
Claim,
ClaimType,
Condition,
ConditionType,
CountryCode,
ErrorCode,
InputCaCheckpoint,
InputCondition,
NextKey,
NoArgsProcedureMethod,
PaginationOptions,
ProcedureAuthorizationStatus,
ProcedureMethod,
ProcedureOpts,
Scope,
} from '~/types';
import {
Events,
Falsyable,
MapMaybePostTransactionValue,
MapTxWithArgs,
MaybePostTransactionValue,
PolymeshTx,
TxWithArgs,
} from '~/types/internal';
import { HumanReadableType, ProcedureFunc, UnionOfProcedureFuncs } from '~/types/utils';
import {
DEFAULT_GQL_PAGE_SIZE,
SUPPORTED_VERSION_RANGE,
SYSTEM_VERSION_RPC_CALL,
} from '~/utils/constants';
import {
bigNumberToU64,
middlewareScopeToScope,
signerToString,
u64ToBigNumber,
} from '~/utils/conversion';
import { isEntity, isMultiClaimCondition, isSingleClaimCondition } from '~/utils/typeguards';
export * from '~/generated/utils';
/**
* @hidden
* Promisified version of a timeout
*
* @param amount - time to wait
*/
export async function delay(amount: number): Promise<void> {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, amount);
});
}
/**
* @hidden
* Convert an entity type and its unique Identifiers to a base64 string
*/
export function serialize<UniqueIdentifiers>(
entityType: string,
uniqueIdentifiers: UniqueIdentifiers
): string {
return Buffer.from(`${entityType}:${stringify(uniqueIdentifiers)}`).toString('base64');
}
/**
* @hidden
* Convert a uuid string to an Identifier object
*/
export function unserialize<UniqueIdentifiers>(id: string): UniqueIdentifiers {
const unserialized = Buffer.from(id, 'base64').toString('utf8');
const matched = unserialized.match(/^.*?:(.*)/);
const errorMsg = 'Wrong ID format';
if (!matched) {
throw new Error(errorMsg);
}
const [, jsonString] = matched;
try {
return JSON.parse(jsonString);
} catch (err) {
throw new Error(errorMsg);
}
}
/**
* @hidden
* Extract the DID from an Identity, or return the DID of the signing Identity if no Identity is passed
*/
export async function getDid(
value: string | Identity | undefined,
context: Context
): Promise<string> {
let did;
if (value) {
did = signerToString(value);
} else {
({ did } = await context.getSigningIdentity());
}
return did;
}
/**
* @hidden
* Given a DID return the corresponding Identity, given an Identity return the Identity
*/
export function asIdentity(value: string | Identity, context: Context): Identity {
return typeof value === 'string' ? new Identity({ did: value }, context) : value;
}
/**
* @hidden
* DID | Identity -> DID
*/
export function asDid(value: string | Identity): string {
return typeof value === 'string' ? value : value.did;
}
/**
* @hidden
* Given an Identity, return the Identity, given a DID returns the corresponding Identity, if value is falsy, then return currentIdentity
*/
export async function getIdentity(
value: string | Identity | undefined,
context: Context
): Promise<Identity> {
if (!value) {
return context.getSigningIdentity();
} else {
return asIdentity(value, context);
}
}
/**
* @hidden
*/
export function createClaim(
claimType: string,
jurisdiction: Falsyable<string>,
middlewareScope: Falsyable<MiddlewareScope>,
cddId: Falsyable<string>,
scopeId: Falsyable<string>
): Claim {
const type = claimType as ClaimType;
const scope = (middlewareScope ? middlewareScopeToScope(middlewareScope) : {}) as Scope;
switch (type) {
case ClaimType.Jurisdiction: {
return {
type,
// this assertion is necessary because CountryCode is not in the middleware types
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
code: stringUpperFirst(jurisdiction!.toLowerCase()) as CountryCode,
scope,
};
}
case ClaimType.NoData: {
return {
type,
};
}
case ClaimType.CustomerDueDiligence: {
return {
type,
id: cddId as string,
};
}
case ClaimType.InvestorUniqueness: {
return {
type,
scope,
scopeId: scopeId as string,
cddId: cddId as string,
};
}
case ClaimType.InvestorUniquenessV2: {
return {
type,
cddId: cddId as string,
};
}
}
return { type, scope };
}
/**
* @hidden
*
* Unwrap a Post Transaction Value
*/
export function unwrapValue<T>(value: MaybePostTransactionValue<T>): T {
if (value instanceof PostTransactionValue) {
return value.value;
}
return value;
}
/**
* @hidden
*
* Unwrap all Post Transaction Values present in a tuple
*/
export function unwrapValues<T extends unknown[]>(values: MapMaybePostTransactionValue<T>): T {
return values.map(unwrapValue) as T;
}
/**
* @hidden
*/
type EventData<Event> = Event extends AugmentedEvent<'promise', infer Data> ? Data : never;
/**
* @hidden
* Find every occurrence of a specific event inside a receipt
*
* @throws If the event is not found
*/
export function filterEventRecords<
ModuleName extends keyof Events,
EventName extends keyof Events[ModuleName]
>(
receipt: ISubmittableResult,
mod: ModuleName,
eventName: EventName
): IEvent<EventData<Events[ModuleName][EventName]>>[] {
const eventRecords = receipt.filterRecords(mod, eventName as string);
if (!eventRecords.length) {
throw new PolymeshError({
code: ErrorCode.UnexpectedError,
message: `Event "${mod}.${eventName}" wasn't fired even though the corresponding transaction was completed. Please report this to the Polymath team`,
});
}
return eventRecords.map(
eventRecord => eventRecord.event as unknown as IEvent<EventData<Events[ModuleName][EventName]>>
);
}
/**
* @hidden
*/
export function padString(value: string, length: number): string {
return padEnd(value, length, '\0');
}
/**
* @hidden
*/
export function removePadding(value: string): string {
// eslint-disable-next-line no-control-regex
return value.replace(/\u0000/g, '');
}
/**
* @hidden
*
* Return whether the string is fully printable ASCII
*/
export function isPrintableAscii(value: string): boolean {
// eslint-disable-next-line no-control-regex
return /^[\x00-\x7F]*$/.test(value);
}
/**
* @hidden
*
* Makes an entries request to the chain. If pagination options are supplied,
* the request will be paginated. Otherwise, all entries will be requested at once
*/
export async function requestPaginated<F extends AnyFunction, T extends AnyTuple>(
query: AugmentedQuery<'promise', F, T> | AugmentedQueryDoubleMap<'promise', F, T>,
opts: {
paginationOpts?: PaginationOptions;
arg?: Parameters<F>[0];
}
): Promise<{
entries: [StorageKey<T>, ObsInnerType<ReturnType<F>>][];
lastKey: NextKey;
}> {
const { arg, paginationOpts } = opts;
let entries: [StorageKey<T>, ObsInnerType<ReturnType<F>>][];
let lastKey: NextKey = null;
const args = arg ? [arg] : [];
if (paginationOpts) {
const { size: pageSize, start: startKey } = paginationOpts;
entries = await query.entriesPaged({
args,
pageSize: pageSize.toNumber(),
startKey,
});
if (pageSize.eq(entries.length)) {
lastKey = entries[entries.length - 1][0].toHex();
}
} else {
/*
* NOTE @monitz87: this assertion is required because types
* are inconsistent in the polkadot repo
*/
entries = await query.entries(...(args as DropLast<Parameters<F>>));
}
return {
entries,
lastKey,
};
}
/**
* @hidden
*
* Makes a request to the chain. If a block hash is supplied,
* the request will be made at that block. Otherwise, the most recent block will be queried
*/
export async function requestAtBlock<F extends AnyFunction>(
query: AugmentedQuery<'promise', F> | AugmentedQueryDoubleMap<'promise', F>,
opts: {
blockHash?: string | BlockHash;
args: Parameters<F>;
},
context: Context
): Promise<ObsInnerType<ReturnType<F>>> {
const { blockHash, args } = opts;
if (blockHash) {
if (!context.isArchiveNode) {
throw new PolymeshError({
code: ErrorCode.DataUnavailable,
message: 'Cannot query previous blocks in a non-archive node',
});
}
return query.at(blockHash, ...args);
}
return query(...args);
}
/**
* @hidden
*
* Calculates next page number for paginated GraphQL ResultSet.
* Returns null if there is no next page.
*
* @param size - page size requested
* @param start - start index requested
* @param totalCount - total amount of elements returned by query
*
* @hidden
*
*/
export function calculateNextKey(
totalCount: BigNumber,
size?: BigNumber,
start?: BigNumber
): NextKey {
const next = (start ?? new BigNumber(0)).plus(size ?? DEFAULT_GQL_PAGE_SIZE);
return totalCount.gt(next) ? next : null;
}
/**
* Create a method that prepares a procedure
*/
export function createProcedureMethod<
ProcedureArgs,
ProcedureReturnValue,
Storage = Record<string, unknown>
>(
args: {
getProcedureAndArgs: () => [
(
| UnionOfProcedureFuncs<ProcedureArgs, ProcedureReturnValue, Storage>
| ProcedureFunc<ProcedureArgs, ProcedureReturnValue, Storage>
),
ProcedureArgs
];
voidArgs: true;
},
context: Context
): NoArgsProcedureMethod<ProcedureReturnValue, ProcedureReturnValue>;
export function createProcedureMethod<
ProcedureArgs,
ProcedureReturnValue,
ReturnValue,
Storage = Record<string, unknown>
>(
args: {
getProcedureAndArgs: () => [
(
| UnionOfProcedureFuncs<ProcedureArgs, ProcedureReturnValue, Storage>
| ProcedureFunc<ProcedureArgs, ProcedureReturnValue, Storage>
),
ProcedureArgs
];
voidArgs: true;
transformer: (value: ProcedureReturnValue) => ReturnValue | Promise<ReturnValue>;
},
context: Context
): NoArgsProcedureMethod<ProcedureReturnValue, ReturnValue>;
export function createProcedureMethod<
// eslint-disable-next-line @typescript-eslint/ban-types
MethodArgs extends {},
ProcedureArgs,
ProcedureReturnValue,
Storage = Record<string, unknown>
>(
args: {
getProcedureAndArgs: (
methodArgs: MethodArgs
) => [
(
| UnionOfProcedureFuncs<ProcedureArgs, ProcedureReturnValue, Storage>
| ProcedureFunc<ProcedureArgs, ProcedureReturnValue, Storage>
),
ProcedureArgs
];
},
context: Context
): ProcedureMethod<MethodArgs, ProcedureReturnValue, ProcedureReturnValue>;
export function createProcedureMethod<
// eslint-disable-next-line @typescript-eslint/ban-types
MethodArgs extends {},
ProcedureArgs,
ProcedureReturnValue,
ReturnValue,
Storage = Record<string, unknown>
>(
args: {
getProcedureAndArgs: (
methodArgs: MethodArgs
) => [
(
| UnionOfProcedureFuncs<ProcedureArgs, ProcedureReturnValue, Storage>
| ProcedureFunc<ProcedureArgs, ProcedureReturnValue, Storage>
),
ProcedureArgs
];
transformer: (value: ProcedureReturnValue) => ReturnValue | Promise<ReturnValue>;
},
context: Context
): ProcedureMethod<MethodArgs, ProcedureReturnValue, ReturnValue>;
// eslint-disable-next-line require-jsdoc
export function createProcedureMethod<
MethodArgs,
ProcedureArgs,
ProcedureReturnValue,
ReturnValue = ProcedureReturnValue,
Storage = Record<string, unknown>
>(
args: {
getProcedureAndArgs: (
methodArgs?: MethodArgs
) => [
(
| UnionOfProcedureFuncs<ProcedureArgs, ProcedureReturnValue, Storage>
| ProcedureFunc<ProcedureArgs, ProcedureReturnValue, Storage>
),
ProcedureArgs
];
transformer?: (value: ProcedureReturnValue) => ReturnValue | Promise<ReturnValue>;
voidArgs?: true;
},
context: Context
):
| ProcedureMethod<MethodArgs, ProcedureReturnValue, ReturnValue>
| NoArgsProcedureMethod<ProcedureReturnValue, ReturnValue> {
const { getProcedureAndArgs, transformer, voidArgs } = args;
if (voidArgs) {
const voidMethod = (
opts: ProcedureOpts = {}
): Promise<TransactionQueue<ProcedureReturnValue, ReturnValue>> => {
const [proc, procArgs] = getProcedureAndArgs();
return proc().prepare({ args: procArgs, transformer }, context, opts);
};
voidMethod.checkAuthorization = async (
opts: ProcedureOpts = {}
): Promise<ProcedureAuthorizationStatus> => {
const [proc, procArgs] = getProcedureAndArgs();
return proc().checkAuthorization(procArgs, context, opts);
};
return voidMethod;
}
const method = (
methodArgs: MethodArgs,
opts: ProcedureOpts = {}
): Promise<TransactionQueue<ProcedureReturnValue, ReturnValue>> => {
const [proc, procArgs] = getProcedureAndArgs(methodArgs);
return proc().prepare({ args: procArgs, transformer }, context, opts);
};
method.checkAuthorization = async (
methodArgs: MethodArgs,
opts: ProcedureOpts = {}
): Promise<ProcedureAuthorizationStatus> => {
const [proc, procArgs] = getProcedureAndArgs(methodArgs);
return proc().checkAuthorization(procArgs, context, opts);
};
return method;
}
/**
* @hidden
*/
export function assertIsInteger(value: BigNumber): void {
if (!value.isInteger()) {
throw new PolymeshError({
code: ErrorCode.ValidationError,
message: 'The number must be an integer',
});
}
}
/**
* @hidden
*/
export function assertIsPositive(value: BigNumber): void {
if (value.isNegative()) {
throw new PolymeshError({
code: ErrorCode.ValidationError,
message: 'The number must be positive',
});
}
}
/**
* @hidden
*/
export function assertAddressValid(address: string, ss58Format: BigNumber): void {
let encodedAddress: string;
try {
encodedAddress = encodeAddress(decodeAddress(address), ss58Format.toNumber());
} catch (err) {
throw new PolymeshError({
code: ErrorCode.ValidationError,
message: 'The supplied address is not a valid SS58 address',
});
}
if (address !== encodedAddress) {
throw new PolymeshError({
code: ErrorCode.ValidationError,
message: "The supplied address is not encoded with the chain's SS58 format",
data: {
ss58Format,
},
});
}
}
/**
* @hidden
*/
export function asTicker(asset: string | Asset): string {
return typeof asset === 'string' ? asset : asset.ticker;
}
/**
* @hidden
*/
export function asAsset(asset: string | Asset, context: Context): Asset {
return typeof asset === 'string' ? new Asset({ ticker: asset }, context) : asset;
}
/**
* @hidden
*/
export function xor(a: boolean, b: boolean): boolean {
return a !== b;
}
/**
* @hidden
*/
function secondsInUnit(unit: CalendarUnit): BigNumber {
const SECOND = new BigNumber(1);
const MINUTE = SECOND.multipliedBy(60);
const HOUR = MINUTE.multipliedBy(60);
const DAY = HOUR.multipliedBy(24);
const WEEK = DAY.multipliedBy(7);
const MONTH = DAY.multipliedBy(30);
const YEAR = DAY.multipliedBy(365);
switch (unit) {
case CalendarUnit.Second: {
return SECOND;
}
case CalendarUnit.Minute: {
return MINUTE;
}
case CalendarUnit.Hour: {
return HOUR;
}
case CalendarUnit.Day: {
return DAY;
}
case CalendarUnit.Week: {
return WEEK;
}
case CalendarUnit.Month: {
return MONTH;
}
case CalendarUnit.Year: {
return YEAR;
}
}
}
/**
* @hidden
* Calculate the numeric complexity of a calendar period
*/
export function periodComplexity(period: CalendarPeriod): BigNumber {
const secsInYear = secondsInUnit(CalendarUnit.Year);
const { amount, unit } = period;
if (amount.isZero()) {
return new BigNumber(1);
}
const secsInUnit = secondsInUnit(unit);
const complexity = secsInYear.dividedBy(secsInUnit.multipliedBy(amount));
return BigNumber.maximum(2, complexity.integerValue(BigNumber.ROUND_FLOOR));
}
/**
* @hidden
* Transform a conversion util into a version that returns null if the input is falsy
*/
export function optionize<InputType, OutputType, RestType extends unknown[]>(
converter: (input: InputType, ...rest: RestType) => OutputType
): (val: InputType | null | undefined, ...rest: RestType) => OutputType | null {
return (value: InputType | null | undefined, ...rest: RestType): OutputType | null => {
const data = value ?? null;
return data && converter(data, ...rest);
};
}
/**
* @hidden
* Compare two tags/modules and return true if they are equal, or if one is the other one's module
*/
export function isModuleOrTagMatch(a: TxTag | ModuleName, b: TxTag | ModuleName): boolean {
const aIsTag = a.includes('.');
const bIsTag = b.includes('.');
// a tag b module
if (aIsTag && !bIsTag) {
return a.split('.')[0] === b;
}
// a module b tag
if (!aIsTag && bIsTag) {
return a === b.split('.')[0];
}
// both tags or both modules
return a === b;
}
/**
* @hidden
*
* Recursively convert a value into a human readable (JSON compliant) version:
* - Entities are converted via their `.toJson` method
* - Dates are converted to ISO strings
* - BigNumbers are converted to numerical strings
*/
export function toHumanReadable<T>(obj: T): HumanReadableType<T> {
if (isEntity<unknown, HumanReadableType<T>>(obj)) {
return obj.toJson();
}
if (obj instanceof BigNumber) {
return obj.toString() as HumanReadableType<T>;
}
if (obj instanceof Date) {
return obj.toISOString() as HumanReadableType<T>;
}
if (Array.isArray(obj)) {
return obj.map(toHumanReadable) as HumanReadableType<T>;
}
if (obj && typeof obj === 'object') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return mapValues(obj as any, val => toHumanReadable(val)) as HumanReadableType<T>;
}
return obj as HumanReadableType<T>;
}
/**
* @hidden
*
* Return whether the two arrays have same elements.
* It uses a `comparator` function to check if elements are equal.
* If no comparator function is provided, it uses `isEqual` function of `lodash`
*/
export function hasSameElements<T>(
first: T[],
second: T[],
comparator: (a: T, b: T) => boolean = isEqual
): boolean {
return !differenceWith(first, second, comparator).length && first.length === second.length;
}
/**
* @hidden
*
* Perform a deep comparison between two compliance conditions
*/
export function conditionsAreEqual(
a: Condition | InputCondition,
b: Condition | InputCondition
): boolean {
let equalClaims = false;
const { type: aType, trustedClaimIssuers: aClaimIssuers = [] } = a;
const { type: bType, trustedClaimIssuers: bClaimIssuers = [] } = b;
if (isSingleClaimCondition(a) && isSingleClaimCondition(b)) {
equalClaims = isEqual(a.claim, b.claim);
} else if (isMultiClaimCondition(a) && isMultiClaimCondition(b)) {
const { claims: aClaims } = a;
const { claims: bClaims } = b;
equalClaims = hasSameElements(aClaims, bClaims);
} else if (aType === ConditionType.IsIdentity && bType === ConditionType.IsIdentity) {
equalClaims = signerToString(a.identity) === signerToString(b.identity);
} else if (aType === ConditionType.IsExternalAgent && bType === ConditionType.IsExternalAgent) {
equalClaims = true;
}
const equalClaimIssuers = hasSameElements(
aClaimIssuers,
bClaimIssuers,
(
{ identity: aIdentity, trustedFor: aTrustedFor },
{ identity: bIdentity, trustedFor: bTrustedFor }
) =>
signerToString(aIdentity) === signerToString(bIdentity) &&
hasSameElements(aTrustedFor || [], bTrustedFor || [])
);
return equalClaims && equalClaimIssuers;
}
/**
* @hidden
*
* Transforms `InputCACheckpoint` values to `Checkpoint | CheckpointSchedule | Date` for easier processing
*/
export async function getCheckpointValue(
checkpoint: InputCaCheckpoint,
asset: string | Asset,
context: Context
): Promise<Checkpoint | CheckpointSchedule | Date> {
if (
checkpoint instanceof Checkpoint ||
checkpoint instanceof CheckpointSchedule ||
checkpoint instanceof Date
) {
return checkpoint;
}
const assetEntity = asAsset(asset, context);
const { type, id } = checkpoint;
if (type === CaCheckpointType.Existing) {
return assetEntity.checkpoints.getOne({ id });
} else {
return (
await assetEntity.checkpoints.schedules.getOne({
id,
})
).schedule;
}
}
interface TxAndArgsArray<Args extends unknown[] = unknown[]> {
transaction: PolymeshTx<Args>;
argsArray: Args[];
}
type MapTxAndArgsArray<Args extends unknown[][]> = {
[K in keyof Args]: Args[K] extends unknown[] ? TxAndArgsArray<Args[K]> : never;
};
// * TODO @monitz87: delete this function when we eliminate `addBatchTransaction`
/**
* @hidden
*/
function mapArgs<Args extends unknown[] | []>({
transaction,
argsArray,
}: TxAndArgsArray<Args>): MapTxWithArgs<Args[]> {
return argsArray.map(args => ({
transaction,
args,
})) as unknown as MapTxWithArgs<Args[]>;
}
// * TODO @monitz87: delete this function when we eliminate `addBatchTransaction`
/**
* Assemble the `transactions` array that has to be passed to `addBatchTransaction` from a set of parameter arrays with their
* respective transaction
*/
export function assembleBatchTransactions<ArgsArray extends unknown[][]>(
txsAndArgs: MapTxAndArgsArray<ArgsArray>
): MapTxWithArgs<unknown[][]> {
return flatMap(txsAndArgs, mapArgs) as unknown as MapTxWithArgs<unknown[][]>;
}
/**
* @hidden
*
* Returns portfolio numbers for a set of portfolio names
*/
export async function getPortfolioIdsByName(
rawIdentityId: IdentityId,
rawNames: PortfolioName[],
context: Context
): Promise<(BigNumber | null)[]> {
const {
polymeshApi: {
query: { portfolio },
},
} = context;
const rawPortfolioNumbers = await portfolio.nameToNumber.multi<PortfolioNumber>(
rawNames.map<[IdentityId, PortfolioName]>(name => [rawIdentityId, name])
);
const portfolioIds = rawPortfolioNumbers.map(number => u64ToBigNumber(number));
// TODO @prashantasdeveloper remove this logic once nameToNumber returns Option<PortfolioNumber>
/**
* since nameToNumber returns 1 for non-existing portfolios, if a name maps to number 1,
* we need to check if the given name actually matches the first portfolio
*/
let firstPortfolioName: PortfolioName;
/*
* even though we make this call without knowing if we will need
* the result, we only await for it if necessary, so it's still
* performant
*/
const gettingFirstPortfolioName = portfolio.portfolios(
rawIdentityId,
bigNumberToU64(new BigNumber(1), context)
);
return P.map(portfolioIds, async (id, index) => {
if (id.eq(1)) {
firstPortfolioName = await gettingFirstPortfolioName;
if (!firstPortfolioName.eq(rawNames[index])) {
return null;
}
}
return id;
});
}
/**
* @hidden
*
* Check if a transaction matches the type of its args. Returns the same value but stripped of the types. This function has no logic, it's strictly
* for type safety around `addBatchTransaction`
*/
export function checkTxType<Args extends unknown[]>(tx: TxWithArgs<Args>): TxWithArgs<unknown[]> {
return tx as unknown as TxWithArgs<unknown[]>;
}
/**
* @hidden
*
* Add an empty handler to a promise to avoid false positive unhandled promise errors. The original promise
* is returned, so rejections are still bubbled up and caught properly. This is an ugly hack and should be used
* sparingly and only if you KNOW that rejections will be handled properly down the line
*
* More info:
*
* - https://github.com/facebook/jest/issues/6028#issuecomment-567851031
* - https://stackoverflow.com/questions/59060508/how-to-handle-an-unhandled-promise-rejection-asynchronously
* - https://stackoverflow.com/questions/40920179/should-i-refrain-from-handling-promise-rejection-asynchronously/40921505#40921505
*/
export function defusePromise<T>(promise: Promise<T>): Promise<T> {
promise.catch(noop);
return promise;
}
/**
* @hidden
*
* Transform an array of Identities into exempted IDs for Transfer Managers. If the asset requires
* investor uniqueness, Scope IDs are fetched and returned. Otherwise, we use Identity IDs
*
* @note fetches missing scope IDs from the chain
* @note even though the signature for `addExemptedEntities` requires `ScopeId`s as parameters,
* it accepts and handles `IdentityId` parameters as well. Nothing special has to be done typing-wise since they're both aliases
* for `U8aFixed`
*
* @throws
* - if the Asset requires Investor Uniqueness and one or more of the passed Identities don't have Scope IDs
* - if there are duplicated Identities/ScopeIDs
*/
export async function getExemptedIds(
identities: (string | Identity)[],
context: Context,
ticker: string
): Promise<string[]> {
const asset = new Asset({ ticker }, context);
const { requiresInvestorUniqueness } = await asset.details();
const didsWithNoScopeId: string[] = [];
const exemptedIds: string[] = [];
const identityEntities = identities.map(identity => asIdentity(identity, context));
if (requiresInvestorUniqueness) {
const scopeIds = await P.map(identityEntities, async identity =>
identity.getScopeId({ asset: ticker })
);
scopeIds.forEach((scopeId, index) => {
if (!scopeId) {
didsWithNoScopeId.push(identityEntities[index].did);
} else {
exemptedIds.push(scopeId);
}
});
if (didsWithNoScopeId.length) {
throw new PolymeshError({
code: ErrorCode.ValidationError,
message: `Identities must have an Investor Uniqueness claim Scope ID in order to be exempted from Transfer Restrictions for Asset "${ticker}"`,
data: {
didsWithNoScopeId,
},
});