-
Notifications
You must be signed in to change notification settings - Fork 346
Expand file tree
/
Copy pathassembled_transaction.ts
More file actions
1125 lines (1050 loc) · 37.4 KB
/
assembled_transaction.ts
File metadata and controls
1125 lines (1050 loc) · 37.4 KB
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
/* disable max-classes rule, because extending error shouldn't count! */
/* eslint max-classes-per-file: 0 */
import {
Account,
Address,
BASE_FEE,
Contract,
Operation,
SorobanDataBuilder,
TransactionBuilder,
authorizeEntry as stellarBaseAuthorizeEntry,
xdr,
} from "@stellar/stellar-base";
import type {
AssembledTransactionOptions,
ClientOptions,
MethodOptions,
Tx,
WalletError,
XDR_BASE64,
} from "./types";
import { Server } from "../rpc";
import { Api } from "../rpc/api";
import { assembleTransaction } from "../rpc/transaction";
import type { Client } from "./client";
import { Err } from "./rust_result";
import { contractErrorPattern, implementsToString, getAccount } from "./utils";
import { DEFAULT_TIMEOUT } from "./types";
import { SentTransaction, Watcher } from "./sent_transaction";
import { Spec } from "./spec";
import {
ExpiredStateError,
ExternalServiceError,
FakeAccountError,
InternalWalletError,
InvalidClientRequestError,
NeedsMoreSignaturesError,
NoSignatureNeededError,
NoSignerError,
NotYetSimulatedError,
NoUnsignedNonInvokerAuthEntriesError,
RestoreFailureError,
SimulationFailedError,
UserRejectedError,
} from "./errors";
/** @module contract */
/**
* The main workhorse of {@link Client}. This class is used to wrap a
* transaction-under-construction and provide high-level interfaces to the most
* common workflows, while still providing access to low-level stellar-sdk
* transaction manipulation.
*
* Most of the time, you will not construct an `AssembledTransaction` directly,
* but instead receive one as the return value of a `Client` method. If
* you're familiar with the libraries generated by soroban-cli's `contract
* bindings typescript` command, these also wraps `Client` and return
* `AssembledTransaction` instances.
*
* Let's look at examples of how to use `AssembledTransaction` for a variety of
* use-cases:
*
* #### 1. Simple read call
*
* Since these only require simulation, you can get the `result` of the call
* right after constructing your `AssembledTransaction`:
*
* ```ts
* const { result } = await AssembledTransaction.build({
* method: 'myReadMethod',
* args: spec.funcArgsToScVals('myReadMethod', {
* args: 'for',
* my: 'method',
* ...
* }),
* contractId: 'C123…',
* networkPassphrase: '…',
* rpcUrl: 'https://…',
* publicKey: undefined, // irrelevant, for simulation-only read calls
* parseResultXdr: (result: xdr.ScVal) =>
* spec.funcResToNative('myReadMethod', result),
* })
* ```
*
* While that looks pretty complicated, most of the time you will use this in
* conjunction with {@link Client}, which simplifies it to:
*
* ```ts
* const { result } = await client.myReadMethod({
* args: 'for',
* my: 'method',
* ...
* })
* ```
*
* #### 2. Simple write call
*
* For write calls that will be simulated and then sent to the network without
* further manipulation, only one more step is needed:
*
* ```ts
* const assembledTx = await client.myWriteMethod({
* args: 'for',
* my: 'method',
* ...
* })
* const sentTx = await assembledTx.signAndSend()
* ```
*
* Here we're assuming that you're using a {@link Client}, rather than
* constructing `AssembledTransaction`'s directly.
*
* Note that `sentTx`, the return value of `signAndSend`, is a
* {@link SentTransaction}. `SentTransaction` is similar to
* `AssembledTransaction`, but is missing many of the methods and fields that
* are only relevant while assembling a transaction. It also has a few extra
* methods and fields that are only relevant after the transaction has been
* sent to the network.
*
* Like `AssembledTransaction`, `SentTransaction` also has a `result` getter,
* which contains the parsed final return value of the contract call. Most of
* the time, you may only be interested in this, so rather than getting the
* whole `sentTx` you may just want to:
*
* ```ts
* const tx = await client.myWriteMethod({ args: 'for', my: 'method', ... })
* const { result } = await tx.signAndSend()
* ```
*
* #### 3. More fine-grained control over transaction construction
*
* If you need more control over the transaction before simulating it, you can
* set various {@link MethodOptions} when constructing your
* `AssembledTransaction`. With a {@link Client}, this is passed as a
* second object after the arguments (or the only object, if the method takes
* no arguments):
*
* ```ts
* const tx = await client.myWriteMethod(
* {
* args: 'for',
* my: 'method',
* ...
* }, {
* fee: '10000', // default: {@link BASE_FEE}
* simulate: false,
* timeoutInSeconds: 20, // default: {@link DEFAULT_TIMEOUT}
* }
* )
* ```
*
* Since we've skipped simulation, we can now edit the `raw` transaction and
* then manually call `simulate`:
*
* ```ts
* tx.raw.addMemo(Memo.text('Nice memo, friend!'))
* await tx.simulate()
* ```
*
* If you need to inspect the simulation later, you can access it with
* `tx.simulation`.
*
* #### 4. Multi-auth workflows
*
* Soroban, and Stellar in general, allows multiple parties to sign a
* transaction.
*
* Let's consider an Atomic Swap contract. Alice wants to give 10 of her Token
* A tokens to Bob for 5 of his Token B tokens.
*
* ```ts
* const ALICE = 'G123...'
* const BOB = 'G456...'
* const TOKEN_A = 'C123…'
* const TOKEN_B = 'C456…'
* const AMOUNT_A = 10n
* const AMOUNT_B = 5n
* ```
*
* Let's say Alice is also going to be the one signing the final transaction
* envelope, meaning she is the invoker. So your app, from Alice's browser,
* simulates the `swap` call:
*
* ```ts
* const tx = await swapClient.swap({
* a: ALICE,
* b: BOB,
* token_a: TOKEN_A,
* token_b: TOKEN_B,
* amount_a: AMOUNT_A,
* amount_b: AMOUNT_B,
* })
* ```
*
* But your app can't `signAndSend` this right away, because Bob needs to sign
* it first. You can check this:
*
* ```ts
* const whoElseNeedsToSign = tx.needsNonInvokerSigningBy()
* ```
*
* You can verify that `whoElseNeedsToSign` is an array of length `1`,
* containing only Bob's public key.
*
* Then, still on Alice's machine, you can serialize the
* transaction-under-assembly:
*
* ```ts
* const json = tx.toJSON()
* ```
*
* And now you need to send it to Bob's browser. How you do this depends on
* your app. Maybe you send it to a server first, maybe you use WebSockets, or
* maybe you have Alice text the JSON blob to Bob and have him paste it into
* your app in his browser (note: this option might be error-prone 😄).
*
* Once you get the JSON blob into your app on Bob's machine, you can
* deserialize it:
*
* ```ts
* const tx = swapClient.txFromJSON(json)
* ```
*
* Or, if you're using a client generated with `soroban contract bindings
* typescript`, this deserialization will look like:
*
* ```ts
* const tx = swapClient.fromJSON.swap(json)
* ```
*
* Then you can have Bob sign it. What Bob will actually need to sign is some
* _auth entries_ within the transaction, not the transaction itself or the
* transaction envelope. Your app can verify that Bob has the correct wallet
* selected, then:
*
* ```ts
* await tx.signAuthEntries()
* ```
*
* Under the hood, this uses `signAuthEntry`, which you either need to inject
* during initial construction of the `Client`/`AssembledTransaction`,
* or which you can pass directly to `signAuthEntries`.
*
* Now Bob can again serialize the transaction and send back to Alice, where
* she can finally call `signAndSend()`.
*
* To see an even more complicated example, where Alice swaps with Bob but the
* transaction is invoked by yet another party, check out
* [test-swap.js](../../test/e2e/src/test-swap.js).
*
* @memberof module:contract
*/
export class AssembledTransaction<T> {
/**
* The TransactionBuilder as constructed in `{@link
* AssembledTransaction}.build`. Feel free set `simulate: false` to modify
* this object before calling `tx.simulate()` manually. Example:
*
* ```ts
* const tx = await myContract.myMethod(
* { args: 'for', my: 'method', ... },
* { simulate: false }
* );
* tx.raw.addMemo(Memo.text('Nice memo, friend!'))
* await tx.simulate();
* ```
*/
public raw?: TransactionBuilder;
/**
* The Transaction as it was built with `raw.build()` right before
* simulation. Once this is set, modifying `raw` will have no effect unless
* you call `tx.simulate()` again.
*/
public built?: Tx;
/**
* The result of the transaction simulation. This is set after the first call
* to `simulate`. It is difficult to serialize and deserialize, so it is not
* included in the `toJSON` and `fromJSON` methods. See `simulationData`
* cached, serializable access to the data needed by AssembledTransaction
* logic.
*/
public simulation?: Api.SimulateTransactionResponse;
/**
* Cached simulation result. This is set after the first call to
* {@link AssembledTransaction#simulationData}, and is used to facilitate
* serialization and deserialization of the AssembledTransaction.
*
* Most of the time, if you need this data, you can call
* `tx.simulation.result`.
*
* If you need access to this data after a transaction has been serialized
* and then deserialized, you can call `simulationData.result`.
*/
private simulationResult?: Api.SimulateHostFunctionResult;
/**
* Cached simulation transaction data. This is set after the first call to
* {@link AssembledTransaction#simulationData}, and is used to facilitate
* serialization and deserialization of the AssembledTransaction.
*
* Most of the time, if you need this data, you can call
* `simulation.transactionData`.
*
* If you need access to this data after a transaction has been serialized
* and then deserialized, you can call `simulationData.transactionData`.
*/
private simulationTransactionData?: xdr.SorobanTransactionData;
/**
* The Soroban server to use for all RPC calls. This is constructed from the
* `rpcUrl` in the options.
*/
private server: Server;
/**
* The signed transaction.
*/
public signed?: Tx;
/**
* A list of the most important errors that various AssembledTransaction
* methods can throw. Feel free to catch specific errors in your application
* logic.
*/
static Errors = {
ExpiredState: ExpiredStateError,
RestorationFailure: RestoreFailureError,
NeedsMoreSignatures: NeedsMoreSignaturesError,
NoSignatureNeeded: NoSignatureNeededError,
NoUnsignedNonInvokerAuthEntries: NoUnsignedNonInvokerAuthEntriesError,
NoSigner: NoSignerError,
NotYetSimulated: NotYetSimulatedError,
FakeAccount: FakeAccountError,
SimulationFailed: SimulationFailedError,
InternalWalletError,
ExternalServiceError,
InvalidClientRequest: InvalidClientRequestError,
UserRejected: UserRejectedError,
};
/**
* Serialize the AssembledTransaction to a JSON string. This is useful for
* saving the transaction to a database or sending it over the wire for
* multi-auth workflows. `fromJSON` can be used to deserialize the
* transaction. This only works with transactions that have been simulated.
*/
toJSON() {
return JSON.stringify({
method: this.options.method,
tx: this.built?.toXDR(),
simulationResult: {
auth: this.simulationData.result.auth.map((a) => a.toXDR("base64")),
retval: this.simulationData.result.retval.toXDR("base64"),
},
simulationTransactionData:
this.simulationData.transactionData.toXDR("base64"),
});
}
static fromJSON<T>(
options: Omit<AssembledTransactionOptions<T>, "args">,
{
tx,
simulationResult,
simulationTransactionData,
}: {
tx: XDR_BASE64;
simulationResult: {
auth: XDR_BASE64[];
retval: XDR_BASE64;
};
simulationTransactionData: XDR_BASE64;
},
): AssembledTransaction<T> {
const txn = new AssembledTransaction(options);
txn.built = TransactionBuilder.fromXDR(tx, options.networkPassphrase) as Tx;
if (txn.built.operations.length !== 1) {
throw new Error(
"Transaction envelope must contain exactly one operation.",
);
}
const operation = txn.built.operations[0] as Operation.InvokeHostFunction;
if (!operation?.func?.value || typeof operation.func.value !== "function") {
throw new Error(
"Could not extract the method from the transaction envelope.",
);
}
const invokeContractArgs = operation.func.value() as xdr.InvokeContractArgs;
if (!invokeContractArgs?.functionName) {
throw new Error(
"Could not extract the method name from the transaction envelope.",
);
}
const xdrContractId = Address.fromScAddress(
invokeContractArgs.contractAddress(),
).toString();
if (xdrContractId !== options.contractId) {
throw new Error(
`Transaction envelope targets contract ${xdrContractId}, but this Client is configured for ${options.contractId}.`,
);
}
txn.simulationResult = {
auth: simulationResult.auth.map((a) =>
xdr.SorobanAuthorizationEntry.fromXDR(a, "base64"),
),
retval: xdr.ScVal.fromXDR(simulationResult.retval, "base64"),
};
txn.simulationTransactionData = xdr.SorobanTransactionData.fromXDR(
simulationTransactionData,
"base64",
);
return txn;
}
/**
* Serialize the AssembledTransaction to a base64-encoded XDR string.
*/
toXDR(): string {
if (!this.built)
throw new Error(
"Transaction has not yet been simulated; " +
"call `AssembledTransaction.simulate` first.",
);
return this.built?.toEnvelope().toXDR("base64");
}
/**
* Deserialize the AssembledTransaction from a base64-encoded XDR string.
*/
static fromXDR<T>(
options: Omit<
AssembledTransactionOptions<T>,
"args" | "method" | "parseResultXdr"
>,
encodedXDR: string,
spec: Spec,
): AssembledTransaction<T> {
const envelope = xdr.TransactionEnvelope.fromXDR(encodedXDR, "base64");
const built = TransactionBuilder.fromXDR(
envelope,
options.networkPassphrase,
) as Tx;
if (built.operations.length !== 1) {
throw new Error(
"Transaction envelope must contain exactly one operation.",
);
}
const operation = built.operations[0] as Operation.InvokeHostFunction;
if (!operation?.func?.value || typeof operation.func.value !== "function") {
throw new Error(
"Could not extract the method from the transaction envelope.",
);
}
const invokeContractArgs = operation.func.value() as xdr.InvokeContractArgs;
if (!invokeContractArgs?.functionName) {
throw new Error(
"Could not extract the method name from the transaction envelope.",
);
}
const xdrContractId = Address.fromScAddress(
invokeContractArgs.contractAddress(),
).toString();
if (xdrContractId !== options.contractId) {
throw new Error(
`Transaction envelope targets contract ${xdrContractId}, but this Client is configured for ${options.contractId}.`,
);
}
const method = invokeContractArgs.functionName().toString("utf-8");
const txn = new AssembledTransaction({
...options,
method,
parseResultXdr: (result: xdr.ScVal) =>
spec.funcResToNative(method, result),
});
txn.built = built;
return txn;
}
private handleWalletError(error?: WalletError): void {
if (!error) return;
const { message, code } = error;
const fullMessage = `${message}${error.ext ? ` (${error.ext.join(", ")})` : ""}`;
switch (code) {
case -1:
throw new AssembledTransaction.Errors.InternalWalletError(fullMessage);
case -2:
throw new AssembledTransaction.Errors.ExternalServiceError(fullMessage);
case -3:
throw new AssembledTransaction.Errors.InvalidClientRequest(fullMessage);
case -4:
throw new AssembledTransaction.Errors.UserRejected(fullMessage);
default:
throw new Error(`Unhandled error: ${fullMessage}`);
}
}
private constructor(public options: AssembledTransactionOptions<T>) {
this.options.simulate = this.options.simulate ?? true;
const { server, allowHttp, headers, rpcUrl } = this.options;
this.server = server ?? new Server(rpcUrl, { allowHttp, headers });
}
/**
* Construct a new AssembledTransaction. This is the main way to create a new
* AssembledTransaction; the constructor is private.
*
* This is an asynchronous constructor for two reasons:
*
* 1. It needs to fetch the account from the network to get the current
* sequence number.
* 2. It needs to simulate the transaction to get the expected fee.
*
* If you don't want to simulate the transaction, you can set `simulate` to
* `false` in the options.
*
* If you need to create an operation other than `invokeHostFunction`, you
* can use {@link AssembledTransaction.buildWithOp} instead.
*
* @example
* const tx = await AssembledTransaction.build({
* ...,
* simulate: false,
* })
*/
static build<T>(
options: AssembledTransactionOptions<T>,
): Promise<AssembledTransaction<T>> {
const contract = new Contract(options.contractId);
return AssembledTransaction.buildWithOp(
contract.call(options.method, ...(options.args ?? [])),
options,
);
}
/**
* Construct a new AssembledTransaction, specifying an Operation other than
* `invokeHostFunction` (the default used by {@link AssembledTransaction.build}).
*
* Note: `AssembledTransaction` currently assumes these operations can be
* simulated. This is not true for classic operations; only for those used by
* Soroban Smart Contracts like `invokeHostFunction` and `createCustomContract`.
*
* @example
* const tx = await AssembledTransaction.buildWithOp(
* Operation.createCustomContract({ ... });
* {
* ...,
* simulate: false,
* }
* )
*/
static async buildWithOp<T>(
operation: xdr.Operation,
options: AssembledTransactionOptions<T>,
): Promise<AssembledTransaction<T>> {
const tx = new AssembledTransaction(options);
const account = await getAccount(options, tx.server);
tx.raw = new TransactionBuilder(account, {
fee: options.fee ?? BASE_FEE,
networkPassphrase: options.networkPassphrase,
})
.setTimeout(options.timeoutInSeconds ?? DEFAULT_TIMEOUT)
.addOperation(operation);
if (options.simulate) await tx.simulate();
return tx;
}
private static async buildFootprintRestoreTransaction<T>(
options: AssembledTransactionOptions<T>,
sorobanData: SorobanDataBuilder | xdr.SorobanTransactionData,
account: Account,
fee: string,
): Promise<AssembledTransaction<T>> {
const tx = new AssembledTransaction(options);
tx.raw = new TransactionBuilder(account, {
fee,
networkPassphrase: options.networkPassphrase,
})
.setSorobanData(
sorobanData instanceof SorobanDataBuilder
? sorobanData.build()
: sorobanData,
)
.addOperation(Operation.restoreFootprint({}))
.setTimeout(options.timeoutInSeconds ?? DEFAULT_TIMEOUT);
await tx.simulate({ restore: false });
return tx;
}
simulate = async ({ restore }: { restore?: boolean } = {}): Promise<this> => {
if (!this.built) {
if (!this.raw) {
throw new Error(
"Transaction has not yet been assembled; " +
"call `AssembledTransaction.build` first.",
);
}
this.built = this.raw.build();
}
restore = restore ?? this.options.restore;
// need to force re-calculation of simulationData for new simulation
delete this.simulationResult;
delete this.simulationTransactionData;
this.simulation = await this.server.simulateTransaction(this.built);
if (restore && Api.isSimulationRestore(this.simulation)) {
const account = await getAccount(this.options, this.server);
const result = await this.restoreFootprint(
this.simulation.restorePreamble,
account,
);
if (result.status === Api.GetTransactionStatus.SUCCESS) {
// need to rebuild the transaction with bumped account sequence number
const contract = new Contract(this.options.contractId);
this.raw = new TransactionBuilder(account, {
fee: this.options.fee ?? BASE_FEE,
networkPassphrase: this.options.networkPassphrase,
})
.addOperation(
contract.call(this.options.method, ...(this.options.args ?? [])),
)
.setTimeout(this.options.timeoutInSeconds ?? DEFAULT_TIMEOUT);
await this.simulate();
return this;
}
throw new AssembledTransaction.Errors.RestorationFailure(
`Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\n${JSON.stringify(result)}`,
);
}
if (Api.isSimulationSuccess(this.simulation)) {
this.built = assembleTransaction(this.built, this.simulation).build();
}
return this;
};
get simulationData(): {
result: Api.SimulateHostFunctionResult;
transactionData: xdr.SorobanTransactionData;
} {
if (this.simulationResult && this.simulationTransactionData) {
return {
result: this.simulationResult,
transactionData: this.simulationTransactionData,
};
}
const simulation = this.simulation!;
if (!simulation) {
throw new AssembledTransaction.Errors.NotYetSimulated(
"Transaction has not yet been simulated",
);
}
if (Api.isSimulationError(simulation)) {
throw new AssembledTransaction.Errors.SimulationFailed(
`Transaction simulation failed: "${simulation.error}"`,
);
}
if (Api.isSimulationRestore(simulation)) {
throw new AssembledTransaction.Errors.ExpiredState(
`You need to restore some contract state before you can invoke this method.\n` +
"You can set `restore` to true in the method options in order to " +
"automatically restore the contract state when needed.",
);
}
// add to object for serialization & deserialization
this.simulationResult = simulation.result ?? {
auth: [],
retval: xdr.ScVal.scvVoid(),
};
this.simulationTransactionData = simulation.transactionData.build();
return {
result: this.simulationResult,
transactionData: this.simulationTransactionData!,
};
}
get result(): T {
try {
if (!this.simulationData.result) {
throw new Error("No simulation result!");
}
return this.options.parseResultXdr(this.simulationData.result.retval);
} catch (e) {
if (!implementsToString(e)) throw e;
const err = this.parseError(e.toString());
if (err) return err as T;
throw e;
}
}
private parseError(errorMessage: string) {
if (!this.options.errorTypes) return undefined;
const match = errorMessage.match(contractErrorPattern);
if (!match) return undefined;
const i = parseInt(match[1], 10);
const err = this.options.errorTypes[i];
if (!err) return undefined;
return new Err(err);
}
/**
* Sign the transaction with the signTransaction function included previously.
* If you did not previously include one, you need to include one now.
*/
sign = async ({
force = false,
signTransaction = this.options.signTransaction,
}: {
/**
* If `true`, sign and send the transaction even if it is a read call
*/
force?: boolean;
/**
* You must provide this here if you did not provide one before
*/
signTransaction?: ClientOptions["signTransaction"];
} = {}): Promise<void> => {
if (!this.built) {
throw new Error("Transaction has not yet been simulated");
}
if (!force && this.isReadCall) {
throw new AssembledTransaction.Errors.NoSignatureNeeded(
"This is a read call. It requires no signature or sending. " +
"Use `force: true` to sign and send anyway.",
);
}
if (!signTransaction) {
throw new AssembledTransaction.Errors.NoSigner(
"You must provide a signTransaction function, either when calling " +
"`signAndSend` or when initializing your Client",
);
}
if (!this.options.publicKey) {
throw new AssembledTransaction.Errors.FakeAccount(
"This transaction was constructed using a default account. Provide a valid publicKey in the AssembledTransactionOptions.",
);
}
// filter out contracts, as these are dealt with via cross contract calls
const sigsNeeded = this.needsNonInvokerSigningBy().filter(
(id) => !id.startsWith("C"),
);
if (sigsNeeded.length) {
throw new AssembledTransaction.Errors.NeedsMoreSignatures(
`Transaction requires signatures from ${sigsNeeded}. ` +
"See `needsNonInvokerSigningBy` for details.",
);
}
const timeoutInSeconds = this.options.timeoutInSeconds ?? DEFAULT_TIMEOUT;
this.built = TransactionBuilder.cloneFrom(this.built!, {
fee: this.built!.fee,
timebounds: undefined,
sorobanData: this.simulationData.transactionData,
})
.setTimeout(timeoutInSeconds)
.build();
const signOpts: Parameters<
NonNullable<ClientOptions["signTransaction"]>
>[1] = {
networkPassphrase: this.options.networkPassphrase,
};
if (this.options.address) signOpts.address = this.options.address;
if (this.options.submit !== undefined)
signOpts.submit = this.options.submit;
if (this.options.submitUrl) signOpts.submitUrl = this.options.submitUrl;
const { signedTxXdr: signature, error } = await signTransaction(
this.built.toXDR(),
signOpts,
);
this.handleWalletError(error);
this.signed = TransactionBuilder.fromXDR(
signature,
this.options.networkPassphrase,
) as Tx;
};
/**
* Sends the transaction to the network to return a `SentTransaction` that
* keeps track of all the attempts to fetch the transaction. Optionally pass
* a {@link Watcher} that allows you to keep track of the progress as the
* transaction is sent and processed.
*/
async send(watcher?: Watcher) {
if (!this.signed) {
throw new Error(
"The transaction has not yet been signed. Run `sign` first, or use `signAndSend` instead.",
);
}
const sent = await SentTransaction.init(this, watcher);
return sent;
}
/**
* Sign the transaction with the `signTransaction` function included previously.
* If you did not previously include one, you need to include one now.
* After signing, this method will send the transaction to the network and
* return a `SentTransaction` that keeps track of all the attempts to fetch
* the transaction. You may pass a {@link Watcher} to keep
* track of this progress.
*/
signAndSend = async ({
force = false,
signTransaction = this.options.signTransaction,
watcher,
}: {
/**
* If `true`, sign and send the transaction even if it is a read call
*/
force?: boolean;
/**
* You must provide this here if you did not provide one before
*/
signTransaction?: ClientOptions["signTransaction"];
/**
* A {@link Watcher} to notify after the transaction is successfully
* submitted to the network (`onSubmitted`) and as the transaction is
* processed (`onProgress`).
*/
watcher?: Watcher;
} = {}): Promise<SentTransaction<T>> => {
if (!this.signed) {
// Store the original submit option
const originalSubmit = this.options.submit;
// Temporarily disable submission in signTransaction to prevent double submission
if (this.options.submit) {
this.options.submit = false;
}
try {
await this.sign({ force, signTransaction });
} finally {
// Restore the original submit option
this.options.submit = originalSubmit;
}
}
return this.send(watcher);
};
/**
* Get a list of accounts, other than the invoker of the simulation, that
* need to sign auth entries in this transaction.
*
* Soroban allows multiple people to sign a transaction. Someone needs to
* sign the final transaction envelope; this person/account is called the
* _invoker_, or _source_. Other accounts might need to sign individual auth
* entries in the transaction, if they're not also the invoker.
*
* This function returns a list of accounts that need to sign auth entries,
* assuming that the same invoker/source account will sign the final
* transaction envelope as signed the initial simulation.
*
* One at a time, for each public key in this array, you will need to
* serialize this transaction with `toJSON`, send to the owner of that key,
* deserialize the transaction with `txFromJson`, and call
* {@link AssembledTransaction#signAuthEntries}. Then re-serialize and send to
* the next account in this list.
*/
needsNonInvokerSigningBy = ({
includeAlreadySigned = false,
}: {
/**
* Whether or not to include auth entries that have already been signed.
* Default: false
*/
includeAlreadySigned?: boolean;
} = {}): string[] => {
if (!this.built) {
throw new Error("Transaction has not yet been simulated");
}
// We expect that any transaction constructed by these libraries has a
// single operation, which is an InvokeHostFunction operation. The host
// function being invoked is the contract method call.
if (!("operations" in this.built)) {
throw new Error(
`Unexpected Transaction type; no operations: ${JSON.stringify(
this.built,
)}`,
);
}
const rawInvokeHostFunctionOp = this.built
.operations[0] as Operation.InvokeHostFunction;
return [
...new Set(
(rawInvokeHostFunctionOp.auth ?? [])
.filter(
(entry) =>
entry.credentials().switch() ===
xdr.SorobanCredentialsType.sorobanCredentialsAddress() &&
(includeAlreadySigned ||
entry.credentials().address().signature().switch().name ===
"scvVoid"),
)
.map((entry) =>
Address.fromScAddress(
entry.credentials().address().address(),
).toString(),
),
),
];
};
/**
* If {@link AssembledTransaction#needsNonInvokerSigningBy} returns a
* non-empty list, you can serialize the transaction with `toJSON`, send it to
* the owner of one of the public keys in the map, deserialize with
* `txFromJSON`, and call this method on their machine. Internally, this will
* use `signAuthEntry` function from connected `wallet` for each.
*
* Then, re-serialize the transaction and either send to the next
* `needsNonInvokerSigningBy` owner, or send it back to the original account
* who simulated the transaction so they can {@link AssembledTransaction#sign}
* the transaction envelope and {@link AssembledTransaction#send} it to the
* network.
*
* Sending to all `needsNonInvokerSigningBy` owners in parallel is not
* currently supported!
*/
signAuthEntries = async ({
expiration = (async () =>
(await this.server.getLatestLedger()).sequence + 100)(),
signAuthEntry = this.options.signAuthEntry,
address = this.options.publicKey,
authorizeEntry = stellarBaseAuthorizeEntry,
}: {
/**
* When to set each auth entry to expire. Could be any number of blocks in
* the future. Can be supplied as a promise or a raw number. Default:
* about 8.3 minutes from now.
*/
expiration?: number | Promise<number>;
/**
* Sign all auth entries for this account. Default: the account that
* constructed the transaction
*/
address?: string;
/**
* You must provide this here if you did not provide one before and you are not passing `authorizeEntry`. Default: the `signAuthEntry` function from the `Client` options. Must sign things as the given `publicKey`.
*/
signAuthEntry?: ClientOptions["signAuthEntry"];
/**
* If you have a pro use-case and need to override the default `authorizeEntry` function, rather than using the one in `@stellar/stellar-base`, you can do that! Your function needs to take at least the first argument, `entry: xdr.SorobanAuthorizationEntry`, and return a `Promise<xdr.SorobanAuthorizationEntry>`.
*
* Note that you if you pass this, then `signAuthEntry` will be ignored.
*/
authorizeEntry?: typeof stellarBaseAuthorizeEntry;
} = {}): Promise<void> => {
if (!this.built)
throw new Error("Transaction has not yet been assembled or simulated");
// Likely if we're using a custom authorizeEntry then we know better than the `needsNonInvokerSigningBy` logic.
if (authorizeEntry === stellarBaseAuthorizeEntry) {
const needsNonInvokerSigningBy = this.needsNonInvokerSigningBy();
if (needsNonInvokerSigningBy.length === 0) {
throw new AssembledTransaction.Errors.NoUnsignedNonInvokerAuthEntries(
"No unsigned non-invoker auth entries; maybe you already signed?",
);
}
if (needsNonInvokerSigningBy.indexOf(address ?? "") === -1) {
throw new AssembledTransaction.Errors.NoSignatureNeeded(
`No auth entries for public key "${address}"`,
);