/
L1ToL2MessageGasEstimator.ts
367 lines (335 loc) · 11.4 KB
/
L1ToL2MessageGasEstimator.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
import { Provider } from '@ethersproject/abstract-provider'
import { BigNumber, BigNumberish } from '@ethersproject/bignumber'
import { BytesLike, constants, utils } from 'ethers'
import { Inbox__factory } from '../abi/factories/Inbox__factory'
import { NodeInterface__factory } from '../abi/factories/NodeInterface__factory'
import { NODE_INTERFACE_ADDRESS } from '../dataEntities/constants'
import { ArbSdkError } from '../dataEntities/errors'
import { getL2Network } from '../dataEntities/networks'
import {
RetryableData,
RetryableDataTools,
} from '../dataEntities/retryableData'
import { L1ToL2TransactionRequest } from '../dataEntities/transactionRequest'
import { getBaseFee, isDefined } from '../utils/lib'
import { OmitTyped } from '../utils/types'
import {
L1ToL2MessageGasParams,
L1ToL2MessageNoGasParams,
} from './L1ToL2MessageCreator'
/**
* The default amount to increase the maximum submission cost. Submission cost is calculated
* from (call data size * some const * l1 base fee). So we need to provide some leeway for
* base fee increase. Since submission fee is a small amount it isn't too bas for UX to increase
* it by a large amount, and provide better safety.
*/
const DEFAULT_SUBMISSION_FEE_PERCENT_INCREASE = BigNumber.from(300)
/**
* When submitting a retryable we need to estimate what the gas price for it will be when we actually come
* to execute it. Since the l2 price can move due to congestion we should provide some padding here
*/
const DEFAULT_GAS_PRICE_PERCENT_INCREASE = BigNumber.from(200)
/**
* An optional big number percentage increase
*/
export type PercentIncrease = {
/**
* If provided, will override the estimated base
*/
base?: BigNumber
/**
* How much to increase the base by. If not provided system defaults may be used.
*/
percentIncrease?: BigNumber
}
export interface GasOverrides {
gasLimit?: PercentIncrease & {
/**
* Set a minimum max gas
*/
min?: BigNumber
}
maxSubmissionFee?: PercentIncrease
maxFeePerGas?: PercentIncrease
/**
* funds deposited along with the retryable (ie the msg.value that called the inbox)
*/
deposit?: Pick<PercentIncrease, 'base'>
}
const defaultL1ToL2MessageEstimateOptions = {
maxSubmissionFeePercentIncrease: DEFAULT_SUBMISSION_FEE_PERCENT_INCREASE,
// gas limit for l1->l2 messages should be predictable. If it isn't due to the nature
// of the specific transaction, then the caller should provide a 'min' override
gasLimitPercentIncrease: constants.Zero,
maxFeePerGasPercentIncrease: DEFAULT_GAS_PRICE_PERCENT_INCREASE,
}
export class L1ToL2MessageGasEstimator {
constructor(public readonly l2Provider: Provider) {}
private percentIncrease(num: BigNumber, increase: BigNumber): BigNumber {
return num.add(num.mul(increase).div(100))
}
private applySubmissionPriceDefaults(
maxSubmissionFeeOptions?: PercentIncrease
) {
return {
base: maxSubmissionFeeOptions?.base,
percentIncrease:
maxSubmissionFeeOptions?.percentIncrease ||
defaultL1ToL2MessageEstimateOptions.maxSubmissionFeePercentIncrease,
}
}
private applyMaxFeePerGasDefaults(maxFeePerGasOptions?: PercentIncrease) {
return {
base: maxFeePerGasOptions?.base,
percentIncrease:
maxFeePerGasOptions?.percentIncrease ||
defaultL1ToL2MessageEstimateOptions.maxFeePerGasPercentIncrease,
}
}
private applyGasLimitDefaults(
gasLimitDefaults?: PercentIncrease & { min?: BigNumber }
) {
return {
base: gasLimitDefaults?.base,
percentIncrease:
gasLimitDefaults?.percentIncrease ||
defaultL1ToL2MessageEstimateOptions.gasLimitPercentIncrease,
min: gasLimitDefaults?.min || constants.Zero,
}
}
/**
* Return the fee, in wei, of submitting a new retryable tx with a given calldata size.
* @param l1Provider
* @param l1BaseFee
* @param callDataSize
* @param options
* @returns
*/
public async estimateSubmissionFee(
l1Provider: Provider,
l1BaseFee: BigNumber,
callDataSize: BigNumber | number,
options?: PercentIncrease
): Promise<L1ToL2MessageGasParams['maxSubmissionCost']> {
const defaultedOptions = this.applySubmissionPriceDefaults(options)
const network = await getL2Network(this.l2Provider)
const inbox = Inbox__factory.connect(network.ethBridge.inbox, l1Provider)
return this.percentIncrease(
defaultedOptions.base ||
(await inbox.calculateRetryableSubmissionFee(callDataSize, l1BaseFee)),
defaultedOptions.percentIncrease
)
}
/**
* Estimate the amount of L2 gas required for putting the transaction in the L2 inbox, and executing it.
* @param retryableData object containing retryable ticket data
* @param senderDeposit we dont know how much gas the transaction will use when executing
* so by default we supply a dummy amount of call value that will definately be more than we need
* @returns
*/
public async estimateRetryableTicketGasLimit(
{
from,
to,
l2CallValue: l2CallValue,
excessFeeRefundAddress,
callValueRefundAddress,
data,
}: L1ToL2MessageNoGasParams,
senderDeposit: BigNumber = utils.parseEther('1').add(l2CallValue)
): Promise<L1ToL2MessageGasParams['gasLimit']> {
const nodeInterface = NodeInterface__factory.connect(
NODE_INTERFACE_ADDRESS,
this.l2Provider
)
return await nodeInterface.estimateGas.estimateRetryableTicket(
from,
senderDeposit,
to,
l2CallValue,
excessFeeRefundAddress,
callValueRefundAddress,
data
)
}
/**
* Provides an estimate for the L2 maxFeePerGas, adding some margin to allow for gas price variation
* @param options
* @returns
*/
public async estimateMaxFeePerGas(
options?: PercentIncrease
): Promise<L1ToL2MessageGasParams['maxFeePerGas']> {
const maxFeePerGasDefaults = this.applyMaxFeePerGasDefaults(options)
// estimate the l2 gas price
return this.percentIncrease(
maxFeePerGasDefaults.base || (await this.l2Provider.getGasPrice()),
maxFeePerGasDefaults.percentIncrease
)
}
/**
* Checks if the estimate is valid when compared with a new one
* @param estimates Original estimate
* @param reEstimates Estimate to compare against
* @returns
*/
public static async isValid(
estimates: L1ToL2MessageGasParams,
reEstimates: L1ToL2MessageGasParams
): Promise<boolean> {
// L2 base fee and minimum submission cost which affect the success of the tx
return (
estimates.maxFeePerGas.gte(reEstimates.maxFeePerGas) &&
estimates.maxSubmissionCost.gte(reEstimates.maxSubmissionCost)
)
}
/**
* Get gas limit, gas price and submission price estimates for sending an L1->L2 message
* @param retryableData Data of retryable ticket transaction
* @param l1BaseFee Current l1 base fee
* @param l1Provider
* @param options
* @returns
*/
public async estimateAll(
retryableEstimateData: L1ToL2MessageNoGasParams,
l1BaseFee: BigNumber,
l1Provider: Provider,
options?: GasOverrides
): Promise<L1ToL2MessageGasParams> {
const { data } = retryableEstimateData
const gasLimitDefaults = this.applyGasLimitDefaults(options?.gasLimit)
// estimate the l1 gas price
const maxFeePerGasPromise = this.estimateMaxFeePerGas(options?.maxFeePerGas)
// estimate the submission fee
const maxSubmissionFeePromise = this.estimateSubmissionFee(
l1Provider,
l1BaseFee,
utils.hexDataLength(data),
options?.maxSubmissionFee
)
// estimate the gas limit
const calculatedGasLimit = this.percentIncrease(
gasLimitDefaults.base ||
(await this.estimateRetryableTicketGasLimit(
retryableEstimateData,
options?.deposit?.base
)),
gasLimitDefaults.percentIncrease
)
const [maxFeePerGas, maxSubmissionFee] = await Promise.all([
maxFeePerGasPromise,
maxSubmissionFeePromise,
])
// always ensure the max gas is greater than the min - this can be useful if we know that
// gas estimation is bad for the provided transaction
const gasLimit = calculatedGasLimit.gt(gasLimitDefaults.min)
? calculatedGasLimit
: gasLimitDefaults.min
const deposit =
options?.deposit?.base ||
gasLimit
.mul(maxFeePerGas)
.add(maxSubmissionFee)
.add(retryableEstimateData.l2CallValue)
return {
gasLimit,
maxSubmissionCost: maxSubmissionFee,
maxFeePerGas,
deposit,
}
}
/**
* Transactions that make an L1->L2 message need to estimate L2 gas parameters
* This function does that, and populates those parameters into a transaction request
* @param dataFunc
* @param l1Provider
* @param gasOverrides
* @returns
*/
public async populateFunctionParams(
/**
* Function that will internally make an L1->L2 transaction
* Will initially be called with dummy values to trigger a special revert containing
* the real params. Then called again with the real params to form the final data to be submitted
*/
dataFunc: (
params: OmitTyped<L1ToL2MessageGasParams, 'deposit'>
) => L1ToL2TransactionRequest['txRequest'],
l1Provider: Provider,
gasOverrides?: GasOverrides
): Promise<{
estimates: L1ToL2MessageGasParams
retryable: RetryableData
data: BytesLike
to: string
value: BigNumberish
}> {
// get function data that should trigger a retryable data error
const {
data: nullData,
to,
value,
from,
} = dataFunc({
gasLimit: RetryableDataTools.ErrorTriggeringParams.gasLimit,
maxFeePerGas: RetryableDataTools.ErrorTriggeringParams.maxFeePerGas,
maxSubmissionCost: BigNumber.from(1),
})
let retryable: RetryableData | null
try {
// get retryable data from the null call
const res = await l1Provider.call({
to: to,
data: nullData,
value: value,
from: from,
})
retryable = RetryableDataTools.tryParseError(res)
if (!isDefined(retryable)) {
throw new ArbSdkError(`No retryable data found in error: ${res}`)
}
} catch (err) {
// ethersjs currently doesnt throw for custom solidity errors, so we shouldn't end up here
// however we try to catch and parse the error anyway in case ethersjs changes
// behaviour and we dont pick up on it
retryable = RetryableDataTools.tryParseError(err as Error)
if (!isDefined(retryable)) {
throw new ArbSdkError('No retryable data found in error', err as Error)
}
}
// use retryable data to get gas estimates
// const gasEstimator = new L1ToL2MessageGasEstimator(l2Provider)
const baseFee = await getBaseFee(l1Provider)
const estimates = await this.estimateAll(
{
from: retryable.from,
to: retryable.to,
data: retryable.data,
l2CallValue: retryable.l2CallValue,
excessFeeRefundAddress: retryable.excessFeeRefundAddress,
callValueRefundAddress: retryable.callValueRefundAddress,
},
baseFee,
l1Provider,
gasOverrides
)
// form the real data for the transaction
const {
data: realData,
to: realTo,
value: realValue,
} = dataFunc({
gasLimit: estimates.gasLimit,
maxFeePerGas: estimates.maxFeePerGas,
maxSubmissionCost: estimates.maxSubmissionCost,
})
return {
estimates,
retryable,
data: realData,
to: realTo,
value: realValue,
}
}
}