generated from PolymeshAssociation/typescript-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.ts
606 lines (514 loc) · 16.6 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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
import { Option } from '@polkadot/types';
import { PalletCorporateActionsDistribution } from '@polkadot/types/lookup';
import BigNumber from 'bignumber.js';
import P from 'bluebird';
import { chunk, flatten, remove } from 'lodash';
import {
HumanReadable as CorporateActionHumanReadable,
Params as CorporateActionParams,
UniqueIdentifiers,
} from '~/api/entities/CorporateAction';
import {
Checkpoint,
CheckpointSchedule,
claimDividends,
Context,
CorporateActionBase,
DefaultPortfolio,
Identity,
modifyCaCheckpoint,
NumberedPortfolio,
payDividends,
PolymeshError,
reclaimDividendDistributionFunds,
} from '~/internal';
import { distributionPaymentsQuery, distributionQuery } from '~/middleware/queries';
import { Query } from '~/middleware/types';
import {
CorporateActionKind,
DistributionPayment,
DividendDistributionDetails,
ErrorCode,
IdentityBalance,
InputCaCheckpoint,
ModifyCaCheckpointParams,
NoArgsProcedureMethod,
PayDividendsParams,
ProcedureMethod,
ResultSet,
TargetTreatment,
} from '~/types';
import { ProcedureParams } from '~/types/internal';
import { Ensured, HumanReadableType, Modify, tuple } from '~/types/utils';
import { MAX_CONCURRENT_REQUESTS, MAX_DECIMALS, MAX_PAGE_SIZE } from '~/utils/constants';
import {
balanceToBigNumber,
boolToBoolean,
corporateActionIdentifierToCaId,
stringToIdentityId,
} from '~/utils/conversion';
import {
calculateNextKey,
createProcedureMethod,
getIdentity,
toHumanReadable,
xor,
} from '~/utils/internal';
import { DistributionParticipant } from './types';
export interface HumanReadable extends CorporateActionHumanReadable {
origin: HumanReadableType<DefaultPortfolio | NumberedPortfolio>;
currency: string;
perShare: string;
maxAmount: string;
expiryDate: string | null;
paymentDate: string;
}
export interface DividendDistributionParams {
origin: DefaultPortfolio | NumberedPortfolio;
currency: string;
perShare: BigNumber;
maxAmount: BigNumber;
expiryDate: null | Date;
paymentDate: Date;
}
export type Params = CorporateActionParams & DividendDistributionParams;
const notExistsMessage = 'The Dividend Distribution no longer exists';
/**
* Represents a Corporate Action via which an Asset issuer wishes to distribute dividends
* between a subset of the Asset Holders (targets)
*/
export class DividendDistribution extends CorporateActionBase {
/**
* Portfolio from which the dividends will be distributed
*/
public origin: DefaultPortfolio | NumberedPortfolio;
/**
* ticker of the currency in which dividends are being distributed
*/
public currency: string;
/**
* amount of `currency` to pay for each share held by the Asset Holders
*/
public perShare: BigNumber;
/**
* maximum amount of `currency` to be distributed. Distributions are "first come, first served", so funds can be depleted before
* every Asset Holder receives their corresponding amount
*/
public maxAmount: BigNumber;
/**
* date after which dividends can no longer be paid/reclaimed. A null value means the distribution never expires
*/
public expiryDate: null | Date;
/**
* date starting from which dividends can be paid/reclaimed
*/
public paymentDate: Date;
/**
* type of dividend distribution being represented. The chain enforces it to be either PredictableBenefit or UnpredictableBenefit
*/
protected declare kind:
| CorporateActionKind.UnpredictableBenefit
| CorporateActionKind.PredictableBenefit;
/**
* @hidden
*/
public constructor(args: UniqueIdentifiers & Params, context: Context) {
const {
origin,
currency,
perShare,
maxAmount,
expiryDate,
paymentDate,
...corporateActionArgs
} = args;
super({ ...corporateActionArgs }, context);
this.origin = origin;
this.currency = currency;
this.perShare = perShare;
this.maxAmount = maxAmount;
this.expiryDate = expiryDate;
this.paymentDate = paymentDate;
this.pay = createProcedureMethod(
{
getProcedureAndArgs: payDividendsArgs => [
payDividends,
{ ...payDividendsArgs, distribution: this },
],
},
context
);
this.claim = createProcedureMethod(
{ getProcedureAndArgs: () => [claimDividends, { distribution: this }], voidArgs: true },
context
);
this.modifyCheckpoint = createProcedureMethod<
Modify<
ModifyCaCheckpointParams,
{
checkpoint: InputCaCheckpoint;
}
>,
ProcedureParams<typeof modifyCaCheckpoint>,
void
>(
{
getProcedureAndArgs: modifyCheckpointArgs => [
modifyCaCheckpoint,
{ corporateAction: this, ...modifyCheckpointArgs },
],
},
context
);
this.reclaimFunds = createProcedureMethod(
{
getProcedureAndArgs: () => [reclaimDividendDistributionFunds, { distribution: this }],
voidArgs: true,
},
context
);
}
/**
* Claim the Dividends corresponding to the signing Identity
*
* @note if `currency` is indivisible, the Identity's share will be rounded down to the nearest integer (after taxes are withheld)
*/
public claim: NoArgsProcedureMethod<void>;
/**
* Modify the Distribution's Checkpoint
*/
public modifyCheckpoint: ProcedureMethod<
Modify<
ModifyCaCheckpointParams,
{
checkpoint: InputCaCheckpoint;
}
>,
void
>;
/**
* Transfer the corresponding share of the dividends to a list of Identities
*
* @note due to performance issues, we do not validate that the distribution has enough remaining funds to pay the corresponding amount to the supplied Identities
* @note if `currency` is indivisible, the Identity's share will be rounded down to the nearest integer (after taxes are withheld)
*/
public pay: ProcedureMethod<PayDividendsParams, void>;
/**
* Reclaim any remaining funds back to the origin Portfolio. This can only be done after the Distribution has expired
*
* @note withheld taxes are also reclaimed in the same transaction
*
* @note required roles:
* - Origin Portfolio Custodian
*/
public reclaimFunds: NoArgsProcedureMethod<void>;
/**
* Retrieve the Checkpoint associated with this Dividend Distribution. If the Checkpoint is scheduled and has not been created yet,
* the corresponding CheckpointSchedule is returned instead
*/
public override async checkpoint(): Promise<Checkpoint | CheckpointSchedule> {
const exists = await this.exists();
if (!exists) {
throw new PolymeshError({
code: ErrorCode.DataUnavailable,
message: notExistsMessage,
});
}
const checkpoint = await super.checkpoint();
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return checkpoint!;
}
/**
* Retrieve whether the Distribution exists
*/
public override async exists(): Promise<boolean> {
const distribution = await this.fetchDistribution();
return distribution.isSome;
}
/**
* Retrieve details associated with this Dividend Distribution
*/
public async details(): Promise<DividendDistributionDetails> {
const distribution = await this.fetchDistribution();
if (distribution.isNone) {
throw new PolymeshError({
code: ErrorCode.DataUnavailable,
message: notExistsMessage,
});
}
const { reclaimed, remaining } = distribution.unwrap();
return {
remainingFunds: balanceToBigNumber(remaining),
fundsReclaimed: boolToBoolean(reclaimed),
};
}
/**
* Retrieve a comprehensive list of all Identities that are entitled to dividends in this Distribution (participants),
* the amount they are entitled to and whether they have been paid or not
*
* @note this request can take a lot of time with large amounts of Asset Holders
* @note if the Distribution Checkpoint hasn't been created yet, the result will be an empty array.
* This is because the Distribution participants cannot be determined without a Checkpoint
*/
public async getParticipants(): Promise<DistributionParticipant[]> {
const {
targets: { identities: targetIdentities, treatment },
paymentDate,
} = this;
let balances: IdentityBalance[] = [];
const checkpoint = await this.checkpoint();
if (checkpoint instanceof CheckpointSchedule) {
return [];
}
let allFetched = false;
let start: string | undefined;
while (!allFetched) {
const { data, next } = await checkpoint.allBalances({ size: MAX_PAGE_SIZE, start });
start = (next as string) || undefined;
allFetched = !next;
balances = [...balances, ...data];
}
const isExclusion = treatment === TargetTreatment.Exclude;
const participants: DistributionParticipant[] = [];
const clonedTargets = [...targetIdentities];
balances.forEach(({ identity, balance }) => {
const isTarget = !!remove(clonedTargets, target => identity.isEqual(target)).length;
if (balance.gt(0) && xor(isTarget, isExclusion)) {
participants.push(this.assembleParticipant(identity, balance));
}
});
// participants can't be paid before the payment date
if (paymentDate < new Date()) {
return participants;
}
const paidStatuses = await this.getParticipantStatuses(participants);
return paidStatuses.map((paid, index) => ({ ...participants[index], paid }));
}
/**
* Retrieve an Identity that is entitled to dividends in this Distribution (participant),
* the amount it is entitled to and whether it has been paid or not
*
* @param args.identity - defaults to the signing Identity
*
* @note if the Distribution Checkpoint hasn't been created yet, the result will be null.
* This is because the Distribution participant's corresponding payment cannot be determined without a Checkpoint
*/
public async getParticipant(args?: {
identity: string | Identity;
}): Promise<DistributionParticipant | null> {
const {
id: localId,
asset: { ticker },
targets: { identities: targetIdentities, treatment },
paymentDate,
context,
context: {
polymeshApi: { query },
},
} = this;
const checkpoint = await this.checkpoint();
if (checkpoint instanceof CheckpointSchedule) {
return null;
}
const [identity, balance] = await Promise.all([
getIdentity(args?.identity, context),
checkpoint.balance(args),
]);
const isTarget = !!targetIdentities.find(target => identity.isEqual(target));
let participant: DistributionParticipant;
const isExclusion = treatment === TargetTreatment.Exclude;
if (balance.gt(0) && xor(isTarget, isExclusion)) {
participant = this.assembleParticipant(identity, balance);
} else {
return null;
}
// participant can't be paid before the payment date
if (paymentDate < new Date()) {
return participant;
}
const rawDid = stringToIdentityId(identity.did, context);
const rawCaId = corporateActionIdentifierToCaId({ ticker, localId }, context);
const holderPaid = await query.capitalDistribution.holderPaid([rawCaId, rawDid]);
const paid = boolToBoolean(holderPaid);
return { ...participant, paid };
}
/**
* @hidden
*/
private assembleParticipant(identity: Identity, balance: BigNumber): DistributionParticipant {
const { defaultTaxWithholding, taxWithholdings, perShare } = this;
let taxWithholdingPercentage = defaultTaxWithholding;
const taxWithholding = taxWithholdings.find(({ identity: taxIdentity }) =>
identity.isEqual(taxIdentity)
);
if (taxWithholding) {
taxWithholdingPercentage = taxWithholding.percentage;
}
const amount = balance.multipliedBy(perShare);
const amountAfterTax = amount
.minus(
amount.multipliedBy(taxWithholdingPercentage).dividedBy(100).decimalPlaces(MAX_DECIMALS)
)
.decimalPlaces(MAX_DECIMALS);
return {
identity,
amount,
taxWithholdingPercentage,
amountAfterTax,
paid: false,
};
}
/**
* @hidden
*/
private fetchDistribution(): Promise<Option<PalletCorporateActionsDistribution>> {
const {
asset: { ticker },
id,
context,
} = this;
return context.polymeshApi.query.capitalDistribution.distributions(
corporateActionIdentifierToCaId({ ticker, localId: id }, context)
);
}
/**
* Retrieve the amount of taxes that have been withheld up to this point in this Distribution
*
* @note uses the middlewareV2
*/
public async getWithheldTax(): Promise<BigNumber> {
const {
id,
asset: { ticker },
context,
} = this;
const taxPromise = context.queryMiddleware<Ensured<Query, 'distribution'>>(
distributionQuery({
id: `${ticker}/${id.toString()}`,
})
);
const [
exists,
{
data: {
distribution: { taxes },
},
},
] = await Promise.all([this.exists(), taxPromise]);
if (!exists) {
throw new PolymeshError({
code: ErrorCode.DataUnavailable,
message: notExistsMessage,
});
}
return new BigNumber(taxes).shiftedBy(-6);
}
/**
* Retrieve the payment history for this Distribution
*
* @note uses the middleware V2
* @note supports pagination
*/
public async getPaymentHistory(
opts: { size?: BigNumber; start?: BigNumber } = {}
): Promise<ResultSet<DistributionPayment>> {
const {
id,
asset: { ticker },
context,
} = this;
const { size, start } = opts;
const paymentsPromise = context.queryMiddleware<Ensured<Query, 'distributionPayments'>>(
distributionPaymentsQuery(
{
distributionId: `${ticker}/${id.toString()}`,
},
size,
start
)
);
const [exists, result] = await Promise.all([this.exists(), paymentsPromise]);
if (!exists) {
throw new PolymeshError({
code: ErrorCode.DataUnavailable,
message: notExistsMessage,
});
}
const {
data: {
distributionPayments: { nodes, totalCount },
},
} = result;
const count = new BigNumber(totalCount);
const data: DistributionPayment[] = [];
nodes.forEach(({ createdBlock, datetime, targetId: did, amount, tax }) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const { blockId, hash } = createdBlock!;
data.push({
blockNumber: new BigNumber(blockId),
blockHash: hash,
date: new Date(datetime),
target: new Identity({ did }, context),
amount: new BigNumber(amount).shiftedBy(-6),
/**
* Since we want to depict the `withheldTax` as percentage value between 0-100,
* we multiply the tax(`Permill`) by 100, hence shifted by -4
*/
withheldTax: new BigNumber(tax).shiftedBy(-4),
});
});
const next = calculateNextKey(count, data.length, start);
return {
data,
next,
count,
};
}
/**
* @hidden
*/
private async getParticipantStatuses(
participants: DistributionParticipant[]
): Promise<boolean[]> {
const {
asset: { ticker },
id: localId,
context: {
polymeshApi: {
query: { capitalDistribution },
},
},
context,
} = this;
/*
* For optimization, we separate the participants into chunks that can fit into one multi call
* and then sequentially perform bunches of said multi requests in parallel
*/
const participantChunks = chunk(participants, MAX_PAGE_SIZE.toNumber());
const parallelCallChunks = chunk(participantChunks, MAX_CONCURRENT_REQUESTS);
let paidStatuses: boolean[] = [];
const caId = corporateActionIdentifierToCaId({ localId, ticker }, context);
await P.each(parallelCallChunks, async callChunk => {
const parallelMultiCalls = callChunk.map(participantChunk => {
const multiParams = participantChunk.map(({ identity: { did } }) =>
tuple(caId, stringToIdentityId(did, context))
);
return capitalDistribution.holderPaid.multi(multiParams);
});
const results = await Promise.all(parallelMultiCalls);
paidStatuses = [...paidStatuses, ...flatten(results).map(paid => boolToBoolean(paid))];
});
return paidStatuses;
}
/**
* Return the Dividend Distribution's static data
*/
public override toHuman(): HumanReadable {
const { origin, currency, perShare, maxAmount, expiryDate, paymentDate } = this;
const parentReadable = super.toHuman();
return {
...toHumanReadable({ origin, currency, perShare, maxAmount, expiryDate, paymentDate }),
...parentReadable,
};
}
}