Merge branch 'contract-updates' of github.com:web3well/bls-wallet into bw-458-audit-fix-06

This commit is contained in:
jacque006
2023-06-27 12:02:49 -06:00
20 changed files with 433 additions and 50 deletions

View File

@@ -40,3 +40,7 @@ PRIORITY_FEE_PER_GAS=0
PREVIOUS_BASE_FEE_PERCENT_INCREASE=2
BUNDLE_CHECKING_CONCURRENCY=8
IS_OPTIMISM=false
OPTIMISM_GAS_PRICE_ORACLE_ADDRESS=0x420000000000000000000000000000000000000F
OPTIMISM_L1_BASE_FEE_PERCENT_INCREASE=2

View File

@@ -38,3 +38,5 @@ PRIORITY_FEE_PER_GAS=500000000
PREVIOUS_BASE_FEE_PERCENT_INCREASE=13
BUNDLE_CHECKING_CONCURRENCY=8
IS_OPTIMISM=false

View File

@@ -35,3 +35,5 @@ PRIORITY_FEE_PER_GAS=500000000
PREVIOUS_BASE_FEE_PERCENT_INCREASE=13
BUNDLE_CHECKING_CONCURRENCY=8
IS_OPTIMISM=false

View File

@@ -89,32 +89,35 @@ commands.
#### Environment Variables
| Name | Example Value | Description |
| ---------------------------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| RPC_URL | https://localhost:8545 | The RPC endpoint for an EVM node that the BLS Wallet contracts are deployed on |
| RPC_POLLING_INTERVAL | 4000 | How long to wait between retries, when needed (used by ethers when waiting for blocks) |
| USE_TEST_NET | false | Whether to set all transaction's `gasPrice` to 0. Workaround for some networks |
| ORIGIN | http://localhost:3000 | The origin for the aggregator client. Used only in manual tests |
| PORT | 3000 | The port to bind the aggregator to |
| NETWORK_CONFIG_PATH | ../contracts/networks/local.json | Path to the network config file, which contains information on deployed BLS Wallet contracts |
| PRIVATE_KEY_AGG | 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 | Private key for the EOA account used to submit bundles on chain. Transactions are paid by the account linked to PRIVATE_KEY_AGG. By default, bundles must pay for themselves by sending funds to tx.origin or the aggregators onchain address |
| PRIVATE_KEY_ADMIN | 0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d | Private key for the admin EOA account. Used only in tests |
| TEST_BLS_WALLETS_SECRET | test-bls-wallets-secret | Secret used to seed BLS Wallet private keys during tests |
| DB_PATH | aggregator.sqlite | File path of the sqlite db |
| BUNDLE_QUERY_LIMIT | 100 | Maximum number of bundles returned from sqlite |
| MAX_GAS_PER_BUNDLE | 2000000 | Limits the amount of user operations which can be bundled together by using this value as the approximate limit on the amount of gas in an aggregate bundle |
| MAX_AGGREGATION_DELAY_MILLIS | 5000 | Maximum amount of time in milliseconds aggregator will wait before submitting bundles on chain. A higher number will allow more time for bundles to fill, but may result in longer periods before submission. A lower number allows more frequent L2 submissions, but may result in smaller bundles |
| MAX_UNCONFIRMED_AGGREGATIONS | 3 | Maximum unconfirmed bundle aggregations that will be submitted on chain |
| LOG_QUERIES | false | Whether to print sqlite queries in event log. When running tests, `TEST_LOGGING` must also be enabled |
| TEST_LOGGING | false | Whether to print aggregator server events to stdout during tests. Useful for debugging & logging |
| REQUIRE_FEES | true | Whether to require that user bundles pay the aggregator a sufficient fee |
| BREAKEVEN_OPERATION_COUNT | 4.5 | The aggregator must pay an overhead to submit a bundle regardless of how many operations it contains. This parameter determines how much each operation must contribute to this overhead |
| ALLOW_LOSSES | true | Even if each user bundle pays the required fee, the aggregate bundle may not be profitable if it is too small. Setting this to true makes the aggregator submit these bundles anyway |
| FEE_TYPE | ether OR token:0xabcd...1234 | The fee type the aggregator will accept. Either `ether` for ETH/chains native currency or `token:0xabcd...1234` (token contract address) for an ERC20 token |
| AUTO_CREATE_INTERNAL_BLS_WALLET | false | An internal BLS wallet is used to calculate bundle overheads. Setting this to true allows creating this wallet on startup, but might be undesirable in production (see `programs/createInternalBlsWallet.ts` for manual creation) |
| PRIORITY_FEE_PER_GAS | 0 | The priority fee used when submitting bundles (and passed on as a requirement for user bundles) |
| PREVIOUS_BASE_FEE_PERCENT_INCREASE | 2 | Used to determine the max basefee attached to aggregator transaction (and passed on as a requirement for user bundles)s |
| BUNDLE_CHECKING_CONCURRENCY | 8 | The maximum number of bundles that are checked concurrently (getting gas usage, detecting fees, etc) |
| Name | Example Value | Description |
| ------------------------------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| RPC_URL | https://localhost:8545 | The RPC endpoint for an EVM node that the BLS Wallet contracts are deployed on |
| RPC_POLLING_INTERVAL | 4000 | How long to wait between retries, when needed (used by ethers when waiting for blocks) |
| USE_TEST_NET | false | Whether to set all transaction's `gasPrice` to 0. Workaround for some networks |
| ORIGIN | http://localhost:3000 | The origin for the aggregator client. Used only in manual tests |
| PORT | 3000 | The port to bind the aggregator to |
| NETWORK_CONFIG_PATH | ../contracts/networks/local.json | Path to the network config file, which contains information on deployed BLS Wallet contracts |
| PRIVATE_KEY_AGG | 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 | Private key for the EOA account used to submit bundles on chain. Transactions are paid by the account linked to PRIVATE_KEY_AGG. By default, bundles must pay for themselves by sending funds to tx.origin or the aggregators onchain address |
| PRIVATE_KEY_ADMIN | 0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d | Private key for the admin EOA account. Used only in tests |
| TEST_BLS_WALLETS_SECRET | test-bls-wallets-secret | Secret used to seed BLS Wallet private keys during tests |
| DB_PATH | aggregator.sqlite | File path of the sqlite db |
| BUNDLE_QUERY_LIMIT | 100 | Maximum number of bundles returned from sqlite |
| MAX_GAS_PER_BUNDLE | 2000000 | Limits the amount of user operations which can be bundled together by using this value as the approximate limit on the amount of gas in an aggregate bundle |
| MAX_AGGREGATION_DELAY_MILLIS | 5000 | Maximum amount of time in milliseconds aggregator will wait before submitting bundles on chain. A higher number will allow more time for bundles to fill, but may result in longer periods before submission. A lower number allows more frequent L2 submissions, but may result in smaller bundles |
| MAX_UNCONFIRMED_AGGREGATIONS | 3 | Maximum unconfirmed bundle aggregations that will be submitted on chain |
| LOG_QUERIES | false | Whether to print sqlite queries in event log. When running tests, `TEST_LOGGING` must also be enabled |
| TEST_LOGGING | false | Whether to print aggregator server events to stdout during tests. Useful for debugging & logging |
| REQUIRE_FEES | true | Whether to require that user bundles pay the aggregator a sufficient fee |
| BREAKEVEN_OPERATION_COUNT | 4.5 | The aggregator must pay an overhead to submit a bundle regardless of how many operations it contains. This parameter determines how much each operation must contribute to this overhead |
| ALLOW_LOSSES | true | Even if each user bundle pays the required fee, the aggregate bundle may not be profitable if it is too small. Setting this to true makes the aggregator submit these bundles anyway |
| FEE_TYPE | ether OR token:0xabcd...1234 | The fee type the aggregator will accept. Either `ether` for ETH/chains native currency or `token:0xabcd...1234` (token contract address) for an ERC20 token |
| AUTO_CREATE_INTERNAL_BLS_WALLET | false | An internal BLS wallet is used to calculate bundle overheads. Setting this to true allows creating this wallet on startup, but might be undesirable in production (see `programs/createInternalBlsWallet.ts` for manual creation) |
| PRIORITY_FEE_PER_GAS | 0 | The priority fee used when submitting bundles (and passed on as a requirement for user bundles) |
| PREVIOUS_BASE_FEE_PERCENT_INCREASE | 2 | Used to determine the max basefee attached to aggregator transaction (and passed on as a requirement for user bundles)s |
| BUNDLE_CHECKING_CONCURRENCY | 8 | The maximum number of bundles that are checked concurrently (getting gas usage, detecting fees, etc) |
| IS_OPTIMISM | false | Optimism's strategy for charging for L1 fees requires special logic in the aggregator. In addition to gasEstimate * gasPrice, we need to replicate Optimism's calculation and pass it on to the user |
| OPTIMISM_GAS_PRICE_ORACLE_ADDRESS | 0x420000000000000000000000000000000000000F | Address for the Optimism gas price oracle contract. Required when IS_OPTIMISM is true |
| OPTIMISM_L1_BASE_FEE_PERCENT_INCREASE | 2 | Similar to PREVIOUS_BASE_FEE_PERCENT_INCREASE, but for the L1 basefee for the optimism-specific calculation. This gets passed on to users. Required when IS_OPTIMISM is true |
## Running

