-
Notifications
You must be signed in to change notification settings - Fork 208
/
Copy pathcomposer.ts
831 lines (740 loc) · 27.6 KB
/
composer.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
import {
ABIAddressType,
abiCheckTransactionType,
ABIMethod,
ABIReferenceType,
ABITupleType,
ABIType,
abiTypeIsReference,
abiTypeIsTransaction,
ABIUintType,
ABIValue,
} from './abi/index.js';
import { AlgodClient } from './client/v2/algod/algod.js';
import {
SimulateRequest,
SimulateRequestTransactionGroup,
PendingTransactionResponse,
SimulateResponse,
} from './client/v2/algod/models/types.js';
import * as encoding from './encoding/encoding.js';
import { Address } from './encoding/address.js';
import { assignGroupID } from './group.js';
import { makeApplicationCallTxnFromObject } from './makeTxn.js';
import {
isTransactionWithSigner,
TransactionSigner,
TransactionWithSigner,
} from './signer.js';
import { Transaction } from './transaction.js';
import { SignedTransaction } from './signedTransaction.js';
import {
BoxReference,
OnApplicationComplete,
SuggestedParams,
} from './types/transactions/base.js';
import { arrayEqual, stringifyJSON, ensureUint64 } from './utils/utils.js';
import { waitForConfirmation } from './wait.js';
// First 4 bytes of SHA-512/256 hash of "return"
const RETURN_PREFIX = new Uint8Array([21, 31, 124, 117]);
// The maximum number of arguments for an application call transaction
const MAX_APP_ARGS = 16;
export type ABIArgument = ABIValue | TransactionWithSigner;
/** Represents the output from a successful ABI method call. */
export interface ABIResult {
/** The TxID of the transaction that invoked the ABI method call. */
txID: string;
/**
* The raw bytes of the return value from the ABI method call. This will be empty if the method
* does not return a value (return type "void").
*/
rawReturnValue: Uint8Array;
/**
* The method that was called for this result
*/
method: ABIMethod;
/**
* The return value from the ABI method call. This will be undefined if the method does not return
* a value (return type "void"), or if the SDK was unable to decode the returned value.
*/
returnValue?: ABIValue;
/** If the SDK was unable to decode a return value, the error will be here. */
decodeError?: Error;
/** The pending transaction information from the method transaction */
txInfo?: PendingTransactionResponse;
}
export enum AtomicTransactionComposerStatus {
/** The atomic group is still under construction. */
BUILDING,
/** The atomic group has been finalized, but not yet signed. */
BUILT,
/** The atomic group has been finalized and signed, but not yet submitted to the network. */
SIGNED,
/** The atomic group has been finalized, signed, and submitted to the network. */
SUBMITTED,
/** The atomic group has been finalized, signed, submitted, and successfully committed to a block. */
COMMITTED,
}
/**
* Add a value to an application call's foreign array. The addition will be as compact as possible,
* and this function will return an index that can be used to reference `valueToAdd` in `array`.
*
* @param valueToAdd - The value to add to the array. If this value is already present in the array,
* it will not be added again. Instead, the existing index will be returned.
* @param array - The existing foreign array. This input may be modified to append `valueToAdd`.
* @param zeroValue - If provided, this value indicated two things: the 0 value is special for this
* array, so all indexes into `array` must start at 1; additionally, if `valueToAdd` equals
* `zeroValue`, then `valueToAdd` will not be added to the array, and instead the 0 indexes will
* be returned.
* @returns An index that can be used to reference `valueToAdd` in `array`.
*/
function populateForeignArray<Type>(
valueToAdd: Type,
array: Type[],
zeroValue?: Type
): number {
if (zeroValue != null && valueToAdd === zeroValue) {
return 0;
}
const offset = zeroValue == null ? 0 : 1;
for (let i = 0; i < array.length; i++) {
if (valueToAdd === array[i]) {
return i + offset;
}
}
array.push(valueToAdd);
return array.length - 1 + offset;
}
/** A class used to construct and execute atomic transaction groups */
export class AtomicTransactionComposer {
/** The maximum size of an atomic transaction group. */
static MAX_GROUP_SIZE: number = 16;
private status = AtomicTransactionComposerStatus.BUILDING;
private transactions: TransactionWithSigner[] = [];
private methodCalls: Map<number, ABIMethod> = new Map();
private signedTxns: Uint8Array[] = [];
private txIDs: string[] = [];
/**
* Get the status of this composer's transaction group.
*/
getStatus(): AtomicTransactionComposerStatus {
return this.status;
}
/**
* Get the number of transactions currently in this atomic group.
*/
count(): number {
return this.transactions.length;
}
/**
* Create a new composer with the same underlying transactions. The new composer's status will be
* BUILDING, so additional transactions may be added to it.
*/
clone(): AtomicTransactionComposer {
const theClone = new AtomicTransactionComposer();
theClone.transactions = this.transactions.map(({ txn, signer }) => {
const txnMap = txn.toEncodingData();
// erase the group ID
txnMap.delete('grp');
return {
// not quite a deep copy, but good enough for our purposes (modifying txn.group in buildGroup)
txn: Transaction.fromEncodingData(txnMap),
signer,
};
});
theClone.methodCalls = new Map(this.methodCalls);
return theClone;
}
/**
* Add a transaction to this atomic group.
*
* An error will be thrown if the transaction has a nonzero group ID, the composer's status is
* not BUILDING, or if adding this transaction causes the current group to exceed MAX_GROUP_SIZE.
*/
addTransaction(txnAndSigner: TransactionWithSigner): void {
if (this.status !== AtomicTransactionComposerStatus.BUILDING) {
throw new Error(
'Cannot add transactions when composer status is not BUILDING'
);
}
if (this.transactions.length === AtomicTransactionComposer.MAX_GROUP_SIZE) {
throw new Error(
`Adding an additional transaction exceeds the maximum atomic group size of ${AtomicTransactionComposer.MAX_GROUP_SIZE}`
);
}
if (txnAndSigner.txn.group && txnAndSigner.txn.group.some((v) => v !== 0)) {
throw new Error('Cannot add a transaction with nonzero group ID');
}
this.transactions.push(txnAndSigner);
}
/**
* Add a smart contract method call to this atomic group.
*
* An error will be thrown if the composer's status is not BUILDING, if adding this transaction
* causes the current group to exceed MAX_GROUP_SIZE, or if the provided arguments are invalid
* for the given method.
*/
addMethodCall({
appID,
method,
methodArgs,
sender,
suggestedParams,
onComplete,
approvalProgram,
clearProgram,
numGlobalInts,
numGlobalByteSlices,
numLocalInts,
numLocalByteSlices,
extraPages,
appAccounts,
appForeignApps,
appForeignAssets,
boxes,
note,
lease,
rekeyTo,
signer,
}: {
/** The ID of the smart contract to call. Set this to 0 to indicate an application creation call. */
appID: number | bigint;
/** The method to call on the smart contract */
method: ABIMethod;
/** The arguments to include in the method call. If omitted, no arguments will be passed to the method. */
methodArgs?: ABIArgument[];
/** The address of the sender of this application call */
sender: string | Address;
/** Transactions params to use for this application call */
suggestedParams: SuggestedParams;
/** The OnComplete action to take for this application call. If omitted, OnApplicationComplete.NoOpOC will be used. */
onComplete?: OnApplicationComplete;
/** The approval program for this application call. Only set this if this is an application creation call, or if onComplete is OnApplicationComplete.UpdateApplicationOC */
approvalProgram?: Uint8Array;
/** The clear program for this application call. Only set this if this is an application creation call, or if onComplete is OnApplicationComplete.UpdateApplicationOC */
clearProgram?: Uint8Array;
/** The global integer schema size. Only set this if this is an application creation call. */
numGlobalInts?: number;
/** The global byte slice schema size. Only set this if this is an application creation call. */
numGlobalByteSlices?: number;
/** The local integer schema size. Only set this if this is an application creation call. */
numLocalInts?: number;
/** The local byte slice schema size. Only set this if this is an application creation call. */
numLocalByteSlices?: number;
/** The number of extra pages to allocate for the application's programs. Only set this if this is an application creation call. If omitted, defaults to 0. */
extraPages?: number;
/** Array of Address strings that represent external accounts supplied to this application. If accounts are provided here, the accounts specified in the method args will appear after these. */
appAccounts?: Array<string | Address>;
/** Array of App ID numbers that represent external apps supplied to this application. If apps are provided here, the apps specified in the method args will appear after these. */
appForeignApps?: Array<number | bigint>;
/** Array of Asset ID numbers that represent external assets supplied to this application. If assets are provided here, the assets specified in the method args will appear after these. */
appForeignAssets?: Array<number | bigint>;
/** The box references for this application call */
boxes?: BoxReference[];
/** The note value for this application call */
note?: Uint8Array;
/** The lease value for this application call */
lease?: Uint8Array;
/** If provided, the address that the sender will be rekeyed to at the conclusion of this application call */
rekeyTo?: string | Address;
/** A transaction signer that can authorize this application call from sender */
signer: TransactionSigner;
}): void {
if (this.status !== AtomicTransactionComposerStatus.BUILDING) {
throw new Error(
'Cannot add transactions when composer status is not BUILDING'
);
}
if (
this.transactions.length + method.txnCount() >
AtomicTransactionComposer.MAX_GROUP_SIZE
) {
throw new Error(
`Adding additional transactions exceeds the maximum atomic group size of ${AtomicTransactionComposer.MAX_GROUP_SIZE}`
);
}
if (BigInt(appID) === BigInt(0)) {
if (
approvalProgram == null ||
clearProgram == null ||
numGlobalInts == null ||
numGlobalByteSlices == null ||
numLocalInts == null ||
numLocalByteSlices == null
) {
throw new Error(
'One of the following required parameters for application creation is missing: approvalProgram, clearProgram, numGlobalInts, numGlobalByteSlices, numLocalInts, numLocalByteSlices'
);
}
} else if (onComplete === OnApplicationComplete.UpdateApplicationOC) {
if (approvalProgram == null || clearProgram == null) {
throw new Error(
'One of the following required parameters for OnApplicationComplete.UpdateApplicationOC is missing: approvalProgram, clearProgram'
);
}
if (
numGlobalInts != null ||
numGlobalByteSlices != null ||
numLocalInts != null ||
numLocalByteSlices != null ||
extraPages != null
) {
throw new Error(
'One of the following application creation parameters were set on a non-creation call: numGlobalInts, numGlobalByteSlices, numLocalInts, numLocalByteSlices, extraPages'
);
}
} else if (
approvalProgram != null ||
clearProgram != null ||
numGlobalInts != null ||
numGlobalByteSlices != null ||
numLocalInts != null ||
numLocalByteSlices != null ||
extraPages != null
) {
throw new Error(
'One of the following application creation parameters were set on a non-creation call: approvalProgram, clearProgram, numGlobalInts, numGlobalByteSlices, numLocalInts, numLocalByteSlices, extraPages'
);
}
if (methodArgs == null) {
// eslint-disable-next-line no-param-reassign
methodArgs = [];
}
if (methodArgs.length !== method.args.length) {
throw new Error(
`Incorrect number of method arguments. Expected ${method.args.length}, got ${methodArgs.length}`
);
}
let basicArgTypes: ABIType[] = [];
let basicArgValues: ABIValue[] = [];
const txnArgs: TransactionWithSigner[] = [];
const refArgTypes: ABIReferenceType[] = [];
const refArgValues: ABIValue[] = [];
const refArgIndexToBasicArgIndex: Map<number, number> = new Map();
// TODO: Box encoding for ABI
const boxReferences: BoxReference[] = !boxes ? [] : boxes;
for (let i = 0; i < methodArgs.length; i++) {
let argType = method.args[i].type;
const argValue = methodArgs[i];
if (abiTypeIsTransaction(argType)) {
if (
!isTransactionWithSigner(argValue) ||
!abiCheckTransactionType(argType, argValue.txn)
) {
throw new Error(
`Expected ${argType} TransactionWithSigner for argument at index ${i}`
);
}
if (argValue.txn.group && argValue.txn.group.some((v) => v !== 0)) {
throw new Error('Cannot add a transaction with nonzero group ID');
}
txnArgs.push(argValue);
continue;
}
if (isTransactionWithSigner(argValue)) {
throw new Error(
`Expected non-transaction value for argument at index ${i}`
);
}
if (abiTypeIsReference(argType)) {
refArgIndexToBasicArgIndex.set(
refArgTypes.length,
basicArgTypes.length
);
refArgTypes.push(argType);
refArgValues.push(argValue);
// treat the reference as a uint8 for encoding purposes
argType = new ABIUintType(8);
}
if (typeof argType === 'string') {
throw new Error(`Unknown ABI type: ${argType}`);
}
basicArgTypes.push(argType);
basicArgValues.push(argValue);
}
const resolvedRefIndexes: number[] = [];
// Converting addresses to string form for easier comparison
const foreignAccounts: string[] =
appAccounts == null ? [] : appAccounts.map((addr) => addr.toString());
const foreignApps: bigint[] =
appForeignApps == null ? [] : appForeignApps.map(ensureUint64);
const foreignAssets: bigint[] =
appForeignAssets == null ? [] : appForeignAssets.map(ensureUint64);
for (let i = 0; i < refArgTypes.length; i++) {
const refType = refArgTypes[i];
const refValue = refArgValues[i];
let resolved = 0;
switch (refType) {
case ABIReferenceType.account: {
const addressType = new ABIAddressType();
const address = addressType.decode(addressType.encode(refValue));
resolved = populateForeignArray(
address,
foreignAccounts,
sender.toString()
);
break;
}
case ABIReferenceType.application: {
const uint64Type = new ABIUintType(64);
const refAppID = uint64Type.decode(uint64Type.encode(refValue));
if (refAppID > Number.MAX_SAFE_INTEGER) {
throw new Error(
`Expected safe integer for application value, got ${refAppID}`
);
}
resolved = populateForeignArray(
refAppID,
foreignApps,
ensureUint64(appID)
);
break;
}
case ABIReferenceType.asset: {
const uint64Type = new ABIUintType(64);
const refAssetID = uint64Type.decode(uint64Type.encode(refValue));
if (refAssetID > Number.MAX_SAFE_INTEGER) {
throw new Error(
`Expected safe integer for asset value, got ${refAssetID}`
);
}
resolved = populateForeignArray(refAssetID, foreignAssets);
break;
}
default:
throw new Error(`Unknown reference type: ${refType}`);
}
resolvedRefIndexes.push(resolved);
}
for (let i = 0; i < resolvedRefIndexes.length; i++) {
const basicArgIndex = refArgIndexToBasicArgIndex.get(i)!;
basicArgValues[basicArgIndex] = resolvedRefIndexes[i];
}
if (basicArgTypes.length > MAX_APP_ARGS - 1) {
const lastArgTupleTypes = basicArgTypes.slice(MAX_APP_ARGS - 2);
const lastArgTupleValues = basicArgValues.slice(MAX_APP_ARGS - 2);
basicArgTypes = basicArgTypes.slice(0, MAX_APP_ARGS - 2);
basicArgValues = basicArgValues.slice(0, MAX_APP_ARGS - 2);
basicArgTypes.push(new ABITupleType(lastArgTupleTypes));
basicArgValues.push(lastArgTupleValues);
}
const appArgsEncoded: Uint8Array[] = [method.getSelector()];
for (let i = 0; i < basicArgTypes.length; i++) {
appArgsEncoded.push(basicArgTypes[i].encode(basicArgValues[i]));
}
const appCall = {
txn: makeApplicationCallTxnFromObject({
sender,
appIndex: appID,
appArgs: appArgsEncoded,
accounts: foreignAccounts,
foreignApps,
foreignAssets,
boxes: boxReferences,
onComplete:
onComplete == null ? OnApplicationComplete.NoOpOC : onComplete,
approvalProgram,
clearProgram,
numGlobalInts,
numGlobalByteSlices,
numLocalInts,
numLocalByteSlices,
extraPages,
lease,
note,
rekeyTo,
suggestedParams,
}),
signer,
};
this.transactions.push(...txnArgs, appCall);
this.methodCalls.set(this.transactions.length - 1, method);
}
/**
* Finalize the transaction group and returned the finalized transactions.
*
* The composer's status will be at least BUILT after executing this method.
*/
buildGroup(): TransactionWithSigner[] {
if (this.status === AtomicTransactionComposerStatus.BUILDING) {
if (this.transactions.length === 0) {
throw new Error('Cannot build a group with 0 transactions');
}
if (this.transactions.length > 1) {
assignGroupID(
this.transactions.map((txnWithSigner) => txnWithSigner.txn)
);
}
this.status = AtomicTransactionComposerStatus.BUILT;
}
return this.transactions;
}
/**
* Obtain signatures for each transaction in this group. If signatures have already been obtained,
* this method will return cached versions of the signatures.
*
* The composer's status will be at least SIGNED after executing this method.
*
* An error will be thrown if signing any of the transactions fails.
*
* @returns A promise that resolves to an array of signed transactions.
*/
async gatherSignatures(): Promise<Uint8Array[]> {
if (this.status >= AtomicTransactionComposerStatus.SIGNED) {
return this.signedTxns;
}
// retrieve built transactions and verify status is BUILT
const txnsWithSigners = this.buildGroup();
const txnGroup = txnsWithSigners.map((txnWithSigner) => txnWithSigner.txn);
const indexesPerSigner: Map<TransactionSigner, number[]> = new Map();
for (let i = 0; i < txnsWithSigners.length; i++) {
const { signer } = txnsWithSigners[i];
if (!indexesPerSigner.has(signer)) {
indexesPerSigner.set(signer, []);
}
indexesPerSigner.get(signer)!.push(i);
}
const orderedSigners = Array.from(indexesPerSigner);
const batchedSigs = await Promise.all(
orderedSigners.map(([signer, indexes]) => signer(txnGroup, indexes))
);
const signedTxns: Array<Uint8Array | null> = txnsWithSigners.map(
() => null
);
for (
let signerIndex = 0;
signerIndex < orderedSigners.length;
signerIndex++
) {
const indexes = orderedSigners[signerIndex][1];
const sigs = batchedSigs[signerIndex];
for (let i = 0; i < indexes.length; i++) {
signedTxns[indexes[i]] = sigs[i];
}
}
function fullyPopulated(a: Array<Uint8Array | null>): a is Uint8Array[] {
return a.every((v) => v != null);
}
if (!fullyPopulated(signedTxns)) {
throw new Error(`Missing signatures. Got ${signedTxns}`);
}
const txIDs = signedTxns.map((stxn, index) => {
try {
return encoding.decodeMsgpack(stxn, SignedTransaction).txn.txID();
} catch (err) {
throw new Error(
`Cannot decode signed transaction at index ${index}. ${err}`
);
}
});
this.signedTxns = signedTxns;
this.txIDs = txIDs;
this.status = AtomicTransactionComposerStatus.SIGNED;
return signedTxns;
}
/**
* Send the transaction group to the network, but don't wait for it to be committed to a block. An
* error will be thrown if submission fails.
*
* The composer's status must be SUBMITTED or lower before calling this method. If submission is
* successful, this composer's status will update to SUBMITTED.
*
* Note: a group can only be submitted again if it fails.
*
* @param client - An Algodv2 client
*
* @returns A promise that, upon success, resolves to a list of TxIDs of the submitted transactions.
*/
async submit(client: AlgodClient): Promise<string[]> {
if (this.status > AtomicTransactionComposerStatus.SUBMITTED) {
throw new Error('Transaction group cannot be resubmitted');
}
const stxns = await this.gatherSignatures();
await client.sendRawTransaction(stxns).do();
this.status = AtomicTransactionComposerStatus.SUBMITTED;
return this.txIDs;
}
/**
* Simulates the transaction group in the network.
*
* The composer will try to sign any transactions in the group, then simulate
* the results.
* Simulating the group will not change the composer's status.
*
* @param client - An Algodv2 client
* @param request - SimulateRequest with options in simulation.
* If provided, the request's transaction group will be overrwritten by the composer's group,
* only simulation related options will be used.
*
* @returns A promise that, upon success, resolves to an object containing an
* array of results containing one element for each method call transaction
* in this group (ABIResult[]) and the SimulateResponse object.
*/
async simulate(
client: AlgodClient,
request?: SimulateRequest
): Promise<{
methodResults: ABIResult[];
simulateResponse: SimulateResponse;
}> {
if (this.status > AtomicTransactionComposerStatus.SUBMITTED) {
throw new Error(
'Simulated Transaction group has already been submitted to the network'
);
}
const stxns = await this.gatherSignatures();
const txnObjects: SignedTransaction[] = stxns.map((stxn) =>
encoding.decodeMsgpack(stxn, SignedTransaction)
);
const currentRequest: SimulateRequest =
request == null ? new SimulateRequest({ txnGroups: [] }) : request;
currentRequest.txnGroups = [
new SimulateRequestTransactionGroup({
txns: txnObjects,
}),
];
const simulateResponse = await client
.simulateTransactions(currentRequest)
.do();
// Parse method response
const methodResults: ABIResult[] = [];
for (const [txnIndex, method] of this.methodCalls) {
const txID = this.txIDs[txnIndex];
const pendingInfo =
simulateResponse.txnGroups[0].txnResults[txnIndex].txnResult;
const methodResult: ABIResult = {
txID,
rawReturnValue: new Uint8Array(),
method,
};
methodResults.push(
AtomicTransactionComposer.parseMethodResponse(
method,
methodResult,
pendingInfo
)
);
}
return { methodResults, simulateResponse };
}
/**
* Send the transaction group to the network and wait until it's committed to a block. An error
* will be thrown if submission or execution fails.
*
* The composer's status must be SUBMITTED or lower before calling this method, since execution is
* only allowed once. If submission is successful, this composer's status will update to SUBMITTED.
* If the execution is also successful, this composer's status will update to COMMITTED.
*
* Note: a group can only be submitted again if it fails.
*
* @param client - An Algodv2 client
* @param waitRounds - The maximum number of rounds to wait for transaction confirmation
*
* @returns A promise that, upon success, resolves to an object containing the confirmed round for
* this transaction, the txIDs of the submitted transactions, and an array of results containing
* one element for each method call transaction in this group.
*/
async execute(
client: AlgodClient,
waitRounds: number
): Promise<{
confirmedRound: bigint;
txIDs: string[];
methodResults: ABIResult[];
}> {
if (this.status === AtomicTransactionComposerStatus.COMMITTED) {
throw new Error(
'Transaction group has already been executed successfully'
);
}
const txIDs = await this.submit(client);
this.status = AtomicTransactionComposerStatus.SUBMITTED;
const firstMethodCallIndex = this.transactions.findIndex((_, index) =>
this.methodCalls.has(index)
);
const indexToWaitFor =
firstMethodCallIndex === -1 ? 0 : firstMethodCallIndex;
const confirmedTxnInfo = await waitForConfirmation(
client,
txIDs[indexToWaitFor],
waitRounds
);
this.status = AtomicTransactionComposerStatus.COMMITTED;
const confirmedRound = confirmedTxnInfo.confirmedRound!;
const methodResults: ABIResult[] = [];
for (const [txnIndex, method] of this.methodCalls) {
const txID = txIDs[txnIndex];
let methodResult: ABIResult = {
txID,
rawReturnValue: new Uint8Array(),
method,
};
try {
const pendingInfo =
txnIndex === firstMethodCallIndex
? confirmedTxnInfo
: // eslint-disable-next-line no-await-in-loop
await client.pendingTransactionInformation(txID).do();
methodResult = AtomicTransactionComposer.parseMethodResponse(
method,
methodResult,
pendingInfo
);
} catch (err) {
methodResult.decodeError = err as Error;
}
methodResults.push(methodResult);
}
return {
confirmedRound,
txIDs,
methodResults,
};
}
/**
* Parses a single ABI Method transaction log into a ABI result object.
*
* @param method
* @param methodResult
* @param pendingInfo
* @returns An ABIResult object
*/
static parseMethodResponse(
method: ABIMethod,
methodResult: ABIResult,
pendingInfo: PendingTransactionResponse
): ABIResult {
const returnedResult: ABIResult = methodResult;
try {
returnedResult.txInfo = pendingInfo;
if (method.returns.type !== 'void') {
const logs = pendingInfo.logs || [];
if (logs.length === 0) {
throw new Error(
`App call transaction did not log a return value ${stringifyJSON(
pendingInfo
)}`
);
}
const lastLog = logs[logs.length - 1];
if (
lastLog.byteLength < 4 ||
!arrayEqual(lastLog.slice(0, 4), RETURN_PREFIX)
) {
throw new Error(
`App call transaction did not log a ABI return value ${stringifyJSON(
pendingInfo
)}`
);
}
returnedResult.rawReturnValue = new Uint8Array(lastLog.slice(4));
returnedResult.returnValue = method.returns.type.decode(
methodResult.rawReturnValue
);
}
} catch (err) {
returnedResult.decodeError = err as Error;
}
return returnedResult;
}
}