generated from PolymeshAssociation/typescript-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.ts
584 lines (507 loc) · 15.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
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
import {
PolymeshPrimitivesSettlementInstructionStatus,
PolymeshPrimitivesSettlementLeg,
} from '@polkadot/types/lookup';
import BigNumber from 'bignumber.js';
import P from 'bluebird';
import { executeManualInstruction } from '~/api/procedures/executeManualInstruction';
import {
Context,
Entity,
FungibleAsset,
Identity,
modifyInstructionAffirmation,
Nft,
NftCollection,
PolymeshError,
Venue,
} from '~/internal';
import { instructionsQuery } from '~/middleware/queries';
import { InstructionStatusEnum, Query } from '~/middleware/types';
import {
AffirmOrWithdrawInstructionParams,
DefaultPortfolio,
ErrorCode,
EventIdentifier,
ExecuteManualInstructionParams,
InstructionAffirmationOperation,
NumberedPortfolio,
OptionalArgsProcedureMethod,
PaginationOptions,
RejectInstructionParams,
ResultSet,
SubCallback,
UnsubCallback,
} from '~/types';
import { InstructionStatus as InternalInstructionStatus } from '~/types/internal';
import { Ensured } from '~/types/utils';
import {
balanceToBigNumber,
bigNumberToU64,
identityIdToString,
instructionMemoToString,
meshAffirmationStatusToAffirmationStatus,
meshInstructionStatusToInstructionStatus,
meshNftToNftId,
meshPortfolioIdToPortfolio,
meshSettlementTypeToEndCondition,
middlewareEventDetailsToEventIdentifier,
momentToDate,
tickerToString,
u64ToBigNumber,
} from '~/utils/conversion';
import { createProcedureMethod, optionize, requestMulti, requestPaginated } from '~/utils/internal';
import {
InstructionAffirmation,
InstructionDetails,
InstructionStatus,
InstructionStatusResult,
Leg,
} from './types';
export interface UniqueIdentifiers {
id: BigNumber;
}
const executedMessage =
'Instruction has already been executed/rejected and it was purged from chain';
/**
* Represents a settlement Instruction to be executed on a certain Venue
*/
export class Instruction extends Entity<UniqueIdentifiers, string> {
/**
* @hidden
* Check if a value is of type {@link UniqueIdentifiers}
*/
public static override isUniqueIdentifiers(identifier: unknown): identifier is UniqueIdentifiers {
const { id } = identifier as UniqueIdentifiers;
return id instanceof BigNumber;
}
/**
* Unique identifier number of the instruction
*/
public id: BigNumber;
/**
* @hidden
*/
public constructor(identifiers: UniqueIdentifiers, context: Context) {
super(identifiers, context);
const { id } = identifiers;
this.id = id;
this.reject = createProcedureMethod(
{
getProcedureAndArgs: args => [
modifyInstructionAffirmation,
{ id, operation: InstructionAffirmationOperation.Reject, ...args },
],
optionalArgs: true,
},
context
);
this.affirm = createProcedureMethod(
{
getProcedureAndArgs: args => [
modifyInstructionAffirmation,
{ id, operation: InstructionAffirmationOperation.Affirm, ...args },
],
optionalArgs: true,
},
context
);
this.withdraw = createProcedureMethod(
{
getProcedureAndArgs: args => [
modifyInstructionAffirmation,
{ id, operation: InstructionAffirmationOperation.Withdraw, ...args },
],
optionalArgs: true,
},
context
);
this.executeManually = createProcedureMethod(
{
getProcedureAndArgs: args => [executeManualInstruction, { id, ...args }],
optionalArgs: true,
},
context
);
}
/**
* Retrieve whether the Instruction has already been executed and pruned from
* the chain.
*/
public async isExecuted(): Promise<boolean> {
const {
context: {
polymeshApi: {
query: { settlement },
},
},
id,
context,
} = this;
const [status, exists] = await Promise.all([
settlement.instructionStatuses(bigNumberToU64(id, context)),
this.exists(),
]);
const statusResult = meshInstructionStatusToInstructionStatus(status);
return (
(statusResult === InternalInstructionStatus.Unknown ||
statusResult === InternalInstructionStatus.Success ||
statusResult === InternalInstructionStatus.Rejected) &&
exists
);
}
/**
* Retrieve whether the Instruction is still pending on chain
*/
public async isPending(): Promise<boolean> {
const {
context: {
polymeshApi: {
query: { settlement },
},
},
id,
context,
} = this;
const status = await settlement.instructionStatuses(bigNumberToU64(id, context));
const statusResult = meshInstructionStatusToInstructionStatus(status);
return statusResult === InternalInstructionStatus.Pending;
}
/**
* Retrieve current status of the Instruction. This can be subscribed to know if instruction fails
*
* @note can be subscribed to
* @note current status as `Executed` means that the Instruction has been executed/rejected and pruned from
* the chain.
*/
public async onStatusChange(callback: SubCallback<InstructionStatus>): Promise<UnsubCallback> {
const {
context: {
polymeshApi: {
query: { settlement },
},
},
id,
context,
} = this;
const assembleResult = (
rawStatus: PolymeshPrimitivesSettlementInstructionStatus
): InstructionStatus => {
const internalStatus = meshInstructionStatusToInstructionStatus(rawStatus);
const status = this.internalToExternalStatus(internalStatus);
if (!status) {
throw new Error('Unknown instruction status');
}
return status;
};
return settlement.instructionStatuses(bigNumberToU64(id, context), status => {
return callback(assembleResult(status));
});
}
/**
* Determine whether this Instruction exists on chain (or existed and was pruned)
*/
public async exists(): Promise<boolean> {
const {
context: {
polymeshApi: {
query: { settlement },
},
},
id,
} = this;
const instructionCounter = await settlement.instructionCounter();
return id.lte(u64ToBigNumber(instructionCounter));
}
/**
* Retrieve information specific to this Instruction
*/
public async details(): Promise<InstructionDetails> {
const {
context: {
polymeshApi: {
query: { settlement },
},
},
id,
context,
} = this;
const rawId = bigNumberToU64(id, context);
const [{ createdAt, tradeDate, valueDate, settlementType: type, venueId }, rawStatus, memo] =
await requestMulti<
[
typeof settlement.instructionDetails,
typeof settlement.instructionStatuses,
typeof settlement.instructionMemos
]
>(context, [
[settlement.instructionDetails, rawId],
[settlement.instructionStatuses, rawId],
[settlement.instructionMemos, rawId],
]);
const internalStatus = meshInstructionStatusToInstructionStatus(rawStatus);
const status = this.internalToExternalStatus(internalStatus);
if (!status) {
throw new PolymeshError({
code: ErrorCode.DataUnavailable,
message: executedMessage,
});
}
return {
status,
createdAt: momentToDate(createdAt.unwrap()),
tradeDate: tradeDate.isSome ? momentToDate(tradeDate.unwrap()) : null,
valueDate: valueDate.isSome ? momentToDate(valueDate.unwrap()) : null,
venue: new Venue({ id: u64ToBigNumber(venueId) }, context),
memo: memo.isSome ? instructionMemoToString(memo.unwrap()) : null,
...meshSettlementTypeToEndCondition(type),
};
}
/**
* Retrieve every authorization generated by this Instruction (status and authorizing Identity)
*
* @note supports pagination
*/
public async getAffirmations(
paginationOpts?: PaginationOptions
): Promise<ResultSet<InstructionAffirmation>> {
const {
context: {
polymeshApi: {
query: { settlement },
},
},
id,
context,
} = this;
const isExecuted = await this.isExecuted();
if (isExecuted) {
throw new PolymeshError({
code: ErrorCode.DataUnavailable,
message: executedMessage,
});
}
const { entries, lastKey: next } = await requestPaginated(settlement.affirmsReceived, {
arg: bigNumberToU64(id, context),
paginationOpts,
});
const data = entries.map(([{ args }, meshAffirmationStatus]) => {
const [, { did }] = args;
return {
identity: new Identity({ did: identityIdToString(did) }, context),
status: meshAffirmationStatusToAffirmationStatus(meshAffirmationStatus),
};
});
return {
data,
next,
};
}
/**
* Retrieve all legs of this Instruction
*
* @note supports pagination
*/
public async getLegs(paginationOpts?: PaginationOptions): Promise<ResultSet<Leg>> {
const {
context: {
polymeshApi: {
query: { settlement },
},
},
id,
context,
} = this;
const isExecuted = await this.isExecuted();
if (isExecuted) {
throw new PolymeshError({
code: ErrorCode.DataUnavailable,
message: executedMessage,
});
}
const { entries: legs, lastKey: next } = await requestPaginated(settlement.instructionLegs, {
arg: bigNumberToU64(id, context),
paginationOpts,
});
const data = legs.map(([, leg]) => {
if (leg.isSome) {
const legValue: PolymeshPrimitivesSettlementLeg = leg.unwrap();
if (legValue.isFungible) {
const { sender, receiver, amount, ticker: rawTicker } = legValue.asFungible;
const ticker = tickerToString(rawTicker);
const fromPortfolio = meshPortfolioIdToPortfolio(sender, context);
const toPortfolio = meshPortfolioIdToPortfolio(receiver, context);
return {
from: fromPortfolio,
to: toPortfolio,
amount: balanceToBigNumber(amount),
asset: new FungibleAsset({ ticker }, context),
};
} else if (legValue.isNonFungible) {
const { sender, receiver, nfts } = legValue.asNonFungible;
const from = meshPortfolioIdToPortfolio(sender, context);
const to = meshPortfolioIdToPortfolio(receiver, context);
const { ticker, ids } = meshNftToNftId(nfts);
return {
from,
to,
nfts: ids.map(nftId => new Nft({ ticker, id: nftId }, context)),
asset: new NftCollection({ ticker }, context),
};
} else {
// assume it is offchain
throw new Error('TODO ERROR: Offchain legs are not supported yet');
}
} else {
throw new Error(
'Instruction has already been executed/rejected and it was purged from chain'
);
}
});
return {
data,
next,
};
}
/**
* Retrieve current status of this Instruction
*
* @note uses the middlewareV2
*/
public async getStatus(): Promise<InstructionStatusResult> {
const isPending = await this.isPending();
if (isPending) {
return {
status: InstructionStatus.Pending,
};
}
const [executedEventIdentifier, failedEventIdentifier] = await Promise.all([
this.getInstructionEventFromMiddleware(InstructionStatusEnum.Executed),
this.getInstructionEventFromMiddleware(InstructionStatusEnum.Failed),
]);
if (executedEventIdentifier) {
return {
status: InstructionStatus.Success,
eventIdentifier: executedEventIdentifier,
};
}
if (failedEventIdentifier) {
return {
status: InstructionStatus.Failed,
eventIdentifier: failedEventIdentifier,
};
}
throw new PolymeshError({
code: ErrorCode.DataUnavailable,
message: "It isn't possible to determine the current status of this Instruction",
});
}
/**
* Reject this instruction
*
* @note reject on `SettleOnAffirmation` will execute the settlement and it will fail immediately.
* @note reject on `SettleOnBlock` behaves just like unauthorize
* @note reject on `SettleManual` behaves just like unauthorize
*/
public reject: OptionalArgsProcedureMethod<RejectInstructionParams, Instruction>;
/**
* Affirm this instruction (authorize)
*/
public affirm: OptionalArgsProcedureMethod<AffirmOrWithdrawInstructionParams, Instruction>;
/**
* Withdraw affirmation from this instruction (unauthorize)
*/
public withdraw: OptionalArgsProcedureMethod<AffirmOrWithdrawInstructionParams, Instruction>;
/**
* Executes an Instruction either of type `SettleManual` or a `Failed` instruction
*/
public executeManually: OptionalArgsProcedureMethod<ExecuteManualInstructionParams, Instruction>;
/**
* @hidden
* Retrieve Instruction status event from middleware V2
*/
private async getInstructionEventFromMiddleware(
status: InstructionStatusEnum
): Promise<EventIdentifier | null> {
const { id, context } = this;
const {
data: {
instructions: {
nodes: [details],
},
},
} = await context.queryMiddleware<Ensured<Query, 'instructions'>>(
instructionsQuery(
{
status,
id: id.toString(),
},
new BigNumber(1),
new BigNumber(0)
)
);
return optionize(middlewareEventDetailsToEventIdentifier)(
details?.updatedBlock,
details?.eventIdx
);
}
/**
* Return the Instruction's ID
*/
public toHuman(): string {
return this.id.toString();
}
/**
* Retrieve all the involved portfolios in this Instruction where the given identity is a custodian of
*/
public async getInvolvedPortfolios(args: {
did: string;
}): Promise<(DefaultPortfolio | NumberedPortfolio)[]> {
const { did } = args;
const { data: legs } = await this.getLegs();
const assemblePortfolios = async (
involvedPortfolios: (DefaultPortfolio | NumberedPortfolio)[],
from: DefaultPortfolio | NumberedPortfolio,
to: DefaultPortfolio | NumberedPortfolio
): Promise<(DefaultPortfolio | NumberedPortfolio)[]> => {
const [fromExists, toExists] = await Promise.all([from.exists(), to.exists()]);
const checkCustody = async (
legPortfolio: DefaultPortfolio | NumberedPortfolio,
exists: boolean
): Promise<void> => {
if (exists) {
const isCustodied = await legPortfolio.isCustodiedBy({ identity: did });
if (isCustodied) {
involvedPortfolios.push(legPortfolio);
}
} else if (legPortfolio.owner.did === did) {
involvedPortfolios.push(legPortfolio);
}
};
await Promise.all([checkCustody(from, fromExists), checkCustody(to, toExists)]);
return involvedPortfolios;
};
const portfolios = await P.reduce<Leg, (DefaultPortfolio | NumberedPortfolio)[]>(
legs,
async (result, { from, to }) => assemblePortfolios(result, from, to),
[]
);
return portfolios;
}
/**
* @hidden
*/
private internalToExternalStatus(status: InternalInstructionStatus): InstructionStatus | null {
switch (status) {
case InternalInstructionStatus.Pending:
return InstructionStatus.Pending;
case InternalInstructionStatus.Failed:
return InstructionStatus.Failed;
case InternalInstructionStatus.Success:
return InstructionStatus.Success;
case InternalInstructionStatus.Rejected:
return InstructionStatus.Rejected;
}
return null;
}
}