View File

@@ -79,3 +79,5 @@ export { bundleFromDto, bundleToDto, initBlsWalletSigner };
export * as sqlite from "https://deno.land/x/sqlite@v3.7.0/mod.ts";
export { Semaphore } from "https://deno.land/x/semaphore@v1.1.2/mod.ts";
export { pick } from "npm:@s-libs/micro-dash@15.2.0";

View File

@@ -0,0 +1,17 @@
#!/usr/bin/env -S deno run --allow-net --allow-env --allow-read
import * as env from "../src/env.ts";
import { ethers } from "../deps.ts";
import OptimismGasPriceOracle from "../src/app/OptimismGasPriceOracle.ts";
const oracle = new OptimismGasPriceOracle(
new ethers.providers.JsonRpcProvider(env.RPC_URL),
);
const { l1BaseFee, overhead, scalar, decimals } = await oracle.getAllParams();
console.log({
l1BaseFee: `${(l1BaseFee.toNumber() / 1e9).toFixed(3)} gwei`,
overhead: `${overhead.toNumber()} L1 gas`,
scalar: scalar.toNumber() / (10 ** decimals.toNumber()),
});

View File

@@ -0,0 +1,17 @@
#!/usr/bin/env -S deno run --allow-net --allow-env --allow-read
import { ethers } from "../deps.ts";
import * as env from "../src/env.ts";
import getOptimismL1Fee from "../src/helpers/getOptimismL1Fee.ts";
const provider = new ethers.providers.JsonRpcProvider(env.RPC_URL);
const txHash = Deno.args[0];
if (!txHash.startsWith("0x")) {
throw new Error("First arg should be tx hash");
}
const l1Fee = await getOptimismL1Fee(provider, txHash);
console.log(`${ethers.utils.formatEther(l1Fee)} ETH`);

