-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
base-invocation-scope.ts
254 lines (218 loc) · 8.6 KB
/
base-invocation-scope.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
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { InputValue } from '@fuel-ts/abi-coder';
import type { ContractIdLike } from '@fuel-ts/interfaces';
import { toBigInt } from '@fuel-ts/math';
import type { Provider, CoinQuantity } from '@fuel-ts/providers';
import { transactionRequestify, ScriptTransactionRequest } from '@fuel-ts/providers';
import { MAX_GAS_PER_TX, InputType } from '@fuel-ts/transactions';
import type { ContractCall } from '../../scripts';
import { contractCallScript } from '../../scripts';
import type {
CallOptions,
InvocationScopeLike,
TransactionCostOptions,
TxParams,
} from '../../types';
import { assert } from '../../util';
import type Contract from '../contract';
import { InvocationCallResult, FunctionInvocationResult } from './invocation-results';
function createContractCall(funcScope: InvocationScopeLike): ContractCall {
const { contract, args, forward, func, callParameters } = funcScope.getCallConfig();
const data = contract.interface.encodeFunctionData(func, args as Array<InputValue>);
return {
contractId: contract.id,
data,
assetId: forward?.assetId,
amount: forward?.amount,
gas: callParameters?.gasLimit,
};
}
export class BaseInvocationScope<TReturn = any> {
transactionRequest: ScriptTransactionRequest;
protected contract: Contract;
protected functionInvocationScopes: Array<InvocationScopeLike> = [];
protected txParameters?: TxParams;
protected requiredCoins: CoinQuantity[] = [];
protected isMultiCall: boolean = false;
constructor(contract: Contract, isMultiCall: boolean) {
this.contract = contract;
this.isMultiCall = isMultiCall;
this.transactionRequest = new ScriptTransactionRequest({
gasLimit: MAX_GAS_PER_TX,
});
}
protected get calls() {
return this.functionInvocationScopes.map((funcScope) => createContractCall(funcScope));
}
protected static getCallOptions(options?: CallOptions) {
return { fundTransaction: true, ...options };
}
protected updateScriptRequest() {
const calls = this.calls;
calls.forEach((c) => {
this.transactionRequest.addContract(c.contractId);
});
this.transactionRequest.setScript(contractCallScript, calls);
}
protected getRequiredCoins(): Array<CoinQuantity> {
const assets = this.calls
.map((call) => ({
assetId: String(call.assetId),
amount: toBigInt(call.amount || 0),
}))
.concat(this.transactionRequest.calculateFee())
.filter(({ assetId, amount }) => assetId && amount);
return assets;
}
protected updateRequiredCoins() {
const assets = this.getRequiredCoins();
const reduceForwardCoins = (
requiredCoins: Map<any, CoinQuantity>,
{ assetId, amount }: CoinQuantity
) => {
const currentAmount = requiredCoins.get(assetId)?.amount || 0n;
return requiredCoins.set(assetId, {
assetId: String(assetId),
amount: currentAmount + toBigInt(amount),
});
};
this.requiredCoins = Array.from(
assets.reduce(reduceForwardCoins, new Map<any, CoinQuantity>()).values()
);
}
protected addCall(funcScope: InvocationScopeLike) {
this.addCalls([funcScope]);
return this;
}
protected addCalls(funcScopes: Array<InvocationScopeLike>) {
this.functionInvocationScopes.push(...funcScopes);
this.updateScriptRequest();
this.updateRequiredCoins();
return this;
}
protected async prepareTransaction(options?: CallOptions) {
// Check if gasLimit is less than the
// sum of all call gasLimits
this.checkGasLimitTotal();
// Update request scripts before call
this.updateScriptRequest();
// Add funds required on forwards and to pay gas
const opts = BaseInvocationScope.getCallOptions(options);
if (opts.fundTransaction && this.contract.wallet) {
await this.fundWithRequiredCoins();
}
}
protected checkGasLimitTotal() {
const gasLimitOnCalls = this.calls.reduce(
(total, call) => BigInt(total) + BigInt(call.gas || 0),
0n
);
if (gasLimitOnCalls > this.transactionRequest.gasLimit) {
throw new Error(
"Transaction gasLimit can't be lower than the sum of the forwarded gas of each call"
);
}
}
/**
* Run a valid transaction in dryRun mode and returns useful details about
* gasUsed, gasPrice, bytePrice and transaction estimate fee in native coins.
*/
async getTransactionCost(options?: TransactionCostOptions) {
const provider = (this.contract.wallet?.provider || this.contract.provider) as Provider;
assert(provider, 'Wallet or Provider is required!');
await this.prepareTransaction(options);
const request = transactionRequestify(this.transactionRequest);
request.gasPrice = BigInt(request.gasPrice || options?.gasPrice || 0);
request.bytePrice = BigInt(request.bytePrice || options?.bytePrice || 0);
const txCost = await provider.getTransactionCost(request, options?.tolerance);
return txCost;
}
/**
* Add to the transaction scope the required amount of unspent UTXO's.
*
* Required Amount = forward coins + transfers + gas fee.
*/
async fundWithRequiredCoins() {
// Clean coin inputs before add new coins to the request
this.transactionRequest.inputs = this.transactionRequest.inputs.filter(
(i) => i.type !== InputType.Coin
);
const coins = await this.contract.wallet?.getCoinsToSpend(this.requiredCoins);
this.transactionRequest.addCoins(coins || []);
return this;
}
txParams(txParams: TxParams) {
this.txParameters = txParams;
const request = this.transactionRequest;
request.gasLimit = toBigInt(txParams.gasLimit || request.gasLimit);
request.gasPrice = toBigInt(txParams.gasPrice || request.gasPrice);
request.bytePrice = toBigInt(txParams.bytePrice || request.bytePrice);
request.addVariableOutputs(this.txParameters?.variableOutputs || 0);
return this;
}
addContracts(contracts: Array<ContractIdLike>) {
contracts.forEach((contract) => this.transactionRequest.addContract(contract));
return this;
}
/**
* Submits a transaction to the blockchain.
*
* This is a final action and will spend the coins and change the state of the contract.
* It also means that invalid transactions will throw an error, and consume gas. To avoid this
* running invalid tx and consuming gas try to `simulate` first when possible.
*/
async call<T = TReturn>(options?: CallOptions): Promise<FunctionInvocationResult<T>> {
assert(this.contract.wallet, 'Wallet is required!');
await this.prepareTransaction(options);
const response = await this.contract.wallet.sendTransaction(this.transactionRequest);
return FunctionInvocationResult.build<T>(
this.functionInvocationScopes,
response,
this.isMultiCall
);
}
/**
* Run a valid transaction and return the result without change the chain state.
* This means, all signatures are validated but no UTXO is spent.
*
* This method is useful for validate propose to avoid spending coins on invalid TXs, also
* to estimate the amount of gas that will be required to run the transaction.
*/
async simulate<T = TReturn>(options?: CallOptions): Promise<InvocationCallResult<T>> {
assert(this.contract.wallet, 'Wallet is required!');
await this.prepareTransaction(options);
const result = await this.contract.wallet.simulateTransaction(this.transactionRequest);
return InvocationCallResult.build<T>(this.functionInvocationScopes, result, this.isMultiCall);
}
/**
* Executes a transaction in dry run mode, without UTXO validations.
*
* A transaction in dry run mode can't change the state of the blockchain. It can be useful to access readonly
* methods or just ust get.
* The UTXO validation disable in this case, enables to send invalid inputs to emulate different conditions, of a
* transaction
*/
async dryRun<T = TReturn>(options?: CallOptions): Promise<InvocationCallResult<T>> {
const provider = (this.contract.wallet?.provider || this.contract.provider) as Provider;
assert(provider, 'Wallet or Provider is required!');
this.prepareTransaction(options);
const request = transactionRequestify(this.transactionRequest);
const response = await provider.call(request, {
utxoValidation: false,
});
const result = await InvocationCallResult.build<T>(
this.functionInvocationScopes,
response,
this.isMultiCall
);
return result;
}
/**
* Executes a readonly contract method call.
*
* Under the hood it uses the `dryRun` method.
*/
async get<T = TReturn>(options?: CallOptions): Promise<InvocationCallResult<T>> {
return this.dryRun<T>(options);
}
}