-
Notifications
You must be signed in to change notification settings - Fork 17
/
contract.ts
1277 lines (1146 loc) · 34.9 KB
/
contract.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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Address, UniqueArray, DelayedTransactions, LT_COLLATOR } from './utils';
import {
AbiParam,
AbiFunction,
AbiEvent,
AbiFields,
FullContractState,
RawTokensObject,
TokensObject,
Transaction,
Message,
AbiFunctionName,
AbiEventName,
AbiFieldName,
AbiFunctionInputs,
DecodedAbiFunctionOutputs,
DecodedAbiFunctionInputs,
DecodedAbiFields,
AbiFunctionInputsWithDefault,
DecodedAbiEventData,
TransactionId,
serializeTokensObject,
parseTransaction,
parseTokensObject,
serializeTransaction,
} from './models';
import { Stream, Subscriber } from './stream';
import { ProviderApiResponse, ProviderRpcClient } from './index';
/**
* @category Contract
*/
export class Contract<Abi> {
private readonly _provider: ProviderRpcClient;
private readonly _abi: string;
private readonly _address: Address;
private readonly _methods: ContractMethods<Abi>;
private readonly _fields: ContractFields<Abi>;
public readonly methodsAbi: { [K in AbiFunctionName<Abi>]: AbiFunction<Abi, K> };
public readonly eventsAbi: { [K in AbiEventName<Abi>]: AbiEvent<Abi, K> };
public readonly fieldsAbi: AbiFields<Abi>;
constructor(provider: ProviderRpcClient, abi: Abi, address: Address) {
type ContractFunction = { name: string; inputs?: AbiParam[]; outputs?: AbiParam[] };
if (!Array.isArray((abi as any).functions)) {
throw new Error('Invalid abi. Functions array required');
}
if (!Array.isArray((abi as any).events)) {
throw new Error('Invalid abi. Events array required');
}
this._provider = provider;
this._abi = JSON.stringify(abi);
this.methodsAbi = ((abi as any).functions as ContractFunction[]).reduce((functions, item) => {
if (item.inputs == null) {
item.inputs = [];
}
if (item.outputs == null) {
item.outputs = [];
}
(functions as any)[item.name] = item;
return functions;
}, {} as typeof Contract.prototype.methodsAbi);
this.eventsAbi = ((abi as any).events as ContractFunction[]).reduce((events, item) => {
if (item.inputs == null) {
item.inputs = [];
}
(events as any)[item.name] = item;
return events;
}, {} as typeof Contract.prototype.eventsAbi);
this.fieldsAbi = (abi as any).fields;
this._address = address;
this._methods = new Proxy(
{},
{
get: <K extends AbiFunctionName<Abi>>(_object: Record<string, unknown>, method: K) => {
const rawAbi = this.methodsAbi[method];
return (params: TokensObject = {}) =>
new ContractMethodImpl(this._provider, rawAbi, this._abi, this._address, method, params);
},
},
) as unknown as ContractMethods<Abi>;
this._fields = new Proxy(
{},
{
get: <K extends AbiFieldName<Abi>>(_object: Record<string, unknown>, field: K) => {
return async (params: GetContractFieldsParams = {}) => {
await this._provider.ensureInitialized();
const { fields, state } = await this._provider.rawApi.getContractFields({
address: this._address.toString(),
abi: this._abi,
cachedState: params?.cachedState,
allowPartial: params?.allowPartial == null ? false : params.allowPartial,
});
if (fields == null) {
if (state == null) {
throw new Error('Account does not exist');
} else if (!state.isDeployed) {
throw new Error('Account is not deployed');
} else {
throw new Error('Invalid account data');
}
}
const parsedFields = parseTokensObject(this.fieldsAbi as AbiParam[], fields) as DecodedAbiFields<Abi>;
if (parsedFields == null || !Object.prototype.hasOwnProperty.call(parsedFields, field)) {
throw new Error('Unknown field');
}
return parsedFields[field];
};
},
},
) as unknown as ContractFields<Abi>;
}
public get methods(): ContractMethods<Abi> {
return this._methods;
}
public get fields(): ContractFields<Abi> {
return this._fields;
}
public get address(): Address {
return this._address;
}
public get abi(): string {
return this._abi;
}
/**
* Requests contract data
*
* ---
* Required permissions: `basic`
*/
public async getFullState(): Promise<ProviderApiResponse<'getFullContractState'>> {
await this._provider.ensureInitialized();
return (await this._provider.rawApi.getFullContractState({
address: this.address.toString(),
})) as ProviderApiResponse<'getFullContractState'>;
}
/**
* Unpacks all fields from the contract state using the specified ABI
*
* ---
* Required permissions: `basic`
*/
public async getFields(args: GetContractFieldsParams = {}): Promise<{
fields?: DecodedAbiFields<Abi>;
state?: FullContractState;
}> {
await this._provider.ensureInitialized();
const { fields, state } = await this._provider.rawApi.getContractFields({
address: this.address.toString(),
abi: this._abi,
cachedState: args.cachedState,
allowPartial: args.allowPartial == null ? false : args.allowPartial,
});
return {
fields:
fields != null ? (parseTokensObject(this.fieldsAbi as AbiParam[], fields) as DecodedAbiFields<Abi>) : undefined,
state,
};
}
/**
* Creates new contract transactions stream
*
* @param subscriber
*/
public transactions(subscriber: Subscriber): Stream<unknown, Transaction> {
return subscriber.transactions(this._address).flatMap(({ transactions }) => transactions);
}
/**
* Creates new contract events stream
*
* @param subscriber
*/
public events(subscriber: Subscriber): Stream<unknown, DecodedEventWithTransaction<Abi, AbiEventName<Abi>>> {
return subscriber
.transactions(this._address)
.flatMap(({ transactions }) => transactions)
.flatMap(tx =>
this.decodeTransactionEvents({ transaction: tx }).then(events => {
events.forEach(event => ((event as DecodedEventWithTransaction<Abi, AbiEventName<Abi>>).transaction = tx));
return events as DecodedEventWithTransaction<Abi, AbiEventName<Abi>>[];
}),
);
}
public async waitForEvent<E extends AbiEventName<Abi> = AbiEventName<Abi>>(
args: WaitForEventParams<Abi, E> = {},
): Promise<DecodedEvent<Abi, E> | undefined> {
const { range, filter } = args;
const filterFn =
typeof filter === 'string'
? ({ event }: DecodedEventWithTransaction<Abi, AbiEventName<Abi>>) => event === filter
: filter;
let subscriber = args.subscriber;
const hasTempSubscriber = subscriber == null;
if (subscriber == null) {
subscriber = new this._provider.Subscriber();
}
const event = await (range?.fromLt != null || range?.fromUtime != null
? subscriber.oldTransactions(this._address, range).merge(subscriber.transactions(this._address))
: subscriber.transactions(this.address)
)
.flatMap(item => item.transactions)
.takeWhile(
item =>
range == null ||
((range.fromLt == null || LT_COLLATOR.compare(item.id.lt, range.fromLt) > 0) &&
(range.fromUtime == null || item.createdAt > range.fromUtime) &&
(range.toLt == null || LT_COLLATOR.compare(item.id.lt, range.toLt) < 0) &&
(range.toUtime == null || item.createdAt < range.toUtime)),
)
.flatMap(tx =>
this.decodeTransactionEvents({ transaction: tx }).then(events => {
events.forEach(event => ((event as DecodedEventWithTransaction<Abi, AbiEventName<Abi>>).transaction = tx));
return events as DecodedEventWithTransaction<Abi, AbiEventName<Abi>>[];
}),
)
.filterMap(async event => {
if (filterFn == null || (await filterFn(event))) {
return event;
} else {
return undefined;
}
})
.first();
hasTempSubscriber && (await subscriber.unsubscribe());
return event;
}
public async getPastEvents<E extends AbiEventName<Abi> = AbiEventName<Abi>>(
args: GetPastEventParams<Abi, E>,
): Promise<EventsBatch<Abi, E>> {
const { range, filter, limit } = args;
const filterFn =
typeof filter === 'string'
? ({ event }: DecodedEventWithTransaction<Abi, AbiEventName<Abi>>) => event === filter
: filter;
const result: DecodedEventWithTransaction<Abi, E>[] = [];
let currentContinuation = args?.continuation;
outer: while (true) {
const { transactions, continuation } = await this._provider.getTransactions({
address: this._address,
continuation: currentContinuation,
});
if (transactions.length === null) {
break;
}
const filteredTransactions = transactions.filter(
item =>
(range?.fromLt == null || LT_COLLATOR.compare(item.id.lt, range.fromLt) > 0) &&
(range?.fromUtime == null || item.createdAt > range.fromUtime) &&
(range?.toLt == null || LT_COLLATOR.compare(item.id.lt, range.toLt) < 0) &&
(range?.toUtime == null || item.createdAt < range.toUtime),
);
if (filteredTransactions.length > 0) {
const parsedEvents = await Promise.all(
filteredTransactions.map(async tx => {
return {
tx,
events: await this.decodeTransactionEvents({ transaction: tx }).then(events => {
events.forEach(
event => ((event as DecodedEventWithTransaction<Abi, AbiEventName<Abi>>).transaction = tx),
);
return events as DecodedEventWithTransaction<Abi, AbiEventName<Abi>>[];
}),
};
}),
);
for (let { tx, events } of parsedEvents) {
if (filterFn != null) {
events = await Promise.all(events.map(async event => ((await filterFn(event)) ? event : undefined))).then(
events => events.filter((event): event is Awaited<DecodedEventWithTransaction<Abi, E>> => event != null),
);
}
currentContinuation = tx.id; // update continuation in case of early break
for (const event of events) {
if (limit != null && result.length >= limit) {
break outer;
}
result.push(event);
}
if (limit != null && result.length >= limit) {
break outer;
}
}
}
currentContinuation = continuation;
if (currentContinuation == null) {
break;
}
}
return { events: result, continuation: currentContinuation };
}
public async decodeTransaction(
args: DecodeTransactionParams<Abi>,
): Promise<DecodedTransaction<Abi, AbiFunctionName<Abi>> | undefined> {
await this._provider.ensureInitialized();
try {
const result = await this._provider.rawApi.decodeTransaction({
transaction: serializeTransaction(args.transaction),
abi: this._abi,
method: args.methods,
});
if (result == null) {
return undefined;
}
const { method, input, output } = result;
const rawAbi = (this.methodsAbi as any)[method];
return {
method,
input: rawAbi.inputs != null ? parseTokensObject(rawAbi.inputs, input) : {},
output: rawAbi.outputs != null ? parseTokensObject(rawAbi.outputs, output) : {},
} as DecodedTransaction<Abi, AbiFunctionName<Abi>>;
} catch (_) {
return undefined;
}
}
public async decodeTransactionEvents(
args: DecodeTransactionEventsParams,
): Promise<DecodedEvent<Abi, AbiEventName<Abi>>[]> {
await this._provider.ensureInitialized();
try {
const { events } = await this._provider.rawApi.decodeTransactionEvents({
transaction: serializeTransaction(args.transaction),
abi: this._abi,
});
const result: DecodedEvent<Abi, AbiEventName<Abi>>[] = [];
for (const { event, data } of events) {
const rawAbi = (this.eventsAbi as any)[event];
result.push({
event,
data: rawAbi.inputs != null ? parseTokensObject(rawAbi.inputs, data) : {},
} as DecodedEvent<Abi, AbiEventName<Abi>>);
}
return result;
} catch (_) {
return [];
}
}
public async decodeInputMessage(
args: DecodeInputParams<Abi>,
): Promise<DecodedInput<Abi, AbiFunctionName<Abi>> | undefined> {
await this._provider.ensureInitialized();
try {
const result = await this._provider.rawApi.decodeInput({
abi: this._abi,
body: args.body,
internal: args.internal,
method: args.methods,
});
if (result == null) {
return undefined;
}
const { method, input } = result;
const rawAbi = (this.methodsAbi as any)[method];
return {
method,
input: rawAbi.inputs != null ? parseTokensObject(rawAbi.inputs, input) : {},
} as DecodedInput<Abi, AbiFunctionName<Abi>>;
} catch (_) {
return undefined;
}
}
public async decodeOutputMessage(
args: DecodeOutputParams<Abi>,
): Promise<DecodedOutput<Abi, AbiFunctionName<Abi>> | undefined> {
await this._provider.ensureInitialized();
try {
const result = await this._provider.rawApi.decodeOutput({
abi: this._abi,
body: args.body,
method: args.methods,
});
if (result == null) {
return undefined;
}
const { method, output } = result;
const rawAbi = (this.methodsAbi as any)[method];
return {
method,
output: rawAbi.outputs != null ? parseTokensObject(rawAbi.outputs, output) : {},
} as DecodedOutput<Abi, AbiFunctionName<Abi>>;
} catch (_) {
return undefined;
}
}
public async decodeEvent(args: DecodeEventParams<Abi>): Promise<DecodedEvent<Abi, AbiEventName<Abi>> | undefined> {
await this._provider.ensureInitialized();
try {
const result = await this._provider.rawApi.decodeEvent({
abi: this.abi,
body: args.body,
event: args.events,
});
if (result == null) {
return undefined;
}
const { event, data } = result;
const rawAbi = (this.eventsAbi as any)[event];
return {
event,
data: rawAbi.inputs != null ? parseTokensObject(rawAbi.inputs, data) : {},
} as DecodedEvent<Abi, AbiEventName<Abi>>;
} catch (_) {
return undefined;
}
}
}
/**
* @category Contract
*/
export class TvmException extends Error {
constructor(public readonly code: number) {
super(`TvmException: ${code}`);
}
}
/**
* @category Contract
*/
export type DelayedMessageExecution = {
/**
* External message hash
*/
messageHash: string;
/**
* Message expiration timestamp
*/
expireAt: number;
/**
* Transaction promise (it will be rejected if the message has expired)
*/
transaction: Promise<Transaction>;
};
/**
* @category Contract
*/
export type ContractMethods<C> = {
[K in AbiFunctionName<C>]: (
params: AbiFunctionInputsWithDefault<C, K>,
) => ContractMethod<AbiFunctionInputs<C, K>, DecodedAbiFunctionOutputs<C, K>>;
};
/**
* @category Contract
*/
export type ContractFields<C> = {
[K in AbiFieldName<C>]: (params?: GetContractFieldsParams) => Promise<DecodedAbiFields<C>[K]>;
};
/**
* @category Contract
*/
export interface ContractMethod<I, O> {
/**
* Target contract address
*/
readonly address: Address;
readonly abi: string;
readonly method: string;
readonly params: I;
/**
* Sends internal message and returns wallet transaction
*
* @param args
*/
send(args: SendInternalParams): Promise<Transaction>;
/**
* Sends internal message without waiting for the transaction
*
* @param args
*/
sendDelayed(args: SendInternalParams): Promise<DelayedMessageExecution>;
/**
* Sends internal message and waits for the new transaction on target address
*
* @param args
*/
sendWithResult(
args: SendInternalParams,
): Promise<{ parentTransaction: Transaction; childTransaction: Transaction; output?: O }>;
/**
* Estimates wallet fee for calling this method as an internal message
*
* @param args
*/
estimateFees(args: SendInternalParams): Promise<string>;
/**
* Sends external message and returns contract transaction with parsed output
*
* @param args
*/
sendExternal(args: SendExternalParams): Promise<{ transaction: Transaction; output?: O }>;
/**
* Sends external message without waiting for the transaction
*
* @param args
*/
sendExternalDelayed(args: SendExternalDelayedParams): Promise<DelayedMessageExecution>;
/**
* Executes only a compute phase locally
*
* @param args
*/
call(args?: CallParams): Promise<O>;
/**
* Encodes this method as an external message and
* executes all transaction phases locally, producing a new state
*/
executeExternal(args: ExecuteExternalParams): Promise<ExecutorOutput<O>>;
/**
* Encodes this method as an internal message and
* executes all transaction phases locally, producing a new state
*/
executeInternal(args: ExecuteInternalParams): Promise<ExecutorOutput<O>>;
/**
* Encodes method call as BOC
*/
encodeInternal(): Promise<string>;
}
class ContractMethodImpl implements ContractMethod<any, any> {
readonly params: RawTokensObject;
constructor(
readonly provider: ProviderRpcClient,
readonly functionAbi: { inputs: AbiParam[]; outputs: AbiParam[] },
readonly abi: string,
readonly address: Address,
readonly method: string,
params: TokensObject,
) {
this.params = serializeTokensObject(params);
}
async send(args: SendInternalParams): Promise<Transaction> {
await this.provider.ensureInitialized();
const { transaction } = await this.provider.rawApi.sendMessage({
sender: args.from.toString(),
recipient: this.address.toString(),
amount: args.amount,
bounce: args.bounce == null ? true : args.bounce,
payload: {
abi: this.abi,
method: this.method,
params: this.params,
},
stateInit: args.stateInit,
});
return parseTransaction(transaction);
}
async sendDelayed(args: SendInternalParams): Promise<DelayedMessageExecution> {
await this.provider.ensureInitialized();
const transactions = new DelayedTransactions();
const subscription = await this.provider.subscribe('messageStatusUpdated');
subscription.on('data', data => {
if (!data.address.equals(args.from)) {
return;
}
transactions.fillTransaction(data.hash, data.transaction);
});
const { message } = await this.provider.rawApi
.sendMessageDelayed({
sender: args.from.toString(),
recipient: this.address.toString(),
amount: args.amount,
bounce: args.bounce == null ? true : args.bounce,
payload: {
abi: this.abi,
method: this.method,
params: this.params,
},
stateInit: args.stateInit,
})
.catch(e => {
subscription.unsubscribe().catch(console.error);
throw e;
});
const transaction = transactions
.waitTransaction(this.address, message.hash)
.finally(() => subscription.unsubscribe().catch(console.error));
return {
messageHash: message.hash,
expireAt: message.expireAt,
transaction,
};
}
async sendWithResult(
args: SendInternalWithResultParams,
): Promise<{ parentTransaction: Transaction; childTransaction: Transaction; output?: any }> {
await this.provider.ensureInitialized();
let subscriber = args.subscriber;
const hasTempSubscriber = subscriber == null;
if (subscriber == null) {
subscriber = new this.provider.Subscriber();
}
try {
// Parent transaction from wallet
let parentTransaction: { transaction: Transaction; possibleMessages: Message[] } | undefined = undefined;
// Child transaction promise
let resolveChildTransactionPromise: ((transaction: Transaction) => void) | undefined;
const childTransactionPromise = new Promise<Transaction>(resolve => {
resolveChildTransactionPromise = tx => resolve(tx);
});
// Array for collecting transactions on target before parent transaction promise resolution
const possibleChildren: Transaction[] = [];
// Subscribe to this account
subscriber
.transactions(this.address)
.flatMap(batch => batch.transactions)
// Listen only messages from sender
.filter(item => item.inMessage.src?.equals(args.from) || false)
.on(tx => {
if (parentTransaction == null) {
// If we don't known whether the message was sent just collect all transactions from the sender
possibleChildren.push(tx);
} else if (parentTransaction.possibleMessages.findIndex(msg => msg.hash == tx.inMessage.hash) >= 0) {
// Resolve promise if transaction was found
resolveChildTransactionPromise?.(tx);
}
});
// Send message
const transaction = await this.send(args);
// Extract all outgoing messages from the parent transaction to this contract
const possibleMessages = transaction.outMessages.filter(msg => msg.dst?.equals(this.address) || false);
// Update stream state
parentTransaction = {
transaction,
possibleMessages,
};
// Check whether child transaction was already found
const alreadyReceived = possibleChildren.find(tx => {
return possibleMessages.findIndex(msg => msg.hash == tx.inMessage.hash) >= 0;
});
if (alreadyReceived != null) {
resolveChildTransactionPromise?.(alreadyReceived);
}
const childTransaction = await childTransactionPromise;
// Parse output
let output: any = undefined;
try {
const result = await this.provider.rawApi.decodeTransaction({
transaction: serializeTransaction(childTransaction),
abi: this.abi,
method: this.method,
});
if (result != null) {
output = this.functionAbi.outputs != null ? parseTokensObject(this.functionAbi.outputs, result.output) : {};
}
} catch (e) {
console.error(e);
}
// Done
return {
parentTransaction: parentTransaction.transaction,
childTransaction,
output,
};
} finally {
hasTempSubscriber && (await subscriber.unsubscribe());
}
}
async estimateFees(args: SendInternalParams): Promise<string> {
await this.provider.ensureInitialized();
const { fees } = await this.provider.rawApi.estimateFees({
sender: args.from.toString(),
recipient: this.address.toString(),
amount: args.amount,
payload: {
abi: this.abi,
method: this.method,
params: this.params,
},
stateInit: args.stateInit,
});
return fees;
}
async sendExternal(args: SendExternalParams): Promise<{ transaction: Transaction; output?: any }> {
await this.provider.ensureInitialized();
const method =
args.withoutSignature === true
? this.provider.rawApi.sendUnsignedExternalMessage
: this.provider.rawApi.sendExternalMessage;
const { transaction, output } = await method({
publicKey: (args as any).publicKey,
recipient: this.address.toString(),
stateInit: args.stateInit,
payload: {
abi: this.abi,
method: this.method,
params: this.params,
},
local: args.local,
executorParams: args.executorParams
? {
disableSignatureCheck: args.executorParams.disableSignatureCheck,
overrideBalance: args.executorParams.overrideBalance,
}
: undefined,
});
return {
transaction: parseTransaction(transaction),
output: output != null ? parseTokensObject(this.functionAbi.outputs, output) : undefined,
};
}
async sendExternalDelayed(args: SendExternalDelayedParams): Promise<DelayedMessageExecution> {
await this.provider.ensureInitialized();
const transactions = new DelayedTransactions();
const subscription = await this.provider.subscribe('messageStatusUpdated');
subscription.on('data', data => {
if (!data.address.equals(this.address)) {
return;
}
transactions.fillTransaction(data.hash, data.transaction);
});
const { message } = await this.provider.rawApi
.sendExternalMessageDelayed({
publicKey: args.publicKey,
recipient: this.address.toString(),
stateInit: args.stateInit,
payload: {
abi: this.abi,
method: this.method,
params: this.params,
},
})
.catch(e => {
subscription.unsubscribe().catch(console.error);
throw e;
});
const transaction = transactions
.waitTransaction(this.address, message.hash)
.finally(() => subscription.unsubscribe().catch(console.error));
return {
messageHash: message.hash,
expireAt: message.expireAt,
transaction,
};
}
async call(args: CallParams = {}): Promise<any> {
await this.provider.ensureInitialized();
const { output, code } = await this.provider.rawApi.runLocal({
address: this.address.toString(),
cachedState: args.cachedState,
responsible: args.responsible,
functionCall: {
abi: this.abi,
method: this.method,
params: this.params,
},
});
if (output == null || code != 0) {
throw new TvmException(code);
} else {
return parseTokensObject(this.functionAbi.outputs, output);
}
}
/**
* Encodes this method as an external message and
* executes all transaction phases locally, producing a new state
*/
async executeExternal(args: ExecuteExternalParams): Promise<ExecutorOutput<any>> {
await this.provider.ensureInitialized();
const { transaction, newState, output } = await this.provider.rawApi.executeLocal({
address: this.address.toString(),
cachedState: args.cachedState,
stateInit: args.stateInit,
payload: {
abi: this.abi,
method: this.method,
params: this.params,
},
messageHeader: {
type: 'external',
publicKey: args.publicKey,
withoutSignature: args.withoutSignature,
},
executorParams:
args.executorParams != null
? {
disableSignatureCheck: args.executorParams.disableSignatureCheck,
overrideBalance: args.executorParams.overrideBalance,
}
: undefined,
});
return {
transaction: parseTransaction(transaction),
newState,
output: output !== undefined ? parseTokensObject(this.functionAbi.outputs, output) : undefined,
} as ExecutorOutput<any>;
}
/**
* Encodes this method as an internal message and
* executes all transaction phases locally, producing a new state
*/
async executeInternal(args: ExecuteInternalParams): Promise<ExecutorOutput<any>> {
await this.provider.ensureInitialized();
const { transaction, newState, output } = await this.provider.rawApi.executeLocal({
address: this.address.toString(),
cachedState: args.cachedState,
stateInit: args.stateInit,
payload: {
abi: this.abi,
method: this.method,
params: this.params,
},
messageHeader: {
type: 'internal',
sender: args.sender.toString(),
amount: args.amount,
bounce: args.bounce != null ? args.bounce : false,
bounced: args.bounced,
},
executorParams:
args.executorParams != null
? {
disableSignatureCheck: args.executorParams.disableSignatureCheck,
overrideBalance: args.executorParams.overrideBalance,
}
: undefined,
});
return {
transaction: parseTransaction(transaction),
newState,
output: output !== undefined ? parseTokensObject(this.functionAbi.outputs, output) : undefined,
} as ExecutorOutput<any>;
}
async encodeInternal(): Promise<string> {
await this.provider.ensureInitialized();
const { boc } = await this.provider.rawApi.encodeInternalInput({
abi: this.abi,
method: this.method,
params: this.params,
});
return boc;
}
}
/**
* @category Contract
*/
export type GetContractFieldsParams = {
/**
* Cached contract state
*/
cachedState?: FullContractState;
/**
* Don't fail if something is left in a cell after unpacking
*/
allowPartial?: boolean;
};
/**
* @category Contract
*/
export type SendInternalParams = {
/**
* Preferred wallet address.
* It is the same address as the `accountInteraction.address`, but it must be explicitly provided
*/
from: Address;
/**
* Amount of nano EVER to send
*/
amount: string;
/**
* @default true
*/
bounce?: boolean;
/**
* Optional base64 encoded TVC
*
* NOTE: If the selected contract do not support stateInit in the internal message,
* an error is returned
*/
stateInit?: string;
};
/**
* @category Contract
*/
export type SendInternalWithResultParams = SendInternalParams & {
/**
* Existing subscriber
*/
subscriber?: Subscriber;
};
/**
* @category Contract
*/
export type SendExternalParams = ({
/**
* Whether to prepare this message without signature. Default: false
*/
withoutSignature: true;
} | {
/**
* The public key of the preferred account.
* It is the same publicKey as the `accountInteraction.publicKey`, but it must be explicitly provided
*/
publicKey: string;
/**
* Whether to prepare this message without signature. Default: false