-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathprovider.ts
1295 lines (1168 loc) · 38.8 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 { AbstractAddress } from '@fuel-ts/interfaces';
import type { BN } from '@fuel-ts/math';
import { bn, max } from '@fuel-ts/math';
import type { Transaction } from '@fuel-ts/transactions';
import {
InputType,
TransactionType,
InputMessageCoder,
TransactionCoder,
} from '@fuel-ts/transactions';
import { checkFuelCoreVersionCompatibility } from '@fuel-ts/versions';
import type { BytesLike } from 'ethers';
import { getBytesCopy, hexlify, Network } from 'ethers';
import { GraphQLClient } from 'graphql-request';
import { clone } from 'ramda';
import { getSdk as getOperationsSdk } from './__generated__/operations';
import type {
GqlChainInfoFragmentFragment,
GqlGasCosts,
GqlGetBlocksQueryVariables,
GqlPeerInfo,
} from './__generated__/operations';
import type { Coin } from './coin';
import type { CoinQuantity, CoinQuantityLike } from './coin-quantity';
import { coinQuantityfy } from './coin-quantity';
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,
} from './transaction-request';
import { transactionRequestify, ScriptTransactionRequest } from './transaction-request';
import type { TransactionResultReceipt } from './transaction-response';
import { TransactionResponse } from './transaction-response';
import { processGqlReceipt } from './transaction-summary/receipt';
import {
calculatePriceWithFactor,
fromUnixToTai64,
getGasUsedFromReceipts,
getReceiptsWithMissingData,
} from './utils';
import { mergeQuantities } from './utils/merge-quantities';
const MAX_RETRIES = 10;
export type CallResult = {
receipts: TransactionResultReceipt[];
};
/**
* 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 ConsensusParameters = {
contractMaxSize: BN;
maxInputs: BN;
maxOutputs: BN;
maxWitnesses: BN;
maxGasPerTx: BN;
maxScriptLength: BN;
maxScriptDataLength: BN;
maxStorageSlots: BN;
maxPredicateLength: BN;
maxPredicateDataLength: BN;
maxGasPerPredicate: BN;
gasPriceFactor: BN;
gasPerByte: BN;
maxMessageDataLength: BN;
chainId: BN;
gasCosts: GqlGasCosts;
};
/**
* Chain information
*/
export type ChainInfo = {
name: string;
baseChainHeight: BN;
consensusParameters: ConsensusParameters;
gasCosts: GqlGasCosts;
latestBlock: {
id: string;
height: BN;
time: string;
transactions: Array<{ id: string }>;
};
};
/**
* Node information
*/
export type NodeInfo = {
utxoValidation: boolean;
vmBacktrace: boolean;
minGasPrice: BN;
maxTx: BN;
maxDepth: BN;
nodeVersion: string;
peers: GqlPeerInfo[];
};
export type NodeInfoAndConsensusParameters = {
minGasPrice: BN;
nodeVersion: string;
gasPerByte: BN;
gasPriceFactor: BN;
maxGasPerTx: BN;
};
// #region cost-estimation-1
export type TransactionCost = {
requiredQuantities: CoinQuantity[];
receipts: TransactionResultReceipt[];
minGasPrice: BN;
gasPrice: BN;
minGas: BN;
maxGas: BN;
gasUsed: BN;
minFee: BN;
maxFee: BN;
usedFee: BN;
};
// #endregion cost-estimation-1
const processGqlChain = (chain: GqlChainInfoFragmentFragment): ChainInfo => {
const { name, daHeight, consensusParameters, latestBlock } = chain;
const { contractParams, feeParams, predicateParams, scriptParams, txParams, gasCosts } =
consensusParameters;
return {
name,
baseChainHeight: bn(daHeight),
consensusParameters: {
contractMaxSize: bn(contractParams.contractMaxSize),
maxInputs: bn(txParams.maxInputs),
maxOutputs: bn(txParams.maxOutputs),
maxWitnesses: bn(txParams.maxWitnesses),
maxGasPerTx: bn(txParams.maxGasPerTx),
maxScriptLength: bn(scriptParams.maxScriptLength),
maxScriptDataLength: bn(scriptParams.maxScriptDataLength),
maxStorageSlots: bn(contractParams.maxStorageSlots),
maxPredicateLength: bn(predicateParams.maxPredicateLength),
maxPredicateDataLength: bn(predicateParams.maxPredicateDataLength),
maxGasPerPredicate: bn(predicateParams.maxGasPerPredicate),
gasPriceFactor: bn(feeParams.gasPriceFactor),
gasPerByte: bn(feeParams.gasPerByte),
maxMessageDataLength: bn(predicateParams.maxMessageDataLength),
chainId: bn(consensusParameters.chainId),
gasCosts,
},
gasCosts,
latestBlock: {
id: latestBlock.id,
height: bn(latestBlock.header.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;
};
export type FetchRequestOptions = {
method: 'POST';
headers: { [key: string]: string };
body: string;
};
/*
* Provider initialization options
*/
export type ProviderOptions = {
fetch?: (url: string, options: FetchRequestOptions) => Promise<unknown>;
cacheUtxo?: number;
};
/**
* UTXO Validation Param
*/
export type UTXOValidationParams = {
utxoValidation?: boolean;
};
/**
* Transaction estimation Param
*/
export type EstimateTransactionParams = {
estimateTxDependencies?: boolean;
};
export type EstimatePredicateParams = {
estimatePredicates?: boolean;
};
export type TransactionCostParams = EstimateTransactionParams & EstimatePredicateParams;
/**
* Provider Call transaction params
*/
export type ProviderCallParams = UTXOValidationParams & EstimateTransactionParams;
/**
* Provider Send transaction params
*/
export type ProviderSendTxParams = EstimateTransactionParams;
/**
* 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 = {};
/**
* 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,
public options: ProviderOptions = {}
) {
this.operations = this.createOperations(url, options);
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 { minGasPrice } = this.getNode();
const { maxGasPerTx, maxGasPerPredicate, gasPriceFactor, gasPerByte, gasCosts } =
this.getChain().consensusParameters;
return {
minGasPrice,
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.operations = this.createOperations(url, options ?? this.options);
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) {
throw new FuelError(
FuelError.CODES.UNSUPPORTED_FUEL_CLIENT_VERSION,
`Fuel client version: ${nodeInfo.nodeVersion}, Supported version: ${supportedVersion}`
);
}
}
/**
* Create GraphQL client and set operations.
*
* @param url - The URL of the Fuel node
* @param options - Additional options for the provider
* @returns The operation SDK object
*/
private createOperations(url: string, options: ProviderOptions = {}) {
this.url = url;
const gqlClient = new GraphQLClient(url, options.fetch ? { fetch: options.fetch } : undefined);
return getOperationsSdk(gqlClient);
}
/**
* 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;
}
/**
* @hidden
*
* Returns the network configuration of the connected Fuel node.
*
* @returns A promise that resolves to the network configuration object
*/
async getNetwork(): Promise<Network> {
const {
name,
consensusParameters: { chainId },
} = await this.getChain();
const network = new Network(name, chainId.toNumber());
return Promise.resolve(network);
}
/**
* 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.header.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),
minGasPrice: bn(nodeInfo.minGasPrice),
nodeVersion: nodeInfo.nodeVersion,
utxoValidation: nodeInfo.utxoValidation,
vmBacktrace: nodeInfo.vmBacktrace,
peers: nodeInfo.peers,
};
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();
}
/**
* @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 }: 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());
const { gasUsed, minGasPrice } = await this.getTransactionCost(transactionRequest, [], {
estimateTxDependencies: false,
estimatePredicates: false,
});
if (bn(minGasPrice).gt(bn(transactionRequest.gasPrice))) {
throw new FuelError(
ErrorCode.GAS_PRICE_TOO_LOW,
`Gas price '${transactionRequest.gasPrice}' is lower than the required: '${minGasPrice}'.`
);
}
const isScriptTransaction = transactionRequest.type === TransactionType.Script;
if (isScriptTransaction && bn(gasUsed).gt(bn(transactionRequest.gasLimit))) {
throw new FuelError(
ErrorCode.GAS_LIMIT_TOO_LOW,
`Gas limit '${transactionRequest.gasLimit}' is lower than the required: '${gasUsed}'.`
);
}
const {
submit: { id: transactionId },
} = await this.operations.submit({ encodedTransaction });
const response = new TransactionResponse(transactionId, this);
return response;
}
/**
* 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) {
await this.estimateTxDependencies(transactionRequest);
}
const encodedTransaction = hexlify(transactionRequest.toTransactionBytes());
const { dryRun: gqlReceipts } = await this.operations.dryRun({
encodedTransaction,
utxoValidation: utxoValidation || false,
});
const receipts = gqlReceipts.map(processGqlReceipt);
return {
receipts,
};
}
/**
* 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 encodedTransaction = hexlify(transactionRequest.toTransactionBytes());
const response = await this.operations.estimatePredicates({
encodedTransaction,
});
const estimatedTransaction = transactionRequest;
const [decodedTransaction] = new TransactionCoder().decode(
getBytesCopy(response.estimatePredicates.rawPayload),
0
);
if (decodedTransaction.inputs) {
decodedTransaction.inputs.forEach((input, index) => {
if ('predicate' in input && input.predicateGasUsed.gt(0)) {
(<CoinTransactionRequestInput>estimatedTransaction.inputs[index]).predicateGasUsed =
input.predicateGasUsed;
}
});
}
return estimatedTransaction;
}
/**
* Will dryRun a transaction and check for missing dependencies.
*
* If there are missing variable outputs,
* `addVariableOutputs` is called on the transaction.
*
* @privateRemarks
* TODO: Investigate support for missing contract IDs
* TODO: Add support for missing output messages
*
* @param transactionRequest - The transaction request object.
* @returns A promise.
*/
async estimateTxDependencies(transactionRequest: TransactionRequest): Promise<void> {
let missingOutputVariableCount = 0;
let missingOutputContractIdsCount = 0;
let tries = 0;
if (transactionRequest.type === TransactionType.Create) {
return;
}
let txRequest = transactionRequest;
if (txRequest.hasPredicateInput()) {
txRequest = (await this.estimatePredicates(txRequest)) as ScriptTransactionRequest;
}
do {
const { dryRun: gqlReceipts } = await this.operations.dryRun({
encodedTransaction: hexlify(txRequest.toTransactionBytes()),
utxoValidation: false,
});
const receipts = gqlReceipts.map(processGqlReceipt);
const { missingOutputVariables, missingOutputContractIds } =
getReceiptsWithMissingData(receipts);
missingOutputVariableCount = missingOutputVariables.length;
missingOutputContractIdsCount = missingOutputContractIds.length;
if (missingOutputVariableCount === 0 && missingOutputContractIdsCount === 0) {
return;
}
if (txRequest instanceof ScriptTransactionRequest) {
txRequest.addVariableOutputs(missingOutputVariableCount);
missingOutputContractIds.forEach(({ contractId }) =>
txRequest.addContractInputAndOutput(Address.fromString(contractId))
);
}
tries += 1;
} while (tries < MAX_RETRIES);
}
/**
* Executes a signed transaction without applying the states changes
* on 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.
* @returns A promise that resolves to the call result object.
*/
async simulate(
transactionRequestLike: TransactionRequestLike,
{ estimateTxDependencies = true }: EstimateTransactionParams = {}
): Promise<CallResult> {
const transactionRequest = transactionRequestify(transactionRequestLike);
if (estimateTxDependencies) {
await this.estimateTxDependencies(transactionRequest);
}
const encodedTransaction = hexlify(transactionRequest.toTransactionBytes());
const { dryRun: gqlReceipts } = await this.operations.dryRun({
encodedTransaction,
utxoValidation: true,
});
const receipts = gqlReceipts.map(processGqlReceipt);
return {
receipts,
};
}
/**
* Returns a transaction cost to enable user
* to set gasLimit and also reserve balance amounts
* on the the transaction.
*
* @privateRemarks
* The tolerance is add on top of the gasUsed calculated
* from the node, this create a safe margin costs like
* change states on transfer that don't occur on the dryRun
* transaction. The default value is 0.2 or 20%
*
* @param transactionRequestLike - The transaction request object.
* @param tolerance - The tolerance to add on top of the gasUsed.
* @returns A promise that resolves to the transaction cost object.
*/
async getTransactionCost(
transactionRequestLike: TransactionRequestLike,
forwardingQuantities: CoinQuantity[] = [],
{ estimateTxDependencies = true, estimatePredicates = true }: TransactionCostParams = {}
): Promise<TransactionCost> {
const transactionRequest = transactionRequestify(clone(transactionRequestLike));
const chainInfo = this.getChain();
const { gasPriceFactor, minGasPrice, maxGasPerTx } = this.getGasConfig();
const gasPrice = max(transactionRequest.gasPrice, minGasPrice);
const isScriptTransaction = transactionRequest.type === TransactionType.Script;
/**
* Estimate predicates gasUsed
*/
if (transactionRequest.hasPredicateInput() && estimatePredicates) {
// Remove gasLimit to avoid gasLimit when estimating predicates
if (isScriptTransaction) {
transactionRequest.gasLimit = bn(0);
}
await this.estimatePredicates(transactionRequest);
}
/**
* Calculate minGas and maxGas based on the real transaction
*/
const minGas = transactionRequest.calculateMinGas(chainInfo);
const maxGas = transactionRequest.calculateMaxGas(chainInfo, minGas);
/**
* Fund with fake UTXOs to avoid not enough funds error
*/
// Getting coin quantities from amounts being transferred
const coinOutputsQuantities = transactionRequest.getCoinOutputsQuantities();
// Combining coin quantities from amounts being transferred and forwarding to contracts
const allQuantities = mergeQuantities(coinOutputsQuantities, forwardingQuantities);
// Funding transaction with fake utxos
transactionRequest.fundWithFakeUtxos(allQuantities);
/**
* Estimate gasUsed for script transactions
*/
let gasUsed = minGas;
let receipts: TransactionResultReceipt[] = [];
// Transactions of type Create does not consume any gas so we can the dryRun
if (isScriptTransaction) {
/**
* Setting the gasPrice to 0 on a dryRun will result in no fees being charged.
* This simplifies the funding with fake utxos, since the coin quantities required
* will only be amounts being transferred (coin outputs) and amounts being forwarded
* to contract calls.
*/
// Calculate the gasLimit again as we insert a fake UTXO and signer
transactionRequest.gasPrice = bn(0);
transactionRequest.gasLimit = bn(maxGasPerTx.sub(maxGas).toNumber() * 0.9);
// Executing dryRun with fake utxos to get gasUsed
const result = await this.call(transactionRequest, {
estimateTxDependencies,
});
receipts = result.receipts;
gasUsed = getGasUsedFromReceipts(receipts);
} else {
// For CreateTransaction the gasUsed is going to be the minGas
gasUsed = minGas;
}
const usedFee = calculatePriceWithFactor(
gasUsed,
gasPrice,
gasPriceFactor
).normalizeZeroToOne();
const minFee = calculatePriceWithFactor(minGas, gasPrice, gasPriceFactor).normalizeZeroToOne();
const maxFee = calculatePriceWithFactor(maxGas, gasPrice, gasPriceFactor).normalizeZeroToOne();
return {
requiredQuantities: allQuantities,
receipts,
gasUsed,
minGasPrice,
gasPrice,
minGas,
maxGas,
usedFee,
minFee,
maxFee,
};
}
async getResourcesForTransaction(
owner: AbstractAddress,
transactionRequestLike: TransactionRequestLike,
forwardingQuantities: CoinQuantity[] = []
) {
const transactionRequest = transactionRequestify(clone(transactionRequestLike));
const transactionCost = await this.getTransactionCost(transactionRequest, forwardingQuantities);
// Add the required resources to the transaction from the owner
transactionRequest.addResources(
await this.getResourcesToSpend(owner, transactionCost.requiredQuantities)
);
// Refetch transaction costs with the new resources
// TODO: we could find a way to avoid fetch estimatePredicates again, by returning the transaction or
// returning a specific gasUsed by the predicate.
// Also for the dryRun we could have the same issue as we are going to run twice the dryRun and the
// estimateTxDependencies as we don't have access to the transaction, maybe returning the transaction would
// be better.
const { requiredQuantities, ...txCost } = await this.getTransactionCost(
transactionRequest,
forwardingQuantities
);
const resources = await this.getResourcesToSpend(owner, requiredQuantities);
return {
resources,
requiredQuantities,
...txCost,
};
}
/**
* Returns coins for the given owner.
*/
async getCoins(
/** The address to get coins for */
owner: AbstractAddress,
/** The asset ID of coins to get */
assetId?: BytesLike,
/** Pagination arguments */
paginationArgs?: CursorPaginationArgs
): Promise<Coin[]> {
const result = await this.operations.getCoins({
first: 10,
...paginationArgs,
filter: { owner: owner.toB256(), assetId: assetId && hexlify(assetId) },
});
const coins = result.coins.edges.map((edge) => edge.node);
return coins.map((coin) => ({
id: coin.utxoId,
assetId: coin.assetId,
amount: bn(coin.amount),
owner: Address.fromAddressOrString(coin.owner),
maturity: bn(coin.maturity).toNumber(),
blockCreated: bn(coin.blockCreated),
txCreatedIdx: bn(coin.txCreatedIdx),
}));
}
/**
* Returns resources for the given owner satisfying the spend query.
*
* @param owner - The address to get resources for.
* @param quantities - The quantities to get.
* @param excludedIds - IDs of excluded resources from the selection.
* @returns A promise that resolves to the resources.
*/
async getResourcesToSpend(
/** The address to get coins for */
owner: AbstractAddress,
/** The quantities to get */
quantities: CoinQuantityLike[],
/** IDs of excluded resources from the selection. */
excludedIds?: ExcludeResourcesOption
): Promise<Resource[]> {
const excludeInput = {
messages: excludedIds?.messages?.map((id) => hexlify(id)) || [],
utxos: excludedIds?.utxos?.map((id) => hexlify(id)) || [],
};
if (this.cache) {
const uniqueUtxos = new Set(
excludeInput.utxos.concat(this.cache?.getActiveData().map((id) => hexlify(id)))
);
excludeInput.utxos = Array.from(uniqueUtxos);
}
const coinsQuery = {
owner: owner.toB256(),
queryPerAsset: quantities
.map(coinQuantityfy)
.map(({ assetId, amount, max: maxPerAsset }) => ({
assetId: hexlify(assetId),
amount: amount.toString(10),
max: maxPerAsset ? maxPerAsset.toString(10) : undefined,
})),
excludedIds: excludeInput,
};
const result = await this.operations.getCoinsToSpend(coinsQuery);
const coins = result.coinsToSpend
.flat()
.map((coin) => {
switch (coin.__typename) {
case 'MessageCoin':
return {
amount: bn(coin.amount),
assetId: coin.assetId,
daHeight: bn(coin.daHeight),
sender: Address.fromAddressOrString(coin.sender),
recipient: Address.fromAddressOrString(coin.recipient),
nonce: coin.nonce,
} as MessageCoin;
case 'Coin':
return {
id: coin.utxoId,
amount: bn(coin.amount),
assetId: coin.assetId,
owner: Address.fromAddressOrString(coin.owner),
maturity: bn(coin.maturity).toNumber(),
blockCreated: bn(coin.blockCreated),
txCreatedIdx: bn(coin.txCreatedIdx),
} as Coin;
default:
return null;
}
})
.filter((v) => !!v) as Array<Resource>;
return coins;
}
/**
* Returns block matching the given ID or height.
*
* @param idOrHeight - ID or height of the block.
* @returns A promise that resolves to the block.
*/
async getBlock(
/** ID or height of the block */
idOrHeight: string | number | 'latest'
): Promise<Block | null> {
let variables;
if (typeof idOrHeight === 'number') {
variables = { height: bn(idOrHeight).toString(10) };
} else if (idOrHeight === 'latest') {
variables = { height: (await this.getBlockNumber()).toString(10) };
} else if (idOrHeight.length === 66) {
variables = { blockId: idOrHeight };
} else {
variables = { blockId: bn(idOrHeight).toString(10) };
}
const { block } = await this.operations.getBlock(variables);
if (!block) {
return null;
}
return {
id: block.id,
height: bn(block.header.height),
time: block.header.time,
transactionIds: block.transactions.map((tx) => tx.id),
};
}
/**
* Returns all the blocks matching the given parameters.
*
* @param params - The parameters to query blocks.
* @returns A promise that resolves to the blocks.
*/
async getBlocks(params: GqlGetBlocksQueryVariables): Promise<Block[]> {
const { blocks: fetchedData } = await this.operations.getBlocks(params);
const blocks: Block[] = fetchedData.edges.map(({ node: block }) => ({
id: block.id,
height: bn(block.header.height),
time: block.header.time,
transactionIds: block.transactions.map((tx) => tx.id),
}));
return blocks;
}
/**
* Returns block matching the given ID or type, including transaction data.
*
* @param idOrHeight - ID or height of the block.
* @returns A promise that resolves to the block.
*/
async getBlockWithTransactions(
/** ID or height of the block */
idOrHeight: string | number | 'latest'
): Promise<(Block & { transactions: Transaction[] }) | null> {
let variables;
if (typeof idOrHeight === 'number') {
variables = { blockHeight: bn(idOrHeight).toString(10) };
} else if (idOrHeight === 'latest') {
variables = { blockHeight: (await this.getBlockNumber()).toString() };
} else {
variables = { blockId: idOrHeight };