generated from PolymeshAssociation/typescript-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 11
/
addInstruction.ts
294 lines (256 loc) · 9.27 KB
/
addInstruction.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
import { Option, u32, u64 } from '@polkadot/types';
import { Balance, Moment } from '@polkadot/types/interfaces';
import { ISubmittableResult } from '@polkadot/types/types';
import BigNumber from 'bignumber.js';
import { PortfolioId, SettlementType, Ticker } from 'polymesh-types/types';
import sinon from 'sinon';
import { Instruction } from '~/api/entities';
import {
createAddInstructionResolver,
getRequiredRoles,
Params,
prepareAddInstruction,
} from '~/api/procedures/addInstruction';
import { Context, PostTransactionValue } from '~/base';
import { dsMockUtils, entityMockUtils, procedureMockUtils } from '~/testUtils/mocks';
import { Mocked } from '~/testUtils/types';
import { InstructionType, RoleType, TickerReservationStatus } from '~/types';
import { PolymeshTx } from '~/types/internal';
import * as utilsModule from '~/utils';
describe('addInstruction procedure', () => {
let mockContext: Mocked<Context>;
let portfolioIdToMeshPortfolioIdStub: sinon.SinonStub;
let stringToTickerStub: sinon.SinonStub<[string, Context], Ticker>;
let numberToU64Stub: sinon.SinonStub<[number | BigNumber, Context], u64>;
let numberToBalanceStub: sinon.SinonStub<
[number | BigNumber, Context, (boolean | undefined)?],
Balance
>;
let endConditionToSettlementTypeStub: sinon.SinonStub<
[
(
| { type: InstructionType.SettleOnAuthorization }
| { type: InstructionType.SettleOnBlock; value: BigNumber }
),
Context
],
SettlementType
>;
let dateToMomentStub: sinon.SinonStub<[Date, Context], Moment>;
let venueId: BigNumber;
let amount: BigNumber;
let from: string;
let to: string;
let token: string;
let validFrom: Date;
let endBlock: BigNumber;
let args: Params;
let rawVenueId: u64;
let rawAmount: Balance;
let rawFrom: PortfolioId;
let rawTo: PortfolioId;
let rawToken: Ticker;
let rawValidFrom: Moment;
let rawEndBlock: u32;
let rawAuthSettlementType: SettlementType;
let rawBlockSettlementType: SettlementType;
let rawLeg: { from: PortfolioId; to: PortfolioId; asset: Ticker; amount: Balance };
let instruction: PostTransactionValue<Instruction>;
beforeAll(() => {
dsMockUtils.initMocks({
contextOptions: { balance: { free: new BigNumber(500), locked: new BigNumber(0) } },
});
procedureMockUtils.initMocks();
entityMockUtils.initMocks();
portfolioIdToMeshPortfolioIdStub = sinon.stub(utilsModule, 'portfolioIdToMeshPortfolioId');
stringToTickerStub = sinon.stub(utilsModule, 'stringToTicker');
numberToU64Stub = sinon.stub(utilsModule, 'numberToU64');
numberToBalanceStub = sinon.stub(utilsModule, 'numberToBalance');
endConditionToSettlementTypeStub = sinon.stub(utilsModule, 'endConditionToSettlementType');
dateToMomentStub = sinon.stub(utilsModule, 'dateToMoment');
venueId = new BigNumber(1);
amount = new BigNumber(100);
from = 'fromDid';
to = 'toDid';
token = 'SOME_TOKEN';
validFrom = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
endBlock = new BigNumber(1000);
rawVenueId = dsMockUtils.createMockU64(venueId.toNumber());
rawAmount = dsMockUtils.createMockBalance(amount.toNumber());
rawFrom = dsMockUtils.createMockPortfolioId({
did: dsMockUtils.createMockIdentityId(from),
kind: dsMockUtils.createMockPortfolioKind('Default'),
});
rawTo = dsMockUtils.createMockPortfolioId({
did: dsMockUtils.createMockIdentityId(to),
kind: dsMockUtils.createMockPortfolioKind('Default'),
});
rawToken = dsMockUtils.createMockTicker(token);
rawValidFrom = dsMockUtils.createMockMoment(validFrom.getTime());
rawEndBlock = dsMockUtils.createMockU32(endBlock.toNumber());
rawAuthSettlementType = dsMockUtils.createMockSettlementType('SettleOnAuthorization');
rawBlockSettlementType = dsMockUtils.createMockSettlementType({ SettleOnBlock: rawEndBlock });
rawLeg = {
from: rawFrom,
to: rawTo,
amount: rawAmount,
asset: rawToken,
};
args = {
venueId,
legs: [
{
from,
to,
token,
amount,
},
],
};
instruction = ('instruction' as unknown) as PostTransactionValue<Instruction>;
});
let addTransactionStub: sinon.SinonStub;
let addAndAuthorizeInstructionTransaction: PolymeshTx<[
u64,
SettlementType,
Option<Moment>,
{ from: PortfolioId; to: PortfolioId; asset: Ticker; amount: Balance }[],
PortfolioId[]
]>;
let addInstructionTransaction: PolymeshTx<[
u64,
SettlementType,
Option<Moment>,
{ from: PortfolioId; to: PortfolioId; asset: Ticker; amount: Balance }[]
]>;
beforeEach(() => {
addTransactionStub = procedureMockUtils.getAddTransactionStub().returns([instruction]);
entityMockUtils.getTickerReservationDetailsStub().resolves({
owner: entityMockUtils.getIdentityInstance(),
expiryDate: null,
status: TickerReservationStatus.Free,
});
addAndAuthorizeInstructionTransaction = dsMockUtils.createTxStub(
'settlement',
'addAndAuthorizeInstruction'
);
addInstructionTransaction = dsMockUtils.createTxStub('settlement', 'addInstruction');
mockContext = dsMockUtils.getContextInstance();
portfolioIdToMeshPortfolioIdStub.withArgs({ did: from }, mockContext).returns(rawFrom);
portfolioIdToMeshPortfolioIdStub.withArgs({ did: to }, mockContext).returns(rawTo);
stringToTickerStub.withArgs(token, mockContext).returns(rawToken);
numberToU64Stub.withArgs(venueId, mockContext).returns(rawVenueId);
numberToBalanceStub.withArgs(amount, mockContext).returns(rawAmount);
endConditionToSettlementTypeStub
.withArgs({ type: InstructionType.SettleOnBlock, value: endBlock }, mockContext)
.returns(rawBlockSettlementType);
endConditionToSettlementTypeStub
.withArgs({ type: InstructionType.SettleOnAuthorization }, mockContext)
.returns(rawAuthSettlementType);
dateToMomentStub.withArgs(validFrom, mockContext).returns(rawValidFrom);
});
afterEach(() => {
entityMockUtils.reset();
procedureMockUtils.reset();
dsMockUtils.reset();
});
afterAll(() => {
entityMockUtils.cleanup();
procedureMockUtils.cleanup();
dsMockUtils.cleanup();
});
test('should throw an error if the legs array is empty', async () => {
const proc = procedureMockUtils.getInstance<Params, Instruction>(mockContext);
let error;
try {
await prepareAddInstruction.call(proc, { ...args, legs: [] });
} catch (err) {
error = err;
}
expect(error.message).toBe("The legs array can't be empty");
});
test('should throw an error if the end block is in the past', async () => {
dsMockUtils.configureMocks({ contextOptions: { latestBlock: new BigNumber(1000) } });
const proc = procedureMockUtils.getInstance<Params, Instruction>(mockContext);
let error;
try {
await prepareAddInstruction.call(proc, { ...args, endBlock: new BigNumber(100) });
} catch (err) {
error = err;
}
expect(error.message).toBe('End block must be a future block');
});
test('should add an add and authorize instruction transaction to the queue', async () => {
dsMockUtils.configureMocks({ contextOptions: { did: from } });
const proc = procedureMockUtils.getInstance<Params, Instruction>(mockContext);
const result = await prepareAddInstruction.call(proc, args);
sinon.assert.calledWith(
addTransactionStub,
addAndAuthorizeInstructionTransaction,
sinon.match({
resolvers: sinon.match.array,
}),
rawVenueId,
rawAuthSettlementType,
null,
[rawLeg],
[rawFrom]
);
expect(result).toBe(instruction);
});
test('should add an add instruction transaction to the queue', async () => {
const proc = procedureMockUtils.getInstance<Params, Instruction>(mockContext);
const result = await prepareAddInstruction.call(proc, {
...args,
legs: [
{ from, to, amount, token: entityMockUtils.getSecurityTokenInstance({ ticker: token }) },
],
validFrom,
endBlock,
});
sinon.assert.calledWith(
addTransactionStub,
addInstructionTransaction,
sinon.match({
resolvers: sinon.match.array,
}),
rawVenueId,
rawBlockSettlementType,
rawValidFrom,
[rawLeg]
);
expect(result).toBe(instruction);
});
});
describe('getRequiredRoles', () => {
test('should return a venue owner role', () => {
const venueId = new BigNumber(100);
const args = {
venueId,
} as Params;
expect(getRequiredRoles(args)).toEqual([{ type: RoleType.VenueOwner, venueId }]);
});
});
describe('createAddInstructionResolver', () => {
const findEventRecordStub = sinon.stub(utilsModule, 'findEventRecord');
const id = new BigNumber(10);
const rawId = dsMockUtils.createMockU64(id.toNumber());
beforeAll(() => {
entityMockUtils.initMocks({
instructionOptions: {
id,
},
});
});
beforeEach(() => {
findEventRecordStub.returns(dsMockUtils.createMockEventRecord(['did', 'venueId', rawId]));
});
afterEach(() => {
findEventRecordStub.reset();
});
test('should return the new Instruction', () => {
const fakeContext = {} as Context;
const result = createAddInstructionResolver(fakeContext)({} as ISubmittableResult);
expect(result.id).toEqual(id);
});
});