-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
provider.ts
1708 lines (1522 loc) · 53.5 KB
/
provider.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 } from '@fuel-ts/address';
import { ErrorCode, FuelError } from '@fuel-ts/errors';
import type { AbstractAccount, AbstractAddress, BytesLike } from '@fuel-ts/interfaces';
import { BN, bn } from '@fuel-ts/math';
import type { Transaction } from '@fuel-ts/transactions';
import {
InputType,
TransactionType,
InputMessageCoder,
TransactionCoder,
} from '@fuel-ts/transactions';
import { arrayify, hexlify, DateTime } from '@fuel-ts/utils';
import { checkFuelCoreVersionCompatibility } from '@fuel-ts/versions';
import { equalBytes } from '@noble/curves/abstract/utils';
import type { DocumentNode } from 'graphql';
import { GraphQLClient } from 'graphql-request';
import type { GraphQLResponse } from 'graphql-request/src/types';
import { clone } from 'ramda';
import type { Predicate } from '../predicate';
import { getSdk as getOperationsSdk } from './__generated__/operations';
import type {
GqlChainInfoFragmentFragment,
GqlConsensusParametersVersion,
GqlContractParameters,
GqlDryRunFailureStatusFragmentFragment,
GqlDryRunSuccessStatusFragmentFragment,
GqlFeeParameters,
GqlGasCosts,
GqlGetBlocksQueryVariables,
GqlMessage,
GqlPredicateParameters,
GqlRelayedTransactionFailed,
GqlScriptParameters,
GqlTxParameters,
} from './__generated__/operations';
import type { Coin } from './coin';
import type { CoinQuantity, CoinQuantityLike } from './coin-quantity';
import { coinQuantityfy } from './coin-quantity';
import { FuelGraphqlSubscriber } from './fuel-graphql-subscriber';
import { MemoryCache } from './memory-cache';
import type { Message, MessageCoin, MessageProof, MessageStatus } from './message';
import type { ExcludeResourcesOption, Resource } from './resource';
import type {
TransactionRequestLike,
TransactionRequest,
TransactionRequestInput,
CoinTransactionRequestInput,
ScriptTransactionRequest,
JsonAbisFromAllCalls,
} from './transaction-request';
import { transactionRequestify } from './transaction-request';
import type { TransactionResultReceipt } from './transaction-response';
import { TransactionResponse } from './transaction-response';
import { processGqlReceipt } from './transaction-summary/receipt';
import { calculateGasFee, getGasUsedFromReceipts, getReceiptsWithMissingData } from './utils';
import type { RetryOptions } from './utils/auto-retry-fetch';
import { autoRetryFetch } from './utils/auto-retry-fetch';
import { mergeQuantities } from './utils/merge-quantities';
const MAX_RETRIES = 10;
export type DryRunStatus =
| Omit<GqlDryRunFailureStatusFragmentFragment, '__typename'>
| Omit<GqlDryRunSuccessStatusFragmentFragment, '__typename'>;
export type CallResult = {
receipts: TransactionResultReceipt[];
dryRunStatus?: DryRunStatus;
};
export type EstimateTxDependenciesReturns = CallResult & {
outputVariables: number;
missingContractIds: string[];
};
/**
* A Fuel block
*/
export type Block = {
id: string;
height: BN;
time: string;
transactionIds: string[];
};
/**
* Deployed Contract bytecode and contract id
*/
export type ContractResult = {
id: string;
bytecode: string;
};
type ModifyStringToBN<T> = {
[P in keyof T]: P extends 'version' ? T[P] : T[P] extends string ? BN : T[P];
};
export type FeeParameters = Omit<GqlFeeParameters, '__typename'>;
export type ContractParameters = Omit<GqlContractParameters, '__typename'>;
export type PredicateParameters = Omit<GqlPredicateParameters, '__typename'>;
export type ScriptParameters = Omit<GqlScriptParameters, '__typename'>;
export type TxParameters = Omit<GqlTxParameters, '__typename'>;
export type GasCosts = Omit<GqlGasCosts, '__typename'>;
export type ConsensusParameters = {
version: GqlConsensusParametersVersion;
chainId: BN;
baseAssetId: string;
feeParameters: ModifyStringToBN<FeeParameters>;
contractParameters: ModifyStringToBN<ContractParameters>;
predicateParameters: ModifyStringToBN<PredicateParameters>;
scriptParameters: ModifyStringToBN<ScriptParameters>;
txParameters: ModifyStringToBN<TxParameters>;
gasCosts: GasCosts;
};
/**
* Chain information
*/
export type ChainInfo = {
name: string;
baseChainHeight: BN;
consensusParameters: ConsensusParameters;
latestBlock: {
id: string;
height: BN;
time: string;
transactions: Array<{ id: string }>;
};
};
/**
* Node information
*/
export type NodeInfo = {
utxoValidation: boolean;
vmBacktrace: boolean;
maxTx: BN;
maxDepth: BN;
nodeVersion: string;
};
export type NodeInfoAndConsensusParameters = {
nodeVersion: string;
gasPerByte: BN;
gasPriceFactor: BN;
maxGasPerTx: BN;
};
// #region cost-estimation-1
export type TransactionCost = {
gasPrice: BN;
gasUsed: BN;
minGas: BN;
minFee: BN;
maxFee: BN;
maxGas: BN;
receipts: TransactionResultReceipt[];
outputVariables: number;
missingContractIds: string[];
estimatedPredicates: TransactionRequestInput[];
requiredQuantities: CoinQuantity[];
addedSignatures: number;
dryRunStatus?: DryRunStatus;
};
// #endregion cost-estimation-1
const processGqlChain = (chain: GqlChainInfoFragmentFragment): ChainInfo => {
const { name, daHeight, consensusParameters, latestBlock } = chain;
const {
contractParams,
feeParams,
predicateParams,
scriptParams,
txParams,
gasCosts,
baseAssetId,
chainId,
version,
} = consensusParameters;
return {
name,
baseChainHeight: bn(daHeight),
consensusParameters: {
version,
chainId: bn(chainId),
baseAssetId,
feeParameters: {
version: feeParams.version,
gasPerByte: bn(feeParams.gasPerByte),
gasPriceFactor: bn(feeParams.gasPriceFactor),
},
contractParameters: {
version: contractParams.version,
contractMaxSize: bn(contractParams.contractMaxSize),
maxStorageSlots: bn(contractParams.maxStorageSlots),
},
txParameters: {
version: txParams.version,
maxInputs: bn(txParams.maxInputs),
maxOutputs: bn(txParams.maxOutputs),
maxWitnesses: bn(txParams.maxWitnesses),
maxGasPerTx: bn(txParams.maxGasPerTx),
maxSize: bn(txParams.maxSize),
maxBytecodeSubsections: bn(txParams.maxBytecodeSubsections),
},
predicateParameters: {
version: predicateParams.version,
maxPredicateLength: bn(predicateParams.maxPredicateLength),
maxPredicateDataLength: bn(predicateParams.maxPredicateDataLength),
maxGasPerPredicate: bn(predicateParams.maxGasPerPredicate),
maxMessageDataLength: bn(predicateParams.maxMessageDataLength),
},
scriptParameters: {
version: scriptParams.version,
maxScriptLength: bn(scriptParams.maxScriptLength),
maxScriptDataLength: bn(scriptParams.maxScriptDataLength),
},
gasCosts,
},
latestBlock: {
id: latestBlock.id,
height: bn(latestBlock.height),
time: latestBlock.header.time,
transactions: latestBlock.transactions.map((i) => ({
id: i.id,
})),
},
};
};
/**
* @hidden
*
* Cursor pagination arguments
*
* https://relay.dev/graphql/connections.htm#sec-Arguments
*/
export type CursorPaginationArgs = {
/** Forward pagination limit */
first?: number | null;
/** Forward pagination cursor */
after?: string | null;
/** Backward pagination limit */
last?: number | null;
/** Backward pagination cursor */
before?: string | null;
};
/*
* Provider initialization options
*/
export type ProviderOptions = {
/**
* Custom fetch function to use for making requests.
*/
fetch?: (
url: string,
requestInit?: RequestInit,
providerOptions?: Omit<ProviderOptions, 'fetch'>
) => Promise<Response>;
/**
* Timeout [ms] after which every request will be aborted.
*/
timeout?: number;
/**
* Cache UTXOs for the given time [ms].
*/
cacheUtxo?: number;
/**
* Retry options to use when fetching data from the node.
*/
retryOptions?: RetryOptions;
/**
* Middleware to modify the request before it is sent.
* This can be used to add headers, modify the body, etc.
*/
requestMiddleware?: (request: RequestInit) => RequestInit | Promise<RequestInit>;
};
/**
* UTXO Validation Param
*/
export type UTXOValidationParams = {
utxoValidation?: boolean;
};
/**
* Transaction estimation Param
*/
export type EstimateTransactionParams = {
estimateTxDependencies?: boolean;
};
export type TransactionCostParams = EstimateTransactionParams & {
resourcesOwner?: AbstractAccount;
quantitiesToContract?: CoinQuantity[];
signatureCallback?: (request: ScriptTransactionRequest) => Promise<ScriptTransactionRequest>;
};
/**
* Provider Call transaction params
*/
export type ProviderCallParams = UTXOValidationParams & EstimateTransactionParams;
/**
* Provider Send transaction params
*/
export type ProviderSendTxParams = EstimateTransactionParams & {
/**
* By default, the promise will resolve immediately after the transaction is submitted.
*
* If set to true, the promise will resolve only when the transaction changes status
* from `SubmittedStatus` to one of `SuccessStatus`, `FailureStatus` or `SqueezedOutStatus`.
*
*/
awaitExecution?: boolean;
};
/**
* URL - Consensus Params mapping.
*/
type ChainInfoCache = Record<string, ChainInfo>;
/**
* URL - Node Info mapping.
*/
type NodeInfoCache = Record<string, NodeInfo>;
/**
* A provider for connecting to a node
*/
export default class Provider {
operations: ReturnType<typeof getOperationsSdk>;
cache?: MemoryCache;
static clearChainAndNodeCaches() {
Provider.nodeInfoCache = {};
Provider.chainInfoCache = {};
}
private static chainInfoCache: ChainInfoCache = {};
private static nodeInfoCache: NodeInfoCache = {};
options: ProviderOptions = {
timeout: undefined,
cacheUtxo: undefined,
fetch: undefined,
retryOptions: undefined,
};
private static getFetchFn(options: ProviderOptions): NonNullable<ProviderOptions['fetch']> {
const { retryOptions, timeout } = options;
return autoRetryFetch(async (...args) => {
const url = args[0];
const request = args[1];
const signal = timeout ? AbortSignal.timeout(timeout) : undefined;
let fullRequest: RequestInit = { ...request, signal };
if (options.requestMiddleware) {
fullRequest = await options.requestMiddleware(fullRequest);
}
return options.fetch ? options.fetch(url, fullRequest, options) : fetch(url, fullRequest);
}, retryOptions);
}
/**
* Constructor to initialize a Provider.
*
* @param url - GraphQL endpoint of the Fuel node
* @param chainInfo - Chain info of the Fuel node
* @param options - Additional options for the provider
* @hidden
*/
protected constructor(
/** GraphQL endpoint of the Fuel node */
public url: string,
options: ProviderOptions = {}
) {
this.options = { ...this.options, ...options };
this.url = url;
this.operations = this.createOperations();
this.cache = options.cacheUtxo ? new MemoryCache(options.cacheUtxo) : undefined;
}
/**
* Creates a new instance of the Provider class. This is the recommended way to initialize a Provider.
* @param url - GraphQL endpoint of the Fuel node
* @param options - Additional options for the provider
*/
static async create(url: string, options: ProviderOptions = {}) {
const provider = new Provider(url, options);
await provider.fetchChainAndNodeInfo();
return provider;
}
/**
* Returns the cached chainInfo for the current URL.
*/
getChain() {
const chain = Provider.chainInfoCache[this.url];
if (!chain) {
throw new FuelError(
ErrorCode.CHAIN_INFO_CACHE_EMPTY,
'Chain info cache is empty. Make sure you have called `Provider.create` to initialize the provider.'
);
}
return chain;
}
/**
* Returns the cached nodeInfo for the current URL.
*/
getNode() {
const node = Provider.nodeInfoCache[this.url];
if (!node) {
throw new FuelError(
ErrorCode.NODE_INFO_CACHE_EMPTY,
'Node info cache is empty. Make sure you have called `Provider.create` to initialize the provider.'
);
}
return node;
}
/**
* Returns some helpful parameters related to gas fees.
*/
getGasConfig() {
const {
txParameters: { maxGasPerTx },
predicateParameters: { maxGasPerPredicate },
feeParameters: { gasPriceFactor, gasPerByte },
gasCosts,
} = this.getChain().consensusParameters;
return {
maxGasPerTx,
maxGasPerPredicate,
gasPriceFactor,
gasPerByte,
gasCosts,
};
}
/**
* Updates the URL for the provider and fetches the consensus parameters for the new URL, if needed.
*/
async connect(url: string, options?: ProviderOptions) {
this.url = url;
this.options = options ?? this.options;
this.operations = this.createOperations();
await this.fetchChainAndNodeInfo();
}
/**
* Fetches both the chain and node information, saves it to the cache, and return it.
*
* @returns NodeInfo and Chain
*/
async fetchChainAndNodeInfo() {
const chain = await this.fetchChain();
const nodeInfo = await this.fetchNode();
Provider.ensureClientVersionIsSupported(nodeInfo);
return {
chain,
nodeInfo,
};
}
private static ensureClientVersionIsSupported(nodeInfo: NodeInfo) {
const { isMajorSupported, isMinorSupported, supportedVersion } =
checkFuelCoreVersionCompatibility(nodeInfo.nodeVersion);
if (!isMajorSupported || !isMinorSupported) {
// eslint-disable-next-line no-console
console.warn(
`The Fuel Node that you are trying to connect to is using fuel-core version ${nodeInfo.nodeVersion},
which is not supported by the version of the TS SDK that you are using.
Things may not work as expected.
Supported fuel-core version: ${supportedVersion}.`
);
}
}
/**
* Create GraphQL client and set operations.
*
* @returns The operation SDK object
*/
private createOperations() {
const fetchFn = Provider.getFetchFn(this.options);
const gqlClient = new GraphQLClient(this.url, {
fetch: (url: string, requestInit: RequestInit) => fetchFn(url, requestInit, this.options),
responseMiddleware: (response: GraphQLResponse<unknown> | Error) => {
if ('response' in response) {
const graphQlResponse = response.response as GraphQLResponse;
if (Array.isArray(graphQlResponse?.errors)) {
throw new FuelError(
FuelError.CODES.INVALID_REQUEST,
graphQlResponse.errors.map((err: Error) => err.message).join('\n\n')
);
}
}
},
});
const executeQuery = (query: DocumentNode, vars: Record<string, unknown>) => {
const opDefinition = query.definitions.find((x) => x.kind === 'OperationDefinition') as {
operation: string;
};
const isSubscription = opDefinition?.operation === 'subscription';
if (isSubscription) {
return new FuelGraphqlSubscriber({
url: this.url,
query,
fetchFn: (url, requestInit) => fetchFn(url as string, requestInit, this.options),
variables: vars,
});
}
return gqlClient.request(query, vars);
};
// @ts-expect-error This is due to this function being generic. Its type is specified when calling a specific operation via provider.operations.xyz.
return getOperationsSdk(executeQuery);
}
/**
* Returns the version of the connected node.
*
* @returns A promise that resolves to the version string.
*/
async getVersion(): Promise<string> {
const {
nodeInfo: { nodeVersion },
} = await this.operations.getVersion();
return nodeVersion;
}
/**
* Returns the block number.
*
* @returns A promise that resolves to the block number
*/
async getBlockNumber(): Promise<BN> {
const { chain } = await this.operations.getChain();
return bn(chain.latestBlock.height, 10);
}
/**
* Returns the chain information.
* @param url - The URL of the Fuel node
* @returns NodeInfo object
*/
async fetchNode(): Promise<NodeInfo> {
const { nodeInfo } = await this.operations.getNodeInfo();
const processedNodeInfo: NodeInfo = {
maxDepth: bn(nodeInfo.maxDepth),
maxTx: bn(nodeInfo.maxTx),
nodeVersion: nodeInfo.nodeVersion,
utxoValidation: nodeInfo.utxoValidation,
vmBacktrace: nodeInfo.vmBacktrace,
};
Provider.nodeInfoCache[this.url] = processedNodeInfo;
return processedNodeInfo;
}
/**
* Fetches the `chainInfo` for the given node URL.
* @param url - The URL of the Fuel node
* @returns ChainInfo object
*/
async fetchChain(): Promise<ChainInfo> {
const { chain } = await this.operations.getChain();
const processedChain = processGqlChain(chain);
Provider.chainInfoCache[this.url] = processedChain;
return processedChain;
}
/**
* Returns the chain ID
* @returns A promise that resolves to the chain ID number
*/
getChainId() {
const {
consensusParameters: { chainId },
} = this.getChain();
return chainId.toNumber();
}
/**
* Returns the base asset ID for the current provider network
*
* @returns the base asset ID
*/
getBaseAssetId() {
const {
consensusParameters: { baseAssetId },
} = this.getChain();
return baseAssetId;
}
/**
* @hidden
*/
#cacheInputs(inputs: TransactionRequestInput[]): void {
if (!this.cache) {
return;
}
inputs.forEach((input) => {
if (input.type === InputType.Coin) {
this.cache?.set(input.id);
}
});
}
/**
* Submits a transaction to the chain to be executed.
*
* If the transaction is missing any dependencies,
* the transaction will be mutated and those dependencies will be added.
*
* @param transactionRequestLike - The transaction request object.
* @returns A promise that resolves to the transaction response object.
*/
// #region Provider-sendTransaction
async sendTransaction(
transactionRequestLike: TransactionRequestLike,
{ estimateTxDependencies = true, awaitExecution = false }: ProviderSendTxParams = {}
): Promise<TransactionResponse> {
const transactionRequest = transactionRequestify(transactionRequestLike);
this.#cacheInputs(transactionRequest.inputs);
if (estimateTxDependencies) {
await this.estimateTxDependencies(transactionRequest);
}
// #endregion Provider-sendTransaction
const encodedTransaction = hexlify(transactionRequest.toTransactionBytes());
let abis: JsonAbisFromAllCalls | undefined;
if (transactionRequest.type === TransactionType.Script) {
abis = transactionRequest.abis;
}
if (awaitExecution) {
const subscription = this.operations.submitAndAwait({ encodedTransaction });
for await (const { submitAndAwait } of subscription) {
if (submitAndAwait.type === 'SqueezedOutStatus') {
throw new FuelError(
ErrorCode.TRANSACTION_SQUEEZED_OUT,
`Transaction Squeezed Out with reason: ${submitAndAwait.reason}`
);
}
if (submitAndAwait.type !== 'SubmittedStatus') {
break;
}
}
const transactionId = transactionRequest.getTransactionId(this.getChainId());
const response = new TransactionResponse(transactionId, this, abis);
await response.fetch();
return response;
}
const {
submit: { id: transactionId },
} = await this.operations.submit({ encodedTransaction });
return new TransactionResponse(transactionId, this, abis);
}
/**
* Executes a transaction without actually submitting it to the chain.
*
* If the transaction is missing any dependencies,
* the transaction will be mutated and those dependencies will be added.
*
* @param transactionRequestLike - The transaction request object.
* @param utxoValidation - Additional provider call parameters.
* @returns A promise that resolves to the call result object.
*/
async call(
transactionRequestLike: TransactionRequestLike,
{ utxoValidation, estimateTxDependencies = true }: ProviderCallParams = {}
): Promise<CallResult> {
const transactionRequest = transactionRequestify(transactionRequestLike);
if (estimateTxDependencies) {
return this.estimateTxDependencies(transactionRequest);
}
const encodedTransaction = hexlify(transactionRequest.toTransactionBytes());
const { dryRun: dryRunStatuses } = await this.operations.dryRun({
encodedTransactions: encodedTransaction,
utxoValidation: utxoValidation || false,
});
const [{ receipts: rawReceipts, status: dryRunStatus }] = dryRunStatuses;
const receipts = rawReceipts.map(processGqlReceipt);
return { receipts, dryRunStatus };
}
/**
* Verifies whether enough gas is available to complete transaction.
*
* @param transactionRequest - The transaction request object.
* @returns A promise that resolves to the estimated transaction request object.
*/
async estimatePredicates(transactionRequest: TransactionRequest): Promise<TransactionRequest> {
const shouldEstimatePredicates = Boolean(
transactionRequest.inputs.find(
(input) =>
'predicate' in input &&
input.predicate &&
!equalBytes(arrayify(input.predicate), arrayify('0x')) &&
new BN(input.predicateGasUsed).isZero()
)
);
if (!shouldEstimatePredicates) {
return transactionRequest;
}
const encodedTransaction = hexlify(transactionRequest.toTransactionBytes());
const response = await this.operations.estimatePredicates({
encodedTransaction,
});
const {
estimatePredicates: { inputs },
} = response;
if (inputs) {
inputs.forEach((input, index) => {
if ('predicateGasUsed' in input && bn(input.predicateGasUsed).gt(0)) {
// eslint-disable-next-line no-param-reassign
(<CoinTransactionRequestInput>transactionRequest.inputs[index]).predicateGasUsed =
input.predicateGasUsed;
}
});
}
return transactionRequest;
}
/**
* Will dryRun a transaction and check for missing dependencies.
*
* If there are missing variable outputs,
* `addVariableOutputs` is called on the transaction.
*
*
* @param transactionRequest - The transaction request object.
* @returns A promise.
*/
async estimateTxDependencies(
transactionRequest: TransactionRequest
): Promise<EstimateTxDependenciesReturns> {
if (transactionRequest.type === TransactionType.Create) {
return {
receipts: [],
outputVariables: 0,
missingContractIds: [],
};
}
let receipts: TransactionResultReceipt[] = [];
const missingContractIds: string[] = [];
let outputVariables = 0;
let dryRunStatus: DryRunStatus | undefined;
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
const {
dryRun: [{ receipts: rawReceipts, status }],
} = await this.operations.dryRun({
encodedTransactions: [hexlify(transactionRequest.toTransactionBytes())],
utxoValidation: false,
});
receipts = rawReceipts.map(processGqlReceipt);
dryRunStatus = status;
const { missingOutputVariables, missingOutputContractIds } =
getReceiptsWithMissingData(receipts);
const hasMissingOutputs =
missingOutputVariables.length !== 0 || missingOutputContractIds.length !== 0;
if (hasMissingOutputs) {
outputVariables += missingOutputVariables.length;
transactionRequest.addVariableOutputs(missingOutputVariables.length);
missingOutputContractIds.forEach(({ contractId }) => {
transactionRequest.addContractInputAndOutput(Address.fromString(contractId));
missingContractIds.push(contractId);
});
const { maxFee } = await this.estimateTxGasAndFee({
transactionRequest,
});
// eslint-disable-next-line no-param-reassign
transactionRequest.maxFee = maxFee;
} else {
break;
}
}
return {
receipts,
outputVariables,
missingContractIds,
dryRunStatus,
};
}
/**
* Dry runs multiple transactions and checks for missing dependencies in batches.
*
* Transactions are dry run in batches. After each dry run, transactions requiring
* further modifications are identified. The method iteratively updates these transactions
* and performs subsequent dry runs until all dependencies for each transaction are satisfied.
*
* @param transactionRequests - Array of transaction request objects.
* @returns A promise that resolves to an array of results for each transaction.
*/
async estimateMultipleTxDependencies(
transactionRequests: TransactionRequest[]
): Promise<EstimateTxDependenciesReturns[]> {
const results: EstimateTxDependenciesReturns[] = transactionRequests.map(() => ({
receipts: [],
outputVariables: 0,
missingContractIds: [],
dryRunStatus: undefined,
}));
const allRequests = clone(transactionRequests);
// Map of original request index to its serialized transaction (for ScriptTransactionRequest only)
const serializedTransactionsMap = new Map();
// Prepare ScriptTransactionRequests and their indices
allRequests.forEach((req, index) => {
if (req.type === TransactionType.Script) {
serializedTransactionsMap.set(index, hexlify(req.toTransactionBytes()));
}
});
// Indices of ScriptTransactionRequests
let transactionsToProcess = Array.from(serializedTransactionsMap.keys());
let attempt = 0;
while (transactionsToProcess.length > 0 && attempt < MAX_RETRIES) {
const encodedTransactions = transactionsToProcess.map((index) =>
serializedTransactionsMap.get(index)
);
const dryRunResults = await this.operations.dryRun({
encodedTransactions,
utxoValidation: false,
});
const nextRoundTransactions = [];
for (let i = 0; i < dryRunResults.dryRun.length; i++) {
const requestIdx = transactionsToProcess[i];
const { receipts: rawReceipts, status } = dryRunResults.dryRun[i];
const result = results[requestIdx];
result.receipts = rawReceipts.map(processGqlReceipt);
result.dryRunStatus = status;
const { missingOutputVariables, missingOutputContractIds } = getReceiptsWithMissingData(
result.receipts
);
const hasMissingOutputs =
missingOutputVariables.length > 0 || missingOutputContractIds.length > 0;
const request = allRequests[requestIdx];
if (hasMissingOutputs && request?.type === TransactionType.Script) {
result.outputVariables += missingOutputVariables.length;
request.addVariableOutputs(missingOutputVariables.length);
missingOutputContractIds.forEach(({ contractId }) => {
request.addContractInputAndOutput(Address.fromString(contractId));
result.missingContractIds.push(contractId);
});
const { maxFee } = await this.estimateTxGasAndFee({
transactionRequest: request,
});
request.maxFee = maxFee;
// Prepare for the next round of dry run
serializedTransactionsMap.set(requestIdx, hexlify(request.toTransactionBytes()));
nextRoundTransactions.push(requestIdx);
}
}
transactionsToProcess = nextRoundTransactions;
attempt += 1;
}
return results;
}
async dryRunMultipleTransactions(
transactionRequests: TransactionRequest[],
{ utxoValidation, estimateTxDependencies = true }: ProviderCallParams = {}
): Promise<CallResult[]> {
if (estimateTxDependencies) {
return this.estimateMultipleTxDependencies(transactionRequests);
}
const encodedTransactions = transactionRequests.map((tx) => hexlify(tx.toTransactionBytes()));
const { dryRun: dryRunStatuses } = await this.operations.dryRun({
encodedTransactions,
utxoValidation: utxoValidation || false,
});
const results = dryRunStatuses.map(({ receipts: rawReceipts, status }) => {
const receipts = rawReceipts.map(processGqlReceipt);
return { receipts, dryRunStatus: status };
});
return results;
}
/**
* Estimates the transaction gas and fee based on the provided transaction request.
* @param transactionRequest - The transaction request object.
* @returns An object containing the estimated minimum gas, minimum fee, maximum gas, and maximum fee.
*/
async estimateTxGasAndFee(params: { transactionRequest: TransactionRequest; gasPrice?: BN }) {
const { transactionRequest } = params;
let { gasPrice } = params;
const chainInfo = this.getChain();
const { gasPriceFactor, maxGasPerTx } = this.getGasConfig();
const minGas = transactionRequest.calculateMinGas(chainInfo);
if (!gasPrice) {
gasPrice = await this.estimateGasPrice(10);
}
const minFee = calculateGasFee({
gasPrice: bn(gasPrice),
gas: minGas,
priceFactor: gasPriceFactor,
tip: transactionRequest.tip,
}).add(1);
let gasLimit = bn(0);
// Only Script transactions consume gas
if (transactionRequest.type === TransactionType.Script) {
// If the gasLimit is set to 0, it means we need to estimate it.
gasLimit = transactionRequest.gasLimit;
if (transactionRequest.gasLimit.eq(0)) {
transactionRequest.gasLimit = minGas;
/*
* Adjusting the gasLimit of a transaction (TX) impacts its maxGas.
* Consequently, this affects the maxFee, as it is derived from the maxGas. To accurately estimate the
* gasLimit for a transaction, especially when the exact gas consumption is uncertain (as in an estimation dry-run),
* the following steps are required:
* 1 - Initially, set the gasLimit using the calculated minGas.
* 2 - Based on this initial gasLimit, calculate the maxGas.
* 3 - Get the maximum gas per transaction allowed by the chain, and subtract the previously calculated maxGas from this limit.
* 4 - The result of this subtraction should then be adopted as the new, definitive gasLimit.
* 5 - Recalculate the maxGas with the updated gasLimit. This new maxGas is then used to compute the maxFee.
* 6 - The calculated maxFee represents the safe, estimated cost required to fund the transaction.
*/
transactionRequest.gasLimit = maxGasPerTx.sub(
transactionRequest.calculateMaxGas(chainInfo, minGas)
);
gasLimit = transactionRequest.gasLimit;
}
}
const maxGas = transactionRequest.calculateMaxGas(chainInfo, minGas);
const maxFee = calculateGasFee({
gasPrice: bn(gasPrice),
gas: maxGas,
priceFactor: gasPriceFactor,
tip: transactionRequest.tip,
}).add(1);
return {
minGas,
minFee,
maxGas,
maxFee,
gasPrice,
gasLimit,