-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathaccount.ts
764 lines (673 loc) · 24.1 KB
/
account.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
import { UTXO_ID_LEN } from '@fuel-ts/abi-coder';
import type { WithAddress } from '@fuel-ts/address';
import { Address } from '@fuel-ts/address';
import { randomBytes } from '@fuel-ts/crypto';
import { ErrorCode, FuelError } from '@fuel-ts/errors';
import type { BigNumberish, BN } from '@fuel-ts/math';
import { bn } from '@fuel-ts/math';
import { InputType } from '@fuel-ts/transactions';
import type { BytesLike } from '@fuel-ts/utils';
import { arrayify, hexlify, isDefined } from '@fuel-ts/utils';
import { clone } from 'ramda';
import type { FuelConnector } from './connectors';
import type {
TransactionRequest,
CoinQuantityLike,
CoinQuantity,
Resource,
ExcludeResourcesOption,
Provider,
ScriptTransactionRequestLike,
TransactionCost,
EstimateTransactionParams,
CursorPaginationArgs,
TransactionRequestLike,
ProviderSendTxParams,
CallResult,
GetCoinsResponse,
GetMessagesResponse,
GetBalancesResponse,
Coin,
TransactionCostParams,
TransactionResponse,
} from './providers';
import {
withdrawScript,
ScriptTransactionRequest,
transactionRequestify,
addAmountToCoinQuantities,
} from './providers';
import {
cacheRequestInputsResourcesFromOwner,
getAssetAmountInRequestInputs,
isRequestInputCoin,
isRequestInputMessageWithoutData,
isRequestInputResource,
} from './providers/transaction-request/helpers';
import { mergeQuantities } from './providers/utils/merge-quantities';
import { AbstractAccount } from './types';
import { assembleTransferToContractScript } from './utils/formatTransferToContractScriptData';
export type TxParamsType = Pick<
ScriptTransactionRequestLike,
'gasLimit' | 'tip' | 'maturity' | 'maxFee' | 'witnessLimit'
>;
export type TransferParams = {
destination: string | Address;
amount: BigNumberish;
assetId: BytesLike;
};
export type ContractTransferParams = {
contractId: string | Address;
amount: BigNumberish;
assetId: BytesLike;
};
export type EstimatedTxParams = Pick<
TransactionCost,
'estimatedPredicates' | 'addedSignatures' | 'requiredQuantities' | 'updateMaxFee' | 'gasPrice'
>;
const MAX_FUNDING_ATTEMPTS = 5;
export type FakeResources = Partial<Coin> & Required<Pick<Coin, 'amount' | 'assetId'>>;
/**
* `Account` provides an abstraction for interacting with accounts or wallets on the network.
*/
export class Account extends AbstractAccount implements WithAddress {
/**
* The address associated with the account.
*/
readonly address: Address;
/**
* The provider used to interact with the network.
*/
protected _provider?: Provider;
/**
* The connector for use with external wallets
*/
protected _connector?: FuelConnector;
/**
* Creates a new Account instance.
*
* @param address - The address of the account.
* @param provider - A Provider instance (optional).
* @param connector - A FuelConnector instance (optional).
*/
constructor(address: string | Address, provider?: Provider, connector?: FuelConnector) {
super();
this._provider = provider;
this._connector = connector;
this.address = Address.fromDynamicInput(address);
}
/**
* The provider used to interact with the network.
*
* @returns A Provider instance.
*
* @throws `FuelError` if the provider is not set.
*/
get provider(): Provider {
if (!this._provider) {
throw new FuelError(ErrorCode.MISSING_PROVIDER, 'Provider not set');
}
return this._provider;
}
/**
* Sets the provider for the account.
*
* @param provider - A Provider instance.
*/
set provider(provider: Provider) {
this._provider = provider;
}
/**
* Changes the provider connection for the account.
*
* @param provider - A Provider instance.
* @returns The updated Provider instance.
*/
connect(provider: Provider): Provider {
this._provider = provider;
return this.provider;
}
/**
* Retrieves resources satisfying the spend query for the account.
*
* @param quantities - Quantities of resources to be obtained.
* @param excludedIds - IDs of resources to be excluded from the query (optional).
* @returns A promise that resolves to an array of Resources.
*/
async getResourcesToSpend(
quantities: CoinQuantityLike[],
excludedIds?: ExcludeResourcesOption
): Promise<Resource[]> {
return this.provider.getResourcesToSpend(this.address, quantities, excludedIds);
}
/**
* Retrieves coins owned by the account.
*
* @param assetId - The asset ID of the coins to retrieve (optional).
* @returns A promise that resolves to an array of Coins.
*/
async getCoins(
assetId?: BytesLike,
paginationArgs?: CursorPaginationArgs
): Promise<GetCoinsResponse> {
return this.provider.getCoins(this.address, assetId, paginationArgs);
}
/**
* Retrieves messages owned by the account.
*
* @returns A promise that resolves to an array of Messages.
*/
async getMessages(paginationArgs?: CursorPaginationArgs): Promise<GetMessagesResponse> {
return this.provider.getMessages(this.address, paginationArgs);
}
/**
* Retrieves the balance of the account for the given asset.
*
* @param assetId - The asset ID to check the balance for (optional).
* @returns A promise that resolves to the balance amount.
*/
async getBalance(assetId?: BytesLike): Promise<BN> {
const assetIdToFetch = assetId ?? (await this.provider.getBaseAssetId());
const amount = await this.provider.getBalance(this.address, assetIdToFetch);
return amount;
}
/**
* Retrieves all the balances for the account.
*
* @returns A promise that resolves to an array of Coins and their quantities.
*/
async getBalances(): Promise<GetBalancesResponse> {
return this.provider.getBalances(this.address);
}
/**
* Funds a transaction request by adding the necessary resources.
*
* @typeParam T - The type of the TransactionRequest.
* @param request - The transaction request to fund.
* @param params - The estimated transaction parameters.
* @returns A promise that resolves to the funded transaction request.
*/
async fund<T extends TransactionRequest>(request: T, params: EstimatedTxParams): Promise<T> {
const { addedSignatures, estimatedPredicates, requiredQuantities, updateMaxFee, gasPrice } =
params;
const fee = request.maxFee;
const baseAssetId = await this.provider.getBaseAssetId();
const requiredInBaseAsset =
requiredQuantities.find((quantity) => quantity.assetId === baseAssetId)?.amount || bn(0);
const requiredQuantitiesWithFee = addAmountToCoinQuantities({
amount: bn(fee),
assetId: baseAssetId,
coinQuantities: requiredQuantities,
});
const quantitiesDict: Record<string, { required: BN; owned: BN }> = {};
requiredQuantitiesWithFee.forEach(({ amount, assetId }) => {
quantitiesDict[assetId] = {
required: amount,
owned: bn(0),
};
});
request.inputs.filter(isRequestInputResource).forEach((input) => {
const isCoin = isRequestInputCoin(input);
const assetId = isCoin ? String(input.assetId) : baseAssetId;
if (quantitiesDict[assetId]) {
quantitiesDict[assetId].owned = quantitiesDict[assetId].owned.add(input.amount);
}
});
let missingQuantities: CoinQuantity[] = [];
Object.entries(quantitiesDict).forEach(([assetId, { owned, required }]) => {
if (owned.lt(required)) {
missingQuantities.push({
assetId,
amount: required.sub(owned),
});
}
});
let needsToBeFunded = missingQuantities.length > 0;
let fundingAttempts = 0;
while (needsToBeFunded && fundingAttempts < MAX_FUNDING_ATTEMPTS) {
const resources = await this.getResourcesToSpend(
missingQuantities,
cacheRequestInputsResourcesFromOwner(request.inputs, this.address)
);
request.addResources(resources);
request.updatePredicateGasUsed(estimatedPredicates);
const requestToReestimate = clone(request);
if (addedSignatures) {
Array.from({ length: addedSignatures }).forEach(() =>
requestToReestimate.addEmptyWitness()
);
}
if (!updateMaxFee) {
needsToBeFunded = false;
break;
}
// Recalculate the fee after adding the resources
const { maxFee: newFee } = await this.provider.estimateTxGasAndFee({
transactionRequest: requestToReestimate,
gasPrice,
});
const totalBaseAssetOnInputs = getAssetAmountInRequestInputs(
request.inputs.filter(isRequestInputResource),
baseAssetId,
baseAssetId
);
// Update the new total as the fee will change after adding new resources
const totalBaseAssetRequiredWithFee = requiredInBaseAsset.add(newFee);
if (totalBaseAssetOnInputs.gt(totalBaseAssetRequiredWithFee)) {
needsToBeFunded = false;
} else {
missingQuantities = [
{
amount: totalBaseAssetRequiredWithFee.sub(totalBaseAssetOnInputs),
assetId: baseAssetId,
},
];
}
fundingAttempts += 1;
}
// If the transaction still needs to be funded after the maximum number of attempts
if (needsToBeFunded) {
throw new FuelError(
ErrorCode.NOT_ENOUGH_FUNDS,
`The account ${this.address} does not have enough base asset funds to cover the transaction execution.`
);
}
await this.provider.validateTransaction(request);
request.updatePredicateGasUsed(estimatedPredicates);
const requestToReestimate = clone(request);
if (addedSignatures) {
Array.from({ length: addedSignatures }).forEach(() => requestToReestimate.addEmptyWitness());
}
if (!updateMaxFee) {
return request;
}
const { maxFee } = await this.provider.estimateTxGasAndFee({
transactionRequest: requestToReestimate,
gasPrice,
});
request.maxFee = maxFee;
return request;
}
/**
* A helper that creates a transfer transaction request and returns it.
*
* @param destination - The address of the destination.
* @param amount - The amount of coins to transfer.
* @param assetId - The asset ID of the coins to transfer (optional).
* @param txParams - The transaction parameters (optional).
* @returns A promise that resolves to the prepared transaction request.
*/
async createTransfer(
destination: string | Address,
amount: BigNumberish,
assetId?: BytesLike,
txParams: TxParamsType = {}
): Promise<ScriptTransactionRequest> {
let request = new ScriptTransactionRequest(txParams);
request = this.addTransfer(request, {
destination,
amount,
assetId: assetId || (await this.provider.getBaseAssetId()),
});
request = await this.estimateAndFundTransaction(request, txParams);
return request;
}
/**
* Transfers coins to a destination address.
*
* @param destination - The address of the destination.
* @param amount - The amount of coins to transfer.
* @param assetId - The asset ID of the coins to transfer (optional).
* @param txParams - The transaction parameters (optional).
* @returns A promise that resolves to the transaction response.
*/
async transfer(
destination: string | Address,
amount: BigNumberish,
assetId?: BytesLike,
txParams: TxParamsType = {}
): Promise<TransactionResponse> {
const request = await this.createTransfer(destination, amount, assetId, txParams);
return this.sendTransaction(request, { estimateTxDependencies: false });
}
/**
* Transfers multiple amounts of a token to multiple recipients.
*
* @param transferParams - An array of `TransferParams` objects representing the transfers to be made.
* @param txParams - Optional transaction parameters.
* @returns A promise that resolves to a `TransactionResponse` object representing the transaction result.
*/
async batchTransfer(
transferParams: TransferParams[],
txParams: TxParamsType = {}
): Promise<TransactionResponse> {
let request = new ScriptTransactionRequest(txParams);
request = this.addBatchTransfer(request, transferParams);
request = await this.estimateAndFundTransaction(request, txParams);
return this.sendTransaction(request, { estimateTxDependencies: false });
}
/**
* Adds a transfer to the given transaction request.
*
* @param request - The script transaction request to add transfers to.
* @param transferParams - The object representing the transfer to be made.
* @returns The updated transaction request with the added transfer.
*/
addTransfer(request: ScriptTransactionRequest, transferParams: TransferParams) {
const { destination, amount, assetId } = transferParams;
this.validateTransferAmount(amount);
request.addCoinOutput(Address.fromAddressOrString(destination), amount, assetId);
return request;
}
/**
* Adds multiple transfers to a script transaction request.
*
* @param request - The script transaction request to add transfers to.
* @param transferParams - An array of `TransferParams` objects representing the transfers to be made.
* @returns The updated script transaction request.
*/
addBatchTransfer(request: ScriptTransactionRequest, transferParams: TransferParams[]) {
transferParams.forEach(({ destination, amount, assetId }) => {
this.addTransfer(request, {
destination,
amount,
assetId,
});
});
return request;
}
/**
* Transfers coins to a contract address.
*
* @param contractId - The address of the contract.
* @param amount - The amount of coins to transfer.
* @param assetId - The asset ID of the coins to transfer (optional).
* @param txParams - The transaction parameters (optional).
* @returns A promise that resolves to the transaction response.
*/
async transferToContract(
contractId: string | Address,
amount: BigNumberish,
assetId: BytesLike,
txParams: TxParamsType = {}
): Promise<TransactionResponse> {
return this.batchTransferToContracts([{ amount, assetId, contractId }], txParams);
}
async batchTransferToContracts(
contractTransferParams: ContractTransferParams[],
txParams: TxParamsType = {}
): Promise<TransactionResponse> {
let request = new ScriptTransactionRequest({
...txParams,
});
const quantities: CoinQuantity[] = [];
const defaultAssetId = await this.provider.getBaseAssetId();
const transferParams = contractTransferParams.map((transferParam) => {
const amount = bn(transferParam.amount);
const contractAddress = Address.fromAddressOrString(transferParam.contractId);
const assetId = transferParam.assetId ? hexlify(transferParam.assetId) : defaultAssetId;
if (amount.lte(0)) {
throw new FuelError(
ErrorCode.INVALID_TRANSFER_AMOUNT,
'Transfer amount must be a positive number.'
);
}
request.addContractInputAndOutput(contractAddress);
quantities.push({ amount, assetId });
return {
amount,
contractId: contractAddress.toB256(),
assetId,
};
});
const { script, scriptData } = await assembleTransferToContractScript(transferParams);
request.script = script;
request.scriptData = scriptData;
request = await this.estimateAndFundTransaction(request, txParams, { quantities });
return this.sendTransaction(request);
}
/**
* Withdraws an amount of the base asset to the base chain.
*
* @param recipient - Address of the recipient on the base chain.
* @param amount - Amount of base asset.
* @param txParams - The transaction parameters (optional).
* @returns A promise that resolves to the transaction response.
*/
async withdrawToBaseLayer(
recipient: string | Address,
amount: BigNumberish,
txParams: TxParamsType = {}
): Promise<TransactionResponse> {
const recipientAddress = Address.fromAddressOrString(recipient);
// add recipient and amount to the transaction script code
const recipientDataArray = arrayify(
'0x'.concat(recipientAddress.toHexString().substring(2).padStart(64, '0'))
);
const amountDataArray = arrayify(
'0x'.concat(bn(amount).toHex().substring(2).padStart(16, '0'))
);
const script = new Uint8Array([
...arrayify(withdrawScript.bytes),
...recipientDataArray,
...amountDataArray,
]);
const params: ScriptTransactionRequestLike = { script, ...txParams };
const baseAssetId = await this.provider.getBaseAssetId();
let request = new ScriptTransactionRequest(params);
const quantities = [{ amount: bn(amount), assetId: baseAssetId }];
const txCost = await this.getTransactionCost(request, { quantities });
request = this.validateGasLimitAndMaxFee({
transactionRequest: request,
gasUsed: txCost.gasUsed,
maxFee: txCost.maxFee,
txParams,
});
await this.fund(request, txCost);
return this.sendTransaction(request);
}
/**
* Returns a transaction cost to enable user
* to set gasLimit and also reserve balance amounts
* on the transaction.
*
* @param transactionRequestLike - The transaction request object.
* @param transactionCostParams - The transaction cost parameters (optional).
*
* @returns A promise that resolves to the transaction cost object.
*/
async getTransactionCost(
transactionRequestLike: TransactionRequestLike,
{ signatureCallback, quantities = [] }: TransactionCostParams = {}
): Promise<TransactionCost> {
const txRequestClone = clone(transactionRequestify(transactionRequestLike));
const baseAssetId = await this.provider.getBaseAssetId();
// Fund with fake UTXOs to avoid not enough funds error
// Getting coin quantities from amounts being transferred
const coinOutputsQuantities = txRequestClone.getCoinOutputsQuantities();
// Combining coin quantities from amounts being transferred and forwarding to contracts
const requiredQuantities = mergeQuantities(coinOutputsQuantities, quantities);
// An arbitrary amount of the base asset is added to cover the transaction fee during dry runs
const transactionFeeForDryRun = [{ assetId: baseAssetId, amount: bn('100000000000000000') }];
const findAssetInput = (assetId: string) =>
txRequestClone.inputs.find((input) => {
if (input.type === InputType.Coin) {
return input.assetId === assetId;
}
// We only consider the message input if it has no data.
// Messages with `data` cannot fund the gas of a transaction.
if (isRequestInputMessageWithoutData(input)) {
return baseAssetId === assetId;
}
return false;
});
const updateAssetInput = (assetId: string, quantity: BN) => {
const assetInput = findAssetInput(assetId);
const usedQuantity = quantity;
if (assetInput && 'amount' in assetInput) {
assetInput.amount = usedQuantity;
} else {
txRequestClone.addResources(
this.generateFakeResources([
{
amount: quantity,
assetId,
},
])
);
}
};
mergeQuantities(requiredQuantities, transactionFeeForDryRun).forEach(({ amount, assetId }) =>
updateAssetInput(assetId, amount)
);
const txCost = await this.provider.getTransactionCost(txRequestClone, {
signatureCallback,
});
return {
...txCost,
requiredQuantities,
};
}
/**
* Sign a message from the account via the connector.
*
* @param message - the message to sign.
* @returns a promise that resolves to the signature.
*
* @hidden
*/
async signMessage(message: string): Promise<string> {
if (!this._connector) {
throw new FuelError(ErrorCode.MISSING_CONNECTOR, 'A connector is required to sign messages.');
}
return this._connector.signMessage(this.address.toString(), message);
}
/**
* Signs a transaction from the account via the connector..
*
* @param transactionRequestLike - The transaction request to sign.
* @returns A promise that resolves to the signature of the transaction.
*/
async signTransaction(transactionRequestLike: TransactionRequestLike): Promise<string> {
if (!this._connector) {
throw new FuelError(
ErrorCode.MISSING_CONNECTOR,
'A connector is required to sign transactions.'
);
}
return this._connector.signTransaction(this.address.toString(), transactionRequestLike);
}
/**
* Sends a transaction to the network.
*
* @param transactionRequestLike - The transaction request to be sent.
* @param sendTransactionParams - The provider send transaction parameters (optional).
* @returns A promise that resolves to the transaction response.
*/
async sendTransaction(
transactionRequestLike: TransactionRequestLike,
{ estimateTxDependencies = true }: ProviderSendTxParams = {}
): Promise<TransactionResponse> {
if (this._connector) {
return this.provider.getTransactionResponse(
await this._connector.sendTransaction(this.address.toString(), transactionRequestLike)
);
}
const transactionRequest = transactionRequestify(transactionRequestLike);
if (estimateTxDependencies) {
await this.provider.estimateTxDependencies(transactionRequest);
}
return this.provider.sendTransaction(transactionRequest, {
estimateTxDependencies: false,
});
}
/**
* Simulates a transaction.
*
* @param transactionRequestLike - The transaction request to be simulated.
* @param estimateTxParams - The estimate transaction params (optional).
* @returns A promise that resolves to the call result.
*/
async simulateTransaction(
transactionRequestLike: TransactionRequestLike,
{ estimateTxDependencies = true }: EstimateTransactionParams = {}
): Promise<CallResult> {
const transactionRequest = transactionRequestify(transactionRequestLike);
if (estimateTxDependencies) {
await this.provider.estimateTxDependencies(transactionRequest);
}
return this.provider.simulate(transactionRequest, { estimateTxDependencies: false });
}
/**
* Generates an array of fake resources based on the provided coins.
*
* @param coins - An array of `FakeResources` objects representing the coins.
* @returns An array of `Resource` objects with generated properties.
*/
generateFakeResources(coins: FakeResources[]): Array<Resource> {
return coins.map((coin) => ({
id: hexlify(randomBytes(UTXO_ID_LEN)),
owner: this.address,
blockCreated: bn(1),
txCreatedIdx: bn(1),
...coin,
}));
}
/** @hidden * */
private validateTransferAmount(amount: BigNumberish) {
if (bn(amount).lte(0)) {
throw new FuelError(
ErrorCode.INVALID_TRANSFER_AMOUNT,
'Transfer amount must be a positive number.'
);
}
}
/** @hidden * */
private async estimateAndFundTransaction(
transactionRequest: ScriptTransactionRequest,
txParams: TxParamsType,
costParams?: TransactionCostParams
) {
let request = transactionRequest;
const txCost = await this.getTransactionCost(request, costParams);
request = this.validateGasLimitAndMaxFee({
transactionRequest: request,
gasUsed: txCost.gasUsed,
maxFee: txCost.maxFee,
txParams,
});
request = await this.fund(request, txCost);
return request;
}
/** @hidden * */
private validateGasLimitAndMaxFee({
gasUsed,
maxFee,
transactionRequest,
txParams: { gasLimit: setGasLimit, maxFee: setMaxFee },
}: {
gasUsed: BN;
maxFee: BN;
transactionRequest: ScriptTransactionRequest;
txParams: Pick<TxParamsType, 'gasLimit' | 'maxFee'>;
}) {
const request = transactionRequestify(transactionRequest) as ScriptTransactionRequest;
if (!isDefined(setGasLimit)) {
request.gasLimit = gasUsed;
} else if (gasUsed.gt(setGasLimit)) {
throw new FuelError(
ErrorCode.GAS_LIMIT_TOO_LOW,
`Gas limit '${setGasLimit}' is lower than the required: '${gasUsed}'.`
);
}
if (!isDefined(setMaxFee)) {
request.maxFee = maxFee;
} else if (maxFee.gt(setMaxFee)) {
throw new FuelError(
ErrorCode.MAX_FEE_TOO_LOW,
`Max fee '${setMaxFee}' is lower than the required: '${maxFee}'.`
);
}
return request;
}
}