View File

@@ -0,0 +1,15 @@
#!/usr/bin/env -S deno run --allow-net --allow-env --allow-read
import { ethers } from "../deps.ts";
import * as env from "../src/env.ts";
import getRawTransaction from "../src/helpers/getRawTransaction.ts";
const provider = new ethers.providers.JsonRpcProvider(env.RPC_URL);
const txHash = Deno.args[0];
if (!txHash.startsWith("0x")) {
throw new Error("First arg should be tx hash");
}
console.log(await getRawTransaction(provider, txHash));

View File

@@ -60,7 +60,7 @@ const bundles: Bundle[] = [];
for (const [i, wallet] of wallets.entries()) {
const nonce = await wallet.Nonce();
console.log("Funding wallet", i);
console.log("Funding wallet", i, "(1 wei to make estimateFee work)");
await (await adminWallet.sendTransaction({
to: wallet.address,
@@ -92,7 +92,7 @@ for (const [i, wallet] of wallets.entries()) {
// Ensure wallet can pay the fee
if (balance.lt(fee)) {
console.log("Funding wallet");
console.log("Funding wallet", i, "(based on estimateFee)");
await (await adminWallet.sendTransaction({
to: wallet.address,

View File

@@ -544,9 +544,10 @@ export default class AggregationStrategy {
bundleOverheadGas ??=
(await this.measureBundleOverhead()).bundleOverheadGas;
const gasEstimate = await this.ethereumService.estimateCompressedGas(
bundle,
);
const gasEstimate = await this.ethereumService
.estimateEffectiveCompressedGas(
bundle,
);
const marginalGasEstimate = gasEstimate.sub(bundleOverheadGas);
@@ -630,12 +631,18 @@ export default class AggregationStrategy {
expectedFee: fee,
requiredFee: feeInfo.requiredFee,
expectedMaxCost: feeInfo.expectedMaxCost,
errorReason: { message: "Insufficient fee" },
errorReason: {
message: [
"Insufficient fee",
`(provided: ${ethers.utils.formatEther(fee)},`,
`required: ${ethers.utils.formatEther(feeInfo.requiredFee)})`,
].join(" "),
},
};
}
const gasEstimate = feeInfo?.gasEstimate ??
await this.ethereumService.estimateCompressedGas(bundle);
await this.ethereumService.estimateEffectiveCompressedGas(bundle);
return {
success,
@@ -673,8 +680,8 @@ export default class AggregationStrategy {
});
const [oneOpGasEstimate, twoOpGasEstimate] = await Promise.all([
es.estimateCompressedGas(bundle1),
es.estimateCompressedGas(
es.estimateEffectiveCompressedGas(bundle1),
es.estimateEffectiveCompressedGas(
this.blsWalletSigner.aggregate([bundle1, bundle2]),
),
]);

View File

@@ -1,6 +1,7 @@
import { HTTPMethods } from "../../deps.ts";
type AppEvent =
| { type: "starting" }
| { type: "listening"; data: { port: number } }
| { type: "db-query"; data: { sql: string; params: unknown } }
| { type: "waiting-unconfirmed-space" }

View File

@@ -23,6 +23,7 @@ import BundleTable, { BundleRow } from "./BundleTable.ts";
import plus from "./helpers/plus.ts";
import AggregationStrategy from "./AggregationStrategy.ts";
import nil from "../helpers/nil.ts";
import getOptimismL1Fee from "../helpers/getOptimismL1Fee.ts";
import ExplicitAny from "../helpers/ExplicitAny.ts";
export type AddBundleResponse = { hash: string } | {
@@ -36,6 +37,7 @@ export default class BundleService {
maxAggregationDelayMillis: env.MAX_AGGREGATION_DELAY_MILLIS,
maxUnconfirmedAggregations: env.MAX_UNCONFIRMED_AGGREGATIONS,
maxEligibilityDelay: env.MAX_ELIGIBILITY_DELAY,
isOptimism: env.IS_OPTIMISM,
};
unconfirmedBundles = new Set<Bundle>();
@@ -165,7 +167,8 @@ export default class BundleService {
if (!signedCorrectly) {
failures.push({
type: "invalid-signature",
description: `invalid bundle signature for signature ${bundle.signature}`,
description:
`invalid bundle signature for signature ${bundle.signature}`,
});
}
@@ -206,7 +209,7 @@ export default class BundleService {
lookupAggregateBundle(subBundleHash: string) {
const subBundle = this.bundleTable.findBundle(subBundleHash);
return this.bundleTable.findAggregateBundle(subBundle?.aggregateHash!)
return this.bundleTable.findAggregateBundle(subBundle?.aggregateHash!);
}
receiptFromBundle(bundle: BundleRow) {
@@ -246,17 +249,17 @@ export default class BundleService {
gas: BigNumber.from(0),
};
});
const verifyMethodName = "verify";
const bundleType = VerificationGatewayFactory.abi.find(
(entry) => "name" in entry && entry.name === verifyMethodName,
)?.inputs[0];
const validatedBundle = {
...bundle,
operations: operationsWithZeroGas,
};
const encodedBundleWithZeroSignature = ethers.utils.defaultAbiCoder.encode(
[bundleType as ExplicitAny],
[
@@ -266,7 +269,7 @@ export default class BundleService {
},
],
);
const bundleHash = ethers.utils.keccak256(encodedBundleWithZeroSignature);
const chainId = (await this.ethereumService.provider.getNetwork()).chainId;
@@ -417,7 +420,16 @@ export default class BundleService {
const profit = balanceAfter.sub(balanceBefore);
/** What we paid to process the bundle */
const cost = receipt.gasUsed.mul(receipt.effectiveGasPrice);
let cost = receipt.gasUsed.mul(receipt.effectiveGasPrice);
if (this.config.isOptimism) {
cost = cost.add(
await getOptimismL1Fee(
this.ethereumService.provider,
receipt.transactionHash,
),
);
}
/** Fees collected from users */
const actualFee = profit.add(cost);

View File

@@ -26,6 +26,8 @@ import toPublicKeyShort from "./helpers/toPublicKeyShort.ts";
import AsyncReturnType from "../helpers/AsyncReturnType.ts";
import ExplicitAny from "../helpers/ExplicitAny.ts";
import nil from "../helpers/nil.ts";
import hexToUint8Array from "../helpers/hexToUint8Array.ts";
import OptimismGasPriceOracle from "./OptimismGasPriceOracle.ts";
export type TxCheckResult = {
failures: TransactionFailure[];
@@ -76,6 +78,7 @@ export default class EthereumService {
public emit: (evt: AppEvent) => void,
public wallet: Wallet,
public provider: ethers.providers.Provider,
public chainId: number,
public blsWalletWrapper: BlsWalletWrapper,
public blsWalletSigner: BlsWalletSigner,
public verificationGateway: VerificationGateway,
@@ -169,6 +172,7 @@ export default class EthereumService {
emit,
wallet,
provider,
chainId,
blsWalletWrapper,
blsWalletSigner,
verificationGateway,
@@ -341,10 +345,10 @@ export default class EthereumService {
};
const attempt = async () => {
let txResponse: ethers.providers.TransactionResponse;
let response: ethers.providers.TransactionResponse;
try {
txResponse = await this.wallet.sendTransaction(txRequest);
response = await this.wallet.sendTransaction(txRequest);
} catch (error) {
if (/\binvalid transaction nonce\b/.test(error.message)) {
// This can occur when the nonce is in the future, which can
@@ -360,7 +364,10 @@ export default class EthereumService {
}
try {
return { type: "receipt" as const, value: await txResponse.wait() };
return {
type: "complete" as const,
value: await response.wait(),
};
} catch (error) {
return { type: "waitError" as const, value: error };
}
@@ -376,7 +383,7 @@ export default class EthereumService {
const attemptResult = await attempt();
if (attemptResult.type === "receipt") {
if (attemptResult.type === "complete") {
return attemptResult.value;
}
@@ -405,17 +412,44 @@ export default class EthereumService {
throw new Error("Expected return or throw from attempt loop");
}
async estimateCompressedGas(bundle: Bundle): Promise<BigNumber> {
/**
* Estimates the amount of effective gas needed to process the bundle using
* compression.
*
* Here 'effective' gas means the number you need to multiply by gasPrice in
* order to get the right fee. There are a few cases here:
*
* 1. L1 chains (used in testing, eg gethDev)
* - Effective gas is equal to regular gas
* 2. Arbitrum
* - The Arbitrum node already responds with effective gas when calling
* estimateGas
* 3. Optimism
* - We estimate Optimism's calculation for the amount of L1 gas it will
* charge for, and then convert that into an equivalend amount of L2 gas.
*/
async estimateEffectiveCompressedGas(bundle: Bundle): Promise<BigNumber> {
const compressedBundle = await this.bundleCompressor.compress(bundle);
return await this.wallet.estimateGas({
let gasEstimate = await this.wallet.estimateGas({
to: this.expanderEntryPoint.address,
data: compressedBundle,
});
if (env.IS_OPTIMISM) {
const extraGasEstimate = await this.estimateOptimismL2GasNeededForL1Gas(
compressedBundle,
gasEstimate,
);
gasEstimate = gasEstimate.add(extraGasEstimate);
}
return gasEstimate;
}
async GasConfig() {
const block = await this.provider.getBlock("latest");
async GasConfig(block?: ethers.providers.Block) {
block ??= await this.provider.getBlock("latest");
const previousBaseFee = block.baseFeePerGas;
assert(previousBaseFee !== null && previousBaseFee !== nil);
@@ -442,6 +476,66 @@ export default class EthereumService {
};
}
/**
* Estimates the L1 gas that Optimism will charge us for and expresses it as
* an amount of equivalent L2 gas.
*
* This is very similar to what Arbitrum does, but in Arbitrum it's built-in,
* and you actually sign for that additional L2 gas. On Optimism, you only
* sign for the actual L2 gas, and optimism just adds the L1 fee.
*
* For our purposes, this works as a way to normalize the behavior between
* the different chains.
*/
async estimateOptimismL2GasNeededForL1Gas(
compressedBundle: string,
gasLimit: BigNumber,
): Promise<BigNumber> {
const block = await this.provider.getBlock("latest");
const gasConfig = await this.GasConfig(block);
const txBytes = await this.wallet.signTransaction({
type: 2,
chainId: this.chainId,
nonce: this.nextNonce,
to: this.expanderEntryPoint.address,
data: compressedBundle,
...gasConfig,
gasLimit,
});
let l1Gas = 0;
for (const byte of hexToUint8Array(txBytes)) {
if (byte === 0) {
l1Gas += 4;
} else {
l1Gas += 16;
}
}
const gasOracle = new OptimismGasPriceOracle(this.provider);
const { l1BaseFee, overhead, scalar, decimals } = await gasOracle
.getAllParams();
const scalarNum = scalar.toNumber() / (10 ** decimals.toNumber());
l1Gas += overhead.toNumber();
assert(block.baseFeePerGas !== null && block.baseFeePerGas !== nil);
assert(env.OPTIMISM_L1_BASE_FEE_PERCENT_INCREASE !== nil);
const adjustedL1BaseFee = l1BaseFee.toNumber() * scalarNum *
(1 + env.OPTIMISM_L1_BASE_FEE_PERCENT_INCREASE / 100);
const feeRatio = adjustedL1BaseFee / block.baseFeePerGas.toNumber();
return BigNumber.from(
Math.ceil(feeRatio * l1Gas),
);
}
private static Wallet(
provider: ethers.providers.Provider,
privateKey: string,

View File

@@ -0,0 +1,52 @@
import { BigNumber, ethers } from "../../deps.ts";
import assert from "../helpers/assert.ts";
import { OPTIMISM_GAS_PRICE_ORACLE_ADDRESS } from "../env.ts";
export default class OptimismGasPriceOracle {
constructor(
public provider: ethers.providers.Provider,
) {}
private async callFn(method: string, blockTag?: ethers.providers.BlockTag) {
const outputBytes = await this.provider.call({
to: OPTIMISM_GAS_PRICE_ORACLE_ADDRESS,
data: ethers.utils.id(method),
}, blockTag);
const result = ethers.utils.defaultAbiCoder.decode(
["uint256"],
outputBytes,
)[0];
assert(result instanceof BigNumber);
return result;
}
async l1BaseFee(blockTag?: ethers.providers.BlockTag) {
return await this.callFn("l1BaseFee()", blockTag);
}
async overhead(blockTag?: ethers.providers.BlockTag) {
return await this.callFn("overhead()", blockTag);
}
async scalar(blockTag?: ethers.providers.BlockTag) {
return await this.callFn("scalar()", blockTag);
}
async decimals(blockTag?: ethers.providers.BlockTag) {
return await this.callFn("decimals()", blockTag);
}
async getAllParams(blockTag?: ethers.providers.BlockTag) {
const [l1BaseFee, overhead, scalar, decimals] = await Promise.all([
this.l1BaseFee(blockTag),
this.overhead(blockTag),
this.scalar(blockTag),
this.decimals(blockTag),
]);
return { l1BaseFee, overhead, scalar, decimals };
}
}

View File

@@ -18,6 +18,8 @@ import HealthService from "./HealthService.ts";
import HealthRouter from "./HealthRouter.ts";
export default async function app(emit: (evt: AppEvent) => void) {
emit({ type: "starting" });
const clock = Clock.create();
const bundleTableMutex = new Mutex();

View File

@@ -1,4 +1,6 @@
import assert from "./helpers/assert.ts";
import {
optionalEnv,
optionalNumberEnv,
requireBigNumberEnv,
requireBoolEnv,
@@ -95,3 +97,38 @@ export const PREVIOUS_BASE_FEE_PERCENT_INCREASE = requireNumberEnv(
export const BUNDLE_CHECKING_CONCURRENCY = requireIntEnv(
"BUNDLE_CHECKING_CONCURRENCY",
);
/**
* Optimism's strategy for charging for L1 fees requires special logic in the
* aggregator. In addition to gasEstimate * gasPrice, we need to replicate
* Optimism's calculation and pass it on to the user.
*/
export const IS_OPTIMISM = requireBoolEnv("IS_OPTIMISM");
/**
* Address for the Optimism gas price oracle contract. Required when
* IS_OPTIMISM is true.
*/
export const OPTIMISM_GAS_PRICE_ORACLE_ADDRESS = optionalEnv(
"OPTIMISM_GAS_PRICE_ORACLE_ADDRESS",
);
/**
* Similar to PREVIOUS_BASE_FEE_PERCENT_INCREASE, but for the L1 basefee for
* the optimism-specific calculation. This gets passed on to users.
* Required when IS_OPTIMISM is true.
*/
export const OPTIMISM_L1_BASE_FEE_PERCENT_INCREASE = optionalNumberEnv(
"OPTIMISM_L1_BASE_FEE_PERCENT_INCREASE",
);
if (IS_OPTIMISM) {
assert(
OPTIMISM_L1_BASE_FEE_PERCENT_INCREASE !== nil,
"OPTIMISM_L1_BASE_FEE_PERCENT_INCREASE is required when IS_OPTIMISM is true",
);
assert(
OPTIMISM_GAS_PRICE_ORACLE_ADDRESS !== nil,
"OPTIMISM_GAS_PRICE_ORACLE_ADDRESS is required when IS_OPTIMISM is true",
);
}

View File

@@ -0,0 +1,50 @@
import { BigNumber, ethers } from "../../deps.ts";
import OptimismGasPriceOracle from "../app/OptimismGasPriceOracle.ts";
import assert from "./assert.ts";
import getRawTransaction from "./getRawTransaction.ts";
import hexToUint8Array from "./hexToUint8Array.ts";
import nil from "./nil.ts";
export default async function getOptimismL1Fee(
provider: ethers.providers.Provider,
txResponseOrHash: string | ethers.providers.TransactionResponse,
) {
const tx = typeof txResponseOrHash === "string"
? await provider.getTransaction(txResponseOrHash)
: txResponseOrHash;
const rawTx = await getRawTransaction(provider, tx);
let l1Gas = 0;
for (const byte of hexToUint8Array(rawTx)) {
if (byte === 0) {
l1Gas += 4;
} else {
l1Gas += 16;
}
}
const gasOracle = new OptimismGasPriceOracle(provider);
assert(tx.blockNumber !== nil);
const {
l1BaseFee,
overhead,
scalar,
decimals,
} = await gasOracle.getAllParams(tx.blockNumber);
l1Gas = l1Gas += overhead.toNumber();
const l1Fee = BigNumber
.from(l1Gas)
.mul(l1BaseFee)
.mul(scalar)
.div(
BigNumber.from(10).pow(decimals),
);
return l1Fee;
}

View File

@@ -0,0 +1,49 @@
import { ethers, pick } from "../../deps.ts";
import assert from "./assert.ts";
import nil from "./nil.ts";
export default async function getRawTransaction(
provider: ethers.providers.Provider,
txResponseOrHash: string | ethers.providers.TransactionResponse,
) {
const tx = typeof txResponseOrHash === "string"
? await provider.getTransaction(txResponseOrHash)
: txResponseOrHash;
const txHash = typeof txResponseOrHash === "string"
? txResponseOrHash
: tx.hash;
assert(typeof txHash === "string");
const { v, r, s } = tx;
assert(r !== nil);
const txBytes = ethers.utils.serializeTransaction(
pick(
tx,
"to",
"nonce",
"gasLimit",
...(tx.type === 2 ? [] : ["gasPrice"] as const),
"data",
"value",
"chainId",
"type",
...(tx.type !== 2 ? [] : [
"accessList",
"maxPriorityFeePerGas",
"maxFeePerGas",
] as const),
),
{ v, r, s },
);
const reconstructedHash = ethers.utils.keccak256(txBytes);
if (reconstructedHash !== txHash) {
throw new Error("Reconstructed hash did not match original hash");
}
return txBytes;
}

View File

@@ -0,0 +1,16 @@
import assert from "./assert.ts";
export default function hexToUint8Array(hex: string) {
assert(hex.startsWith("0x"));
assert(hex.length % 2 === 0);
const len = (hex.length - 2) / 2;
const result = new Uint8Array(len);
for (let i = 0; i < len; i++) {
const hexPos = 2 * i + 2;
result[i] = parseInt(hex.slice(hexPos, hexPos + 2), 16);
}
return result;
}

View File

@@ -37,6 +37,7 @@ export const bundleServiceDefaultTestConfig:
maxAggregationDelayMillis: 5000,
maxUnconfirmedAggregations: 3,
maxEligibilityDelay: 300,
isOptimism: false,
};
export const aggregationStrategyDefaultTestConfig: AggregationStrategyConfig = {