generated from PolymeshAssociation/typescript-boilerplate
/
setTransferRestrictions.ts
324 lines (282 loc) · 10.1 KB
/
setTransferRestrictions.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
import { U8aFixed } from '@polkadot/types';
import BigNumber from 'bignumber.js';
import P from 'bluebird';
import { difference, differenceWith, isEqual } from 'lodash';
import { Ticker, TransferManager, TxTag } from 'polymesh-types/types';
import { Asset, PolymeshError, Procedure } from '~/internal';
import {
CountTransferRestrictionInput,
ErrorCode,
PercentageTransferRestrictionInput,
TransferRestriction,
TransferRestrictionType,
TxTags,
} from '~/types';
import { ProcedureAuthorization } from '~/types/internal';
import { tuple } from '~/types/utils';
import {
stringToScopeId,
stringToTicker,
transferRestrictionToTransferManager,
u32ToBigNumber,
} from '~/utils/conversion';
import { assembleBatchTransactions, defusePromise, getExemptedIds } from '~/utils/internal';
export interface SetCountTransferRestrictionsParams {
/**
* array of Count Transfer Restrictions with their corresponding exemptions (if applicable)
*/
restrictions: CountTransferRestrictionInput[];
type: TransferRestrictionType.Count;
}
export interface SetPercentageTransferRestrictionsParams {
/**
* array of Percentage Transfer Restrictions with their corresponding exemptions (if applicable)
*/
restrictions: PercentageTransferRestrictionInput[];
type: TransferRestrictionType.Percentage;
}
export type SetTransferRestrictionsParams = { ticker: string } & (
| SetCountTransferRestrictionsParams
| SetPercentageTransferRestrictionsParams
);
/**
* @hidden
*/
export interface Storage {
restrictionsToAdd: [Ticker, TransferManager][];
restrictionsToRemove: [Ticker, TransferManager][];
exemptionsToAdd: [Ticker, TransferManager, U8aFixed[]][];
exemptionsToRemove: [Ticker, TransferManager, U8aFixed[]][];
occupiedSlots: BigNumber;
}
/**
* @hidden
*/
export async function prepareSetTransferRestrictions(
this: Procedure<SetTransferRestrictionsParams, BigNumber, Storage>,
args: SetTransferRestrictionsParams
): Promise<BigNumber> {
const {
context: {
polymeshApi: {
tx: { statistics },
consts,
},
},
storage: {
restrictionsToAdd,
restrictionsToRemove,
exemptionsToAdd,
exemptionsToRemove,
occupiedSlots,
},
} = this;
const {
restrictions: { length: newRestrictionAmount },
} = args;
const restrictionsToAddAmount = restrictionsToAdd.length;
const restrictionsToRemoveAmount = restrictionsToRemove.length;
const exemptionsToAddAmount = exemptionsToAdd.length;
const exemptionsToRemoveAmount = exemptionsToRemove.length;
if (
!restrictionsToAddAmount &&
!restrictionsToRemoveAmount &&
!exemptionsToAddAmount &&
!exemptionsToRemoveAmount
) {
throw new PolymeshError({
code: ErrorCode.NoDataChange,
message: newRestrictionAmount
? 'The supplied restrictions are already in place'
: 'There are no restrictions to remove',
});
}
const maxTransferManagers = u32ToBigNumber(consts.statistics.maxTransferManagersPerAsset);
const finalCount = occupiedSlots.plus(newRestrictionAmount);
if (finalCount.gte(maxTransferManagers)) {
throw new PolymeshError({
code: ErrorCode.LimitExceeded,
message: 'Cannot set more Transfer Restrictions than there are slots available',
data: {
availableSlots: maxTransferManagers.minus(occupiedSlots),
},
});
}
const transactions = assembleBatchTransactions(
tuple(
{
transaction: statistics.removeTransferManager,
argsArray: restrictionsToRemove,
},
{
transaction: statistics.addTransferManager,
argsArray: restrictionsToAdd,
},
{
transaction: statistics.removeExemptedEntities,
argsArray: exemptionsToRemove,
},
{
transaction: statistics.addExemptedEntities,
argsArray: exemptionsToAdd,
}
)
);
this.addBatchTransaction({ transactions });
return finalCount;
}
/**
* @hidden
*/
export function getAuthorization(
this: Procedure<SetTransferRestrictionsParams, BigNumber, Storage>,
{ ticker }: SetTransferRestrictionsParams
): ProcedureAuthorization {
const { restrictionsToRemove, restrictionsToAdd, exemptionsToAdd, exemptionsToRemove } =
this.storage;
const transactions: TxTag[] = [];
if (restrictionsToAdd.length) {
transactions.push(TxTags.statistics.AddTransferManager);
}
if (restrictionsToRemove.length) {
transactions.push(TxTags.statistics.RemoveTransferManager);
}
if (exemptionsToAdd.length) {
transactions.push(TxTags.statistics.AddExemptedEntities);
}
if (exemptionsToRemove.length) {
transactions.push(TxTags.statistics.RemoveExemptedEntities);
}
return {
permissions: {
assets: [new Asset({ ticker }, this.context)],
transactions,
portfolios: [],
},
};
}
/**
* @hidden
*/
export async function prepareStorage(
this: Procedure<SetTransferRestrictionsParams, BigNumber, Storage>,
args: SetTransferRestrictionsParams
): Promise<Storage> {
const { context } = this;
const { ticker, type, restrictions } = args;
const rawTicker = stringToTicker(ticker, context);
const {
transferRestrictions: { count, percentage },
} = new Asset({ ticker }, context);
const [
{ restrictions: currentCountRestrictions },
{ restrictions: currentPercentageRestrictions },
] = await Promise.all([count.get(), percentage.get()]);
const currentRestrictions: TransferRestriction[] = [];
const currentExemptions: [TransferRestriction, string[]][] = [];
const toAddRestrictions: TransferRestriction[] = [];
const toAddExemptionPromises: [TransferRestriction, Promise<string[]>][] = [];
let occupiedSlots = currentCountRestrictions.length + currentPercentageRestrictions.length;
/*
* we're using `defusePromise` here because we KNOW the exempted ID promises are being
* awaited later and errors WILL be caught
*/
if (type === TransferRestrictionType.Count) {
restrictions.forEach(({ exemptedIdentities = [], count: value }) => {
const restriction = { type: TransferRestrictionType.Count, value };
toAddRestrictions.push(restriction);
toAddExemptionPromises.push(
tuple(restriction, defusePromise(getExemptedIds(exemptedIdentities, context, ticker)))
);
});
currentCountRestrictions.forEach(({ exemptedIds = [], count: value }) => {
const restriction = { type: TransferRestrictionType.Count, value };
currentRestrictions.push(restriction);
currentExemptions.push(tuple(restriction, exemptedIds));
});
} else {
restrictions.forEach(({ exemptedIdentities = [], percentage: value }) => {
const restriction = { type: TransferRestrictionType.Percentage, value };
toAddRestrictions.push(restriction);
toAddExemptionPromises.push(
tuple(restriction, defusePromise(getExemptedIds(exemptedIdentities, context, ticker)))
);
});
currentPercentageRestrictions.forEach(({ exemptedIds = [], percentage: value }) => {
const restriction = { type: TransferRestrictionType.Percentage, value };
currentRestrictions.push(restriction);
currentExemptions.push(tuple(restriction, exemptedIds));
});
}
const toAddExemptions = await P.map(
toAddExemptionPromises,
async ([restriction, exemptedPromise]) => {
const exempted = await exemptedPromise;
return tuple(restriction, exempted);
}
);
const newRestrictions = differenceWith(toAddRestrictions, currentRestrictions, isEqual);
const toRemoveRestrictions = differenceWith(currentRestrictions, toAddRestrictions, isEqual);
const transformRestriction = (restriction: TransferRestriction): [Ticker, TransferManager] =>
tuple(rawTicker, transferRestrictionToTransferManager(restriction, context));
const restrictionsToRemove = toRemoveRestrictions.map(transformRestriction);
const restrictionsToAdd = newRestrictions.map(transformRestriction);
occupiedSlots -= currentRestrictions.length;
const newExemptions: [TransferRestriction, string[]][] = [];
const toRemoveExemptions: [TransferRestriction, string[]][] = [];
toAddExemptions.forEach(exemption => {
const [restriction, exempted] = exemption;
if (newRestrictions.find(res => isEqual(restriction, res)) && exempted.length) {
newExemptions.push(exemption);
return;
}
const currentExemption = currentExemptions.find(([res]) => isEqual(res, restriction));
const currentExempted = currentExemption?.[1] || [];
// Scope/Identity IDs that weren't exempted before for that restriction
const newExempted = difference(exempted, currentExempted);
if (newExempted.length) {
newExemptions.push(tuple(restriction, newExempted));
}
// Scope/Identity IDs that will no longer be exempted for that restriction
const toRemoveExempted = difference(currentExempted, exempted);
if (toRemoveExempted.length) {
toRemoveExemptions.push(tuple(restriction, toRemoveExempted));
}
});
// also remove all exemptions of the restrictions that will be removed
toRemoveRestrictions.forEach(restriction => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const [, currentExempted] = currentExemptions.find(([res]) => isEqual(res, restriction))!;
if (currentExempted.length) {
toRemoveExemptions.push(tuple(restriction, currentExempted));
}
});
const transformExemptions = ([restriction, entityIds]: [TransferRestriction, string[]]): [
Ticker,
TransferManager,
U8aFixed[]
] =>
tuple(
rawTicker,
transferRestrictionToTransferManager(restriction, context),
// we use `stringToScopeId` because both `ScopeId` and `IdentityId` are aliases for `U8aFixed`
entityIds.map(entityId => stringToScopeId(entityId, context))
);
const exemptionsToAdd = newExemptions.map(transformExemptions);
const exemptionsToRemove = toRemoveExemptions.map(transformExemptions);
return {
restrictionsToRemove,
restrictionsToAdd,
exemptionsToAdd,
exemptionsToRemove,
occupiedSlots: new BigNumber(occupiedSlots),
};
}
/**
* @hidden
*/
export const setTransferRestrictions = (): Procedure<
SetTransferRestrictionsParams,
BigNumber,
Storage
> => new Procedure(prepareSetTransferRestrictions, getAuthorization, prepareStorage);