generated from PolymeshAssociation/typescript-boilerplate
/
index.ts
380 lines (327 loc) · 9.86 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
import BigNumber from 'bignumber.js';
import { values } from 'lodash';
import {
Account,
Context,
Entity,
Identity,
moveFunds,
MoveFundsParams,
PolymeshError,
quitCustody,
SecurityToken,
setCustodian,
SetCustodianParams,
} from '~/internal';
import { settlements } from '~/middleware/queries';
import { Query } from '~/middleware/types';
import { Ensured, ErrorCode, ProcedureMethod, ResultSet } from '~/types';
import {
addressToKey,
balanceToBigNumber,
identityIdToString,
keyToAddress,
middlewarePortfolioToPortfolio,
portfolioIdToMeshPortfolioId,
tickerToString,
} from '~/utils/conversion';
import {
calculateNextKey,
createProcedureMethod,
getDid,
getToken,
toHumanReadable,
} from '~/utils/internal';
import { HistoricSettlement, PortfolioBalance } from './types';
export interface UniqueIdentifiers {
did: string;
id?: BigNumber;
}
interface HumanReadable {
did: string;
id?: string;
}
const notExistsMessage = 'The Portfolio was removed and no longer exists';
/**
* Represents a base Portfolio for a specific Identity in the Polymesh blockchain
*/
export abstract class Portfolio extends Entity<UniqueIdentifiers, HumanReadable> {
/**
* @hidden
* Check if a value is of type [[UniqueIdentifiers]]
*/
public static isUniqueIdentifiers(identifier: unknown): identifier is UniqueIdentifiers {
const { did, id } = identifier as UniqueIdentifiers;
return typeof did === 'string' && (id === undefined || id instanceof BigNumber);
}
/**
* identity of the Portfolio's owner
*/
public owner: Identity;
/**
* internal Portfolio identifier (unused for default Portfolio)
*/
protected _id?: BigNumber;
/**
* @hidden
*/
public constructor(identifiers: UniqueIdentifiers, context: Context) {
super(identifiers, context);
const { did, id } = identifiers;
this.owner = new Identity({ did }, context);
this._id = id;
this.setCustodian = createProcedureMethod(
{ getProcedureAndArgs: args => [setCustodian, { ...args, did, id }] },
context
);
this.moveFunds = createProcedureMethod(
{ getProcedureAndArgs: args => [moveFunds, { ...args, from: this }] },
context
);
this.quitCustody = createProcedureMethod(
{ getProcedureAndArgs: () => [quitCustody, { portfolio: this }] },
context
);
}
/**
* Return whether an Identity is the Portfolio owner
*
* @param args.identity - defaults to the current Identity
*/
public async isOwnedBy(args?: { identity: string | Identity }): Promise<boolean> {
const {
owner: { did: ownerDid },
context,
} = this;
const did = await getDid(args?.identity, context);
return ownerDid === did;
}
/**
* Return whether an Identity is the Portfolio custodian
*
* @param args.identity - optional, defaults to the current Identity
*/
public async isCustodiedBy(args?: { identity: string | Identity }): Promise<boolean> {
const { context } = this;
const [portfolioCustodian, targetDid] = await Promise.all([
this.getCustodian(),
getDid(args?.identity, context),
]);
return portfolioCustodian.did === targetDid;
}
/**
* Retrieve the balances of all assets in this Portfolio
*
* @param args.tokens - array of Security Tokens (or tickers) for which to fetch balances (optional, all balances are retrieved if not passed)
*/
public async getTokenBalances(args?: {
tokens: (string | SecurityToken)[];
}): Promise<PortfolioBalance[]> {
const {
owner: { did },
_id: number,
context: {
polymeshApi: {
query: { portfolio },
},
},
context,
} = this;
const rawPortfolioId = portfolioIdToMeshPortfolioId({ did, number }, context);
const [exists, totalBalanceEntries, lockedBalanceEntries] = await Promise.all([
this.exists(),
portfolio.portfolioAssetBalances.entries(rawPortfolioId),
portfolio.portfolioLockedAssets.entries(rawPortfolioId),
]);
if (!exists) {
throw new PolymeshError({
code: ErrorCode.DataUnavailable,
message: notExistsMessage,
});
}
const assetBalances: Record<string, PortfolioBalance> = {};
totalBalanceEntries.forEach(([key, balance]) => {
const ticker = tickerToString(key.args[1]);
const total = balanceToBigNumber(balance);
assetBalances[ticker] = {
token: new SecurityToken({ ticker }, context),
total,
locked: new BigNumber(0),
free: total,
};
});
lockedBalanceEntries.forEach(([key, balance]) => {
const ticker = tickerToString(key.args[1]);
const locked = balanceToBigNumber(balance);
assetBalances[ticker].locked = locked;
assetBalances[ticker].free = assetBalances[ticker].total.minus(locked);
});
const mask: PortfolioBalance[] | undefined = args?.tokens.map(token => ({
total: new BigNumber(0),
locked: new BigNumber(0),
free: new BigNumber(0),
token: getToken(token, context),
}));
if (mask) {
return mask.map(portfolioBalance => {
const {
token: { ticker },
} = portfolioBalance;
return assetBalances[ticker] ?? portfolioBalance;
});
}
return values(assetBalances);
}
/**
* Send an invitation to an Identity to assign it as custodian for this Portfolio
*
* @note this may create an AuthorizationRequest which has to be accepted by
* the corresponding Identity. An Account or Identity can
* fetch its pending Authorization Requests by calling `authorizations.getReceived`
*
* @note required role:
* - Portfolio Custodian
*/
public setCustodian: ProcedureMethod<SetCustodianParams, void>;
/**
* Moves funds from this Portfolio to another one owned by the same Identity
*
* @note required role:
* - Portfolio Custodian
*/
public moveFunds: ProcedureMethod<MoveFundsParams, void>;
/**
* Returns the custody of the portfolio to the portfolio owner unilaterally
*
* @note required role:
* - Portfolio Custodian
*/
public quitCustody: ProcedureMethod<void, void>;
/**
* Retrieve the custodian Identity of this Portfolio
*
* @note if no custodian is set, the owner Identity is returned
*/
public async getCustodian(): Promise<Identity> {
const {
owner,
owner: { did },
_id: number,
context: {
polymeshApi: {
query: { portfolio },
},
},
context,
} = this;
const rawPortfolioId = portfolioIdToMeshPortfolioId({ did, number }, context);
const [portfolioCustodian, exists] = await Promise.all([
portfolio.portfolioCustodian(rawPortfolioId),
this.exists(),
]);
if (!exists) {
throw new PolymeshError({
code: ErrorCode.DataUnavailable,
message: notExistsMessage,
});
}
try {
const rawIdentityId = portfolioCustodian.unwrap();
return new Identity({ did: identityIdToString(rawIdentityId) }, context);
} catch (_) {
return owner;
}
}
/**
* Retrieve a list of transactions where this portfolio was involved. Can be filtered using parameters
*
* @param filters.account - account involved in the settlement
* @param filters.ticker - ticker involved in the transaction
* @param filters.size - page size
* @param filters.start - page offset
*
* @note supports pagination
* @note uses the middleware
*/
public async getTransactionHistory(
filters: {
account?: string;
ticker?: string;
size?: number;
start?: number;
} = {}
): Promise<ResultSet<HistoricSettlement>> {
const {
context,
owner: { did },
_id: number,
} = this;
const { account, ticker, size, start } = filters;
const settlementsPromise = context.queryMiddleware<Ensured<Query, 'settlements'>>(
settlements({
identityId: did,
portfolioNumber: number ? number.toString() : null,
addressFilter: account ? addressToKey(account, context) : undefined,
tickerFilter: ticker,
count: size,
skip: start,
})
);
const [result, exists] = await Promise.all([settlementsPromise, this.exists()]);
if (!exists) {
throw new PolymeshError({
code: ErrorCode.DataUnavailable,
message: notExistsMessage,
});
}
const {
data: { settlements: settlementsResult },
} = result;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const { items, totalCount: count } = settlementsResult!;
const data: HistoricSettlement[] = [];
let next = null;
if (items) {
items.forEach(item => {
/* eslint-disable @typescript-eslint/no-non-null-assertion */
const { block_id: blockId, result: status, addresses, legs: settlementLegs } = item!;
data.push({
blockNumber: new BigNumber(blockId),
status,
accounts: addresses!.map(
address => new Account({ address: keyToAddress('0x' + address, context) }, context)
),
legs: settlementLegs.map(leg => {
return {
token: new SecurityToken({ ticker: leg!.ticker }, context),
amount: new BigNumber(leg!.amount).shiftedBy(-6),
direction: leg!.direction,
from: middlewarePortfolioToPortfolio(leg!.from, context),
to: middlewarePortfolioToPortfolio(leg!.to, context),
};
}),
});
/* eslint-enabled @typescript-eslint/no-non-null-assertion */
});
next = calculateNextKey(count, size, start);
}
return {
data,
next,
count,
};
}
/**
* Return the Portfolio ID and owner DID
*/
public toJson(): HumanReadable {
const {
_id: id,
owner: { did },
} = this;
const result = {
did,
};
return id ? toHumanReadable({ ...result, id }) : result;
}
}