-
Notifications
You must be signed in to change notification settings - Fork 53
/
utils.ts
546 lines (491 loc) · 16.4 KB
/
utils.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
import { Address, Tuple, TupleItem, TupleItemInt, TupleReader, toNano } from "ton";
import { Cell, Slice, Sender, SenderArguments, ContractProvider, Message, beginCell, Dictionary, MessageRelaxed, Transaction, fromNano } from "ton-core";
import { Blockchain, BlockchainTransaction, MessageParams, SendMessageResult, SmartContract, SmartContractTransaction } from "@ton-community/sandbox";
import { computeMessageForwardFees, MsgPrices } from "./fees";
import { Op } from "./PoolConstants";
import { MessageValue } from "ton-core/dist/types/Message";
import { compareTransaction, flattenTransaction, FlatTransactionComparable } from "@ton-community/test-utils";
import { extractEvents } from "@ton-community/sandbox/dist/event/Event";
const randomAddress = (wc: number = 0) => {
const buf = Buffer.alloc(32);
for (let i = 0; i < buf.length; i++) {
buf[i] = Math.floor(Math.random() * 256);
}
return new Address(wc, buf);
};
const differentAddress = (oldAddr:Address) => {
let newAddr = oldAddr;
do {
newAddr = randomAddress(newAddr.workChain);
} while(newAddr.equals(oldAddr));
return newAddr;
}
export function findCommon(s1: string, s2: string): number {
let i = 0;
while (i < s1.length && s1[i] === s2[i])
i++;
return i;
}
export const getRandom = (min:number, max:number) => {
return Math.random() * (max - min) + min;
}
enum roundMode {floor, ceil, round};
export const getRandomInt = (min:number, max:number, mode: roundMode = roundMode.floor) => {
let res = getRandom(min, max);
if(mode == roundMode.floor) {
res = Math.floor(res);
}
else if(mode == roundMode.ceil) {
res = Math.ceil(res);
}
else {
res = Math.round(res);
}
return res;
}
export const getRandomTon = (min:number | string | bigint, max:number | string | bigint): bigint => {
let minVal: number;
let maxVal: number;
// Meh
if(typeof min == 'number') {
minVal = min;
}
else if(typeof min == 'string') {
minVal = Number(min);
}
else {
minVal = Number(fromNano(min));
}
if(typeof max == 'number') {
maxVal = max;
}
else if(typeof max == 'string') {
maxVal = Number(max.split('.')[0]);
}
else {
maxVal = Number(fromNano(max).split('.')[0]);
}
return toNano(getRandom(minVal, maxVal).toFixed(9));
}
export const buff2bigint = (buff: Buffer) : bigint => {
return BigInt("0x" + buff.toString("hex"));
}
export const bigint2buff = (num:bigint) : Buffer => {
return Buffer.from(num.toString(16), 'hex')
}
export const computedGeneric = (trans:Transaction) => {
if(trans.description.type !== "generic")
throw("Expected generic transaction");
if(trans.description.computePhase.type !== "vm")
throw("Compute phase expected")
return trans.description.computePhase;
};
export const getMsgExcess = (trans:Transaction, msg:Message, value:bigint, msgConf:MsgPrices) => {
const fwdFees = computeMessageForwardFees(msgConf, msg);
return value - computedGeneric(trans).gasFees - fwdFees.remaining - fwdFees.fees;
}
export const sendBulkMessage = async (msg: Message,
smc:SmartContract,
count:number,
cb: (res:SmartContractTransaction,n:number) => Promise<void>,
params?: MessageParams )=> {
for ( let i = 0; i < count; i++ ) {
await cb(await smc.receiveMessage(msg, params), i);
}
}
interface IAny {}
interface TupleReaderConstructor <T extends IAny>{
new (...args: any[]) : T
fromReader(rdr: TupleReader) : T;
}
class TupleReaderFactory<T extends IAny>{
private constructable: TupleReaderConstructor<T>;
constructor(constructable: TupleReaderConstructor<T>) {
this.constructable = constructable;
}
createObject(rdr: TupleReader) : T {
return this.constructable.fromReader(rdr);
}
}
class LispIterator <T extends IAny> implements Iterator <T> {
private curItem:TupleReader | null;
private done:boolean;
private ctor: TupleReaderFactory<T>;
constructor(tuple:TupleReader | null, ctor: TupleReaderFactory<T>) {
this.done = false; //tuple === null || tuple.remaining == 0;
this.curItem = tuple;
this.ctor = ctor;
}
public next(): IteratorResult<T> {
this.done = this.curItem === null || this.curItem.remaining == 0;
let value: TupleReader;
if( ! this.done) {
const head = this.curItem!.readTuple();
const tail = this.curItem!.readTupleOpt();
if(tail !== null) {
this.curItem = tail;
}
value = head;
return {done: this.done, value: this.ctor.createObject(value)};
}
else {
return {done: true, value: null}
}
}
}
export class LispList <T extends IAny> {
private tuple: TupleReader | null;
private ctor: TupleReaderFactory<T>;
constructor(tuple: TupleReader | null, ctor: TupleReaderConstructor<T>) {
this.tuple = tuple;
this.ctor = new TupleReaderFactory(ctor);
}
toArray() : T[] {
return [...this];
}
[Symbol.iterator]() {
return new LispIterator(this.tuple, this.ctor);
}
}
export const muldivExtra = (a: bigint, b: bigint, c: bigint) => {
return b == c ? a : a * b / c
}
export const getExternals = (transactions: BlockchainTransaction[]) => {
const externals:Message[] = [];
return transactions.reduce((all, curExt) => [...all, ...curExt.externals], externals);
}
export const loadSigned = (ds: Slice) => {
const neg = ds.loadBit();
const value = ds.loadCoins();
return neg ? - value : value;
}
export const testLog = (message: Message, from: Address, topic: number | bigint, matcher?:(body: Cell) => boolean) => {
// Meh
if(message.info.type !== "external-out") {
console.log("Wrong from");
return false;
}
if(!message.info.src.equals(from))
return false;
if(!message.info.dest)
return false;
if(message.info.dest!.value !== BigInt(topic))
return false;
if(matcher !== undefined) {
if(!message.body)
console.log("No body");
return matcher(message.body);
}
return true;
};
type LoanParams = {
lender: Address,
amount: bigint,
}
type RepaymentParams = LoanParams & {
profit: bigint
}
export const testLogRepayment = (message: Message, from: Address, match: Partial<RepaymentParams>) => {
return testLog(message, from, 2, x => {
const bs = x.beginParse();
const repayment: RepaymentParams = {
lender: bs.loadAddress(),
amount: bs.loadCoins(),
profit: loadSigned(bs),
};
return testPartial(repayment, match);
});
};
export const testLogLoan = (message: Message, from: Address, match: Partial<LoanParams>) => {
return testLog(message, from, 1, x => {
const bs = x.beginParse();
const loan : LoanParams = {
lender: bs.loadAddress(),
amount: bs.loadCoins()
}
return testPartial(loan, match);
});
}
type RoundCompletionParams = {
round: number,
borrowed: bigint,
returned: bigint,
profit: bigint
}
export const testLogRound = (message: Message, from: Address, match: Partial<RoundCompletionParams>) => {
return testLog(message, from, 3, x => {
const bs = x.beginParse();
const roundStats : RoundCompletionParams = {
round: bs.loadUint(32),
borrowed: bs.loadCoins(),
returned: bs.loadCoins(),
profit: loadSigned(bs)
};
return testPartial(roundStats, match);
});
}
export const testLogRotation = (message: Message, from: Address, roundId: number) => {
return testLog(message, from, 4, x => {
const testVal = x.beginParse().preloadUint(32);
return testVal == roundId;
});
}
type Log = RoundCompletionParams | LoanParams | RepaymentParams | number;
type LogTypes = 1 | 2 | 3 | 4;
type LogMatch<T extends LogTypes> = T extends 1 ? Partial<LoanParams>
: T extends 2 ? Partial<RepaymentParams>
: T extends 3 ? Partial<RoundCompletionParams>
: number;
export const assertLog = <T extends LogTypes>(transactions: BlockchainTransaction[], from: Address, type: T, match:LogMatch<T> ) => {
expect(getExternals(transactions).some(x => {
let res = false;
switch(type) {
case 1:
res = testLogLoan(x, from, match as Partial<LoanParams>);
break;
case 2:
res = testLogRepayment(x, from, match as Partial<RepaymentParams>);
break;
case 3:
res = testLogRound(x, from, match as Partial<RoundCompletionParams>);
break;
case 4:
res = testLogRotation(x, from, match as number);
break;
}
return res;
})).toBe(true);
}
export type InternalTransfer = {
from: Address | null,
to: Address | null,
amount: bigint,
forwardAmount: bigint,
payload: Cell | null
};
export type ControllerStaticData = {
id: number,
validator: Address,
pool: Address,
governor: Address,
approver: Address | null,
halter: Address | null
}
export const parseControllerStatic = (meta: Cell) => {
const ms = meta.beginParse();
const hs = ms.preloadRef().beginParse(); // Halter appriver cell
return {
id: ms.loadUint(32),
validator: ms.loadAddress(),
pool: ms.loadAddress(),
governor: ms.loadAddress(),
approver: hs.loadAddressAny(),
halter: hs.loadAddressAny()
};
}
export const parseInternalTransfer = (body: Cell) => {
const ts = body.beginParse();
if(ts.loadUint(32) !== Op.jetton.internal_transfer)
throw(Error("Internal transfer op expected!"));
ts.skip(64);
return {
amount: ts.loadCoins(),
from: ts.loadAddressAny(),
to: ts.loadAddressAny(),
forwardAmount: ts.loadCoins(),
payload: ts.loadMaybeRef()
};
};
type JettonTransferNotification = {
amount: bigint,
from: Address | null,
payload: Cell | null
}
export const parseTransferNotification = (body: Cell) => {
const bs = body.beginParse().skip(64 + 32);
return {
amount: bs.loadCoins(),
from: bs.loadAddressAny(),
payload: bs.loadMaybeRef()
}
}
type JettonBurnNotification = {
amount: bigint,
from: Address,
response_address: Address | null,
request_immediate?: boolean,
fill_or_kill?: boolean
}
export const parseBurnNotification = (body: Cell) => {
const ds = body.beginParse().skip(64 + 32);
let res ={
amount: ds.loadCoins(),
from: ds.loadAddress(),
response_address: ds.loadAddressAny(),
};
if(ds.remainingBits >= 2) {
return {...res,
request_immediate: ds.loadBit(),
fill_or_kill: ds.loadBit()
};
}
return res;
}
// Some fuzzy logic here
export const approximatelyEqual = (a: bigint, b: bigint, threshold: bigint) => {
let delta = a < b ? b - a : a - b;
return delta <= threshold;
}
const testPartial = (cmp: any, match: any) => {
for (let key in match) {
if(!(key in cmp)) {
throw Error(`Unknown key ${key} in ${cmp}`);
}
if(match[key] instanceof Address) {
if(!(cmp[key] instanceof Address)) {
return false
}
if(!(match[key] as Address).equals(cmp[key])) {
return false
}
}
else if(match[key] instanceof Cell) {
if(!(cmp[key] instanceof Cell)) {
return false;
}
if(!(match[key] as Cell).equals(cmp[key])) {
return false;
}
}
else if(match[key] !== cmp[key]){
return false;
}
}
return true;
}
export const testJettonBurnNotification = (body: Cell, match: Partial<JettonBurnNotification>) => {
const res= parseBurnNotification(body);
return testPartial(res, match);
}
export const testControllerMeta = (meta: Cell, match: Partial<ControllerStaticData>) => {
const res = parseControllerStatic(meta);
return testPartial(res, match);
}
export const testJettonTransfer = (body: Cell, match: Partial<InternalTransfer>) => {
const res = parseInternalTransfer(body);
return testPartial(res, match);
};
export const testJettonNotification = (body: Cell, match: Partial<JettonTransferNotification>) => {
const res = parseTransferNotification(body);
return testPartial(res, match);
}
type PayoutMint = {
dest: Address,
amount: bigint,
notification: bigint,
forward: bigint
payload?: Cell | null
};
export const parsePayoutMint = (data: Cell) : PayoutMint => {
const ds = data.beginParse().skip(32 + 64);
return {
dest: ds.loadAddress(),
amount: ds.loadCoins(),
notification: ds.loadCoins(),
forward: ds.loadCoins(),
// payload: ds.loadMaybeRef()
};
}
export const testMintMsg = (body: Cell, match: Partial<PayoutMint>) => {
const res = parsePayoutMint(body);
return testPartial(res, match);
}
export const findTransaction = (txs: BlockchainTransaction[], match: FlatTransactionComparable) => {
return txs.find(x => compareTransaction(flattenTransaction(x), match));
}
export const executeTill = async (txs: AsyncIterable<BlockchainTransaction> | AsyncIterator<BlockchainTransaction>, match: FlatTransactionComparable) => {
let executed: BlockchainTransaction[] = [];
let txIterable = txs as AsyncIterable<BlockchainTransaction>;
let txIterator = txs as AsyncIterator<BlockchainTransaction>;
if(txIterable[Symbol.asyncIterator]) {
for await (const tx of txIterable) {
executed.push(tx);
if(compareTransaction(flattenTransaction(tx), match)) {
return tx;
}
}
}
else {
let iterResult = await txIterator.next();
while(!iterResult.done){
executed.push(iterResult.value);
if(compareTransaction(flattenTransaction(iterResult.value), match)) {
return iterResult.value;
}
iterResult = await txIterator.next();
}
}
// Will fail with common error message format
expect(executed).toHaveTransaction(match);
}
export const executeFrom = async (txs: AsyncIterator<BlockchainTransaction>) => {
let executed: BlockchainTransaction[] = [];
let iterResult = await txs.next();
while(!iterResult.done){
executed.push(iterResult.value);
iterResult = await txs.next();
}
return executed;
}
export const filterTransaction = (txs: BlockchainTransaction[], match: FlatTransactionComparable) => {
return txs.filter(x => compareTransaction(flattenTransaction(x), match));
}
type MsgQueued = {
msg: Message,
parent?: BlockchainTransaction
};
export class Txiterator implements AsyncIterator<BlockchainTransaction> {
private msqQueue: MsgQueued[];
private blockchain: Blockchain;
constructor(bc:Blockchain, msg: Message) {
this.msqQueue = [{msg}];
this.blockchain = bc;
}
public async next(): Promise<IteratorResult<BlockchainTransaction>> {
if(this.msqQueue.length == 0) {
return {done: true, value: undefined};
}
const curMsg = this.msqQueue.shift()!;
const inMsg = curMsg.msg;
if(inMsg.info.type !== "internal")
throw(Error("Internal only"));
const smc = await this.blockchain.getContract(inMsg.info.dest);
const res = smc.receiveMessage(inMsg, {now: this.blockchain.now});
const bcRes = {
...res,
events: extractEvents(res),
parent: curMsg.parent,
children: [],
externals: []
}
for(let i = 0; i < res.outMessagesCount; i++) {
const outMsg = res.outMessages.get(i)!;
// Only add internal for now
if(outMsg.info.type === "internal") {
this.msqQueue.push({msg:outMsg, parent: bcRes})
}
}
return {done: false, value: bcRes};
}
};
export const stepByStep = (bc: Blockchain, msg: Message) => {
// Returns AscyncIterable
return {
[Symbol.asyncIterator] () {
return new Txiterator(bc, msg);
}
}
}
export {
differentAddress,
};