-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathcommon.ts
433 lines (405 loc) · 14.8 KB
/
common.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
import assert from "assert";
import Decimal from "decimal.js";
import { ethers, PopulatedTransaction, providers, VoidSigner } from "ethers";
import { getGasPriceEstimate } from "../gasPriceOracle";
import { TypedMessage } from "../interfaces/TypedData";
import { BigNumber, BigNumberish, BN, formatUnits, parseUnits, toBN } from "./BigNumberUtils";
import { ConvertDecimals } from "./FormattingUtils";
import { chainIsOPStack } from "./NetworkUtils";
import { Address, createPublicClient, Hex, http, Transport } from "viem";
import * as chains from "viem/chains";
import { publicActionsL2 } from "viem/op-stack";
import { estimateGas } from "viem/linea";
import { getPublicClient } from "../gasPriceOracle/util";
export type Decimalish = string | number | Decimal;
export const AddressZero = ethers.constants.AddressZero;
export const MAX_BIG_INT = BigNumber.from(Number.MAX_SAFE_INTEGER.toString());
/**
* toBNWei.
*
* @param {BigNumberish} num
* @param {number} decimals
* @returns {BN}
*/
export const toBNWei = (num: BigNumberish, decimals?: number): BN => parseUnits(num.toString(), decimals);
/**
* fromWei.
*
* @param {BigNumberish} num
* @param {number} decimals
* @returns {string}
*/
export const fromWei = (num: BigNumberish, decimals?: number): string => formatUnits(num.toString(), decimals);
/**
* min.
*
* @param {BigNumberish} a
* @param {BigNumberish} b
* @returns {BN}
*/
export function min(a: BigNumberish, b: BigNumberish): BN {
const bna = toBN(a);
const bnb = toBN(b);
return bna.lte(bnb) ? bna : bnb;
}
/**
* max.
*
* @param {BigNumberish} a
* @param {BigNumberish} b
* @returns {BN}
*/
export function max(a: BigNumberish, b: BigNumberish): BN {
const bna = toBN(a);
const bnb = toBN(b);
return bna.gte(bnb) ? bna : bnb;
}
export const fixedPointAdjustment = toBNWei("1");
/**
* Convert an amount of native gas token into a token given price and token decimals.
*
* @param {BigNumberish} fromAmount - Amount of native gas token to convert.
* @param {string | number} [ price=1 ] - The price as native gas token per token, ie how much native gas token can 1 token buy.
* @param {} [ toDecimals=18 ] - Number of decimals for the token currency.
* @param {} [ nativeDecimals=18 ] - Number of decimals for the native token currency.
* @returns {string} The number of tokens denominated in token decimals in the smallest unit (wei).
*/
export function nativeToToken(
fromAmount: BigNumberish,
price: string | number = 1,
toDecimals = 18,
nativeDecimals = 18
): string {
const priceWei = toBNWei(price);
const toAmount = toBNWei(fromAmount).div(priceWei);
return ConvertDecimals(nativeDecimals, toDecimals)(toAmount).toString();
}
/**
* Convert a gas amount and gas price to wei.
*
* @param {number} gas - gas amount.
* @param {BigNumberish} gasPrice - gas price in gwei.
* @returns {BigNumber} - total fees in wei.
*/
export const gasCost = (gas: BigNumberish, gasPrice: BigNumberish): BigNumber => {
return BigNumber.from(gas).mul(gasPrice);
};
/**
* getGasFees. Low level pure function call to calculate gas fees.
*
* @param {number} gas - The gast cost for transfer, use constants defined in file.
* @param {BigNumberish} gasPrice - Estimated gas price in wei.
* @param {string | number} [price = 1] - The price of the token in native gas token, how much native gas token can 1 token buy.
* @param {number} [decimals=18] - Number of decimals of token.
* @returns {string} - The value of fees native to the token provided, in its smallest unit.
*/
export function calculateGasFees(
gas: number,
gasPrice: BigNumberish,
price: string | number = 1,
decimals = 18
): string {
const amountNative = gasCost(gas, gasPrice);
return nativeToToken(amountNative, price, decimals);
}
/**
* percent.
*
* @param {BigNumberish} numerator
* @param {BigNumberish} denominator
* @returns {BN}
*/
export function percent(numerator: BigNumberish, denominator: BigNumberish): BN {
return fixedPointAdjustment.mul(numerator).div(denominator);
}
/**
* calcContinuousCompoundInterest. From https://www.calculatorsoup.com/calculators/financial/compound-interest-calculator.php?given_data=find_r&A=2&P=1&n=0&t=1&given_data_last=find_r&action=solve
* Returns a yearly interest rate if start/end amount had been continuously compounded over the period elapsed. Multiply result by 100 for a %.
*
* @param {string} startAmount
* @param {string} endAmount
* @param {string} periodsElapsed
* @param {string} periodsPerYear
*/
export const calcContinuousCompoundInterest = (
startAmount: Decimalish,
endAmount: Decimalish,
periodsElapsed: Decimalish,
periodsPerYear: Decimalish
): string => {
const years = new Decimal(periodsPerYear).div(periodsElapsed);
return new Decimal(endAmount).div(startAmount).ln().div(years).toString();
};
/**
* calcPeriodicCompoundInterest. Taken from https://www.calculatorsoup.com/calculators/financial/compound-interest-calculator.php?given_data=find_r&A=2&P=1&n=365&t=1&given_data_last=find_r&action=solve
* This will return a periodically compounded interest rate for 1 year. Multiply result by 100 for a %.
*
* @param {string} startAmount - Starting amount or price
* @param {string} endAmount - Ending amount or price
* @param {string} periodsElapsed - How many periods elapsed for the start and end amount.
* @param {string} periodsPerYear - How many periods in 1 year.
*/
export const calcPeriodicCompoundInterest = (
startAmount: Decimalish,
endAmount: Decimalish,
periodsElapsed: Decimalish,
periodsPerYear: Decimalish
): string => {
const n = new Decimal(periodsPerYear);
const A = new Decimal(endAmount);
const P = new Decimal(startAmount);
const t = new Decimal(periodsPerYear).div(periodsElapsed);
const one = new Decimal(1);
return n
.mul(
A.div(P)
.pow(one.div(n.div(t)))
.sub(one)
)
.toFixed(18);
};
/**
* calcApr. Simple apr calculation based on extrapolating the difference for a short period over a year.
*
* @param {Decimalish} startAmount - Starting amount or price
* @param {Decimalish} endAmount - Ending amount or price
* @param {Decimalish} periodsElapsed - periods elapsed from start to end
* @param {Decimalish} periodsPerYear - periods per year
*/
export const calcApr = (
startAmount: Decimalish,
endAmount: Decimalish,
periodsElapsed: Decimalish,
periodsPerYear: Decimalish
): string => {
return new Decimal(endAmount).sub(startAmount).div(startAmount).mul(periodsPerYear).div(periodsElapsed).toFixed(18);
};
/**
* Takes two values and returns a list of number intervals
*
* @example
* ```js
* getSamplesBetween(1, 9, 3) //returns [[1, 3], [4, 7], [8, 9]]
* ```
*/
export const getSamplesBetween = (min: number, max: number, size: number) => {
let keepIterate = true;
const intervals = [];
while (keepIterate) {
const to = Math.min(min + size - 1, max);
intervals.push([min, to]);
min = to + 1;
if (min >= max) keepIterate = false;
}
return intervals;
};
/**
* A promise that resolves after a specified number of seconds
* @param seconds The number of seconds to wait
*/
export function delay(seconds: number) {
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
}
/**
* Attempt to retry a function call a number of times with a delay between each attempt
* @param call The function to call
* @param times The number of times to retry
* @param delayS The number of seconds to delay between each attempt
* @returns The result of the function call.
*/
export function retry<T>(call: () => Promise<T>, times: number, delayS: number): Promise<T> {
let promiseChain = call();
for (let i = 0; i < times; i++)
promiseChain = promiseChain.catch(async () => {
await delay(delayS);
return await call();
});
return promiseChain;
}
export type TransactionCostEstimate = {
nativeGasCost: BigNumber; // Units: gas
tokenGasCost: BigNumber; // Units: wei (nativeGasCost * wei/gas)
};
/**
* Estimates the total gas cost required to submit an unsigned (populated) transaction on-chain.
* @param unsignedTx The unsigned transaction that this function will estimate.
* @param senderAddress The address that the transaction will be submitted from.
* @param provider A valid ethers provider - will be used to reason the gas price.
* @param options
* @param options.gasPrice A manually provided gas price - if set, this function will not resolve the current gas price.
* @param options.gasUnits A manually provided gas units - if set, this function will not estimate the gas units.
* @param options.transport A custom transport object for custom gas price retrieval.
* @returns Estimated cost in units of gas and the underlying gas token (gasPrice * estimatedGasUnits).
*/
export async function estimateTotalGasRequiredByUnsignedTransaction(
unsignedTx: PopulatedTransaction,
senderAddress: string,
provider: providers.Provider,
options: Partial<{
gasPrice: BigNumberish;
gasUnits: BigNumberish;
transport: Transport;
}> = {}
): Promise<TransactionCostEstimate> {
const { gasPrice: _gasPrice, gasUnits, transport } = options || {};
const { chainId } = await provider.getNetwork();
const voidSigner = new VoidSigner(senderAddress, provider);
// Estimate the Gas units required to submit this transaction.
const nativeGasCost = gasUnits ? BigNumber.from(gasUnits) : await voidSigner.estimateGas(unsignedTx);
let tokenGasCost: BigNumber;
// OP stack is a special case; gas cost is computed by the SDK, without having to query price.
if (chainIsOPStack(chainId)) {
const chain = Object.values(chains).find((chain) => chain.id === chainId);
assert(chain, `Chain ID ${chainId} not supported`);
const opStackClient = createPublicClient({
chain,
transport: transport ?? http(),
}).extend(publicActionsL2());
const populatedTransaction = await voidSigner.populateTransaction({
...unsignedTx,
gasLimit: nativeGasCost, // prevents additional gas estimation call
});
const [l1GasCost, l2GasPrice] = await Promise.all([
opStackClient.estimateL1Fee({
account: senderAddress as Address,
to: populatedTransaction.to as Address,
value: BigInt(populatedTransaction.value?.toString() ?? 0),
data: populatedTransaction.data as Hex,
gas: populatedTransaction.gasLimit ? BigInt(populatedTransaction.gasLimit.toString()) : undefined,
}),
_gasPrice ? BigInt(_gasPrice.toString()) : opStackClient.getGasPrice(),
]);
const l2GasCost = nativeGasCost.mul(l2GasPrice.toString());
tokenGasCost = BigNumber.from(l1GasCost.toString()).add(l2GasCost);
} else if (chainId === CHAIN_IDs.LINEA && process.env[`NEW_GAS_PRICE_ORACLE_${chainId}`] === "true") {
// Permit linea_estimateGas via NEW_GAS_PRICE_ORACLE_59144=true
const {
gasLimit: nativeGasCost,
baseFeePerGas,
priorityFeePerGas,
} = await getLineaGasFees(chainId, transport, unsignedTx);
tokenGasCost = baseFeePerGas.add(priorityFeePerGas).mul(nativeGasCost);
} else {
let gasPrice = _gasPrice;
if (!gasPrice) {
const gasPriceEstimate = await getGasPriceEstimate(provider, chainId, transport);
gasPrice = gasPriceEstimate.maxFeePerGas;
}
tokenGasCost = nativeGasCost.mul(gasPrice);
}
return {
nativeGasCost, // Units: gas
tokenGasCost, // Units: wei (nativeGasCost * wei/gas)
};
}
async function getLineaGasFees(chainId: number, transport: Transport | undefined, unsignedTx: PopulatedTransaction) {
const { gasLimit, baseFeePerGas, priorityFeePerGas } = await estimateGas(getPublicClient(chainId, transport), {
account: unsignedTx.from as Address,
to: unsignedTx.to as Address,
value: BigInt(unsignedTx.value?.toString() || "1"),
});
return {
gasLimit: BigNumber.from(gasLimit.toString()),
baseFeePerGas: BigNumber.from(baseFeePerGas.toString()),
priorityFeePerGas: BigNumber.from(priorityFeePerGas.toString()),
};
}
export type UpdateDepositDetailsMessageType = {
UpdateDepositDetails: [
{
name: "depositId";
type: "uint32";
},
{ name: "originChainId"; type: "uint256" },
{ name: "updatedRelayerFeePct"; type: "int64" },
{ name: "updatedRecipient"; type: "address" },
{ name: "updatedMessage"; type: "bytes" },
];
};
export type UpdateV3DepositDetailsMessageType = {
UpdateDepositDetails: [
{ name: "depositId"; type: "uint32" },
{ name: "originChainId"; type: "uint256" },
{ name: "updatedOutputAmount"; type: "uint256" },
{ name: "updatedRecipient"; type: "address" },
{ name: "updatedMessage"; type: "bytes" },
];
};
/**
* Utility function to get EIP-712 compliant typed data that can be signed with the JSON-RPC method
* `eth_signedTypedDataV4` in MetaMask (https://docs.metamask.io/guide/signing-data.html). The resulting signature
* can then be used to call the method `speedUpDeposit` of a `SpokePool.sol` contract.
* @param depositId The deposit ID to speed up.
* @param originChainId The chain ID of the origin chain.
* @param updatedRelayerFeePct The new relayer fee percentage.
* @param updatedRecipient The new recipient address.
* @param updatedMessage The new message that should be provided to the recipient.
* @return EIP-712 compliant typed data.
*/
export function getUpdateDepositTypedData(
depositId: number,
originChainId: number,
updatedRelayerFeePct: BigNumber,
updatedRecipient: string,
updatedMessage: string
): TypedMessage<UpdateDepositDetailsMessageType> {
return {
types: {
UpdateDepositDetails: [
{ name: "depositId", type: "uint32" },
{ name: "originChainId", type: "uint256" },
{ name: "updatedRelayerFeePct", type: "int64" },
{ name: "updatedRecipient", type: "address" },
{ name: "updatedMessage", type: "bytes" },
],
},
primaryType: "UpdateDepositDetails",
domain: {
name: "ACROSS-V2",
version: "1.0.0",
chainId: originChainId,
},
message: {
depositId,
originChainId,
updatedRelayerFeePct,
updatedRecipient,
updatedMessage,
},
};
}
export function getUpdateV3DepositTypedData(
depositId: number,
originChainId: number,
updatedOutputAmount: BigNumber,
updatedRecipient: string,
updatedMessage: string
): TypedMessage<UpdateV3DepositDetailsMessageType> {
return {
types: {
UpdateDepositDetails: [
{ name: "depositId", type: "uint32" },
{ name: "originChainId", type: "uint256" },
{ name: "updatedOutputAmount", type: "uint256" },
{ name: "updatedRecipient", type: "address" },
{ name: "updatedMessage", type: "bytes" },
],
},
primaryType: "UpdateDepositDetails",
domain: {
name: "ACROSS-V2",
version: "1.0.0",
chainId: originChainId,
},
message: {
depositId,
originChainId,
updatedOutputAmount,
updatedRecipient,
updatedMessage,
},
};
}
export function randomAddress() {
return ethers.utils.getAddress(ethers.utils.hexlify(ethers.utils.randomBytes(20)));
}