Skip to content

fix(relayer): Use precomputed gas limits #1876

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 10 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 52 additions & 44 deletions src/clients/ProfitClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export class ProfitClient {
private unprofitableFills: { [chainId: number]: UnprofitableFill[] } = {};

// Track total gas costs of a relay on each chain.
protected totalGasCosts: { [chainId: number]: TransactionCostEstimate } = {};
protected totalGasCosts: { [chainId: number]: { [outputToken: string]: TransactionCostEstimate } } = {};

// Queries needed to fetch relay gas costs.
private relayerFeeQueries: { [chainId: number]: relayFeeCalculator.QueryInterface } = {};
Expand Down Expand Up @@ -221,18 +221,18 @@ export class ProfitClient {
}

async getTotalGasCost(deposit: Deposit): Promise<TransactionCostEstimate> {
const { destinationChainId: chainId } = deposit;
const { destinationChainId, outputToken } = deposit;

// If there's no attached message, gas consumption from previous fills can be used in most cases.
// @todo: Simulate this per-token in future, because some ERC20s consume more gas.
if (isMessageEmpty(resolveDepositMessage(deposit)) && isDefined(this.totalGasCosts[chainId])) {
return this.totalGasCosts[chainId];
const gasCost = this.totalGasCosts[destinationChainId]?.[outputToken];
if (isMessageEmpty(resolveDepositMessage(deposit)) && isDefined(gasCost)) {
return gasCost;
}

return this._getTotalGasCost(deposit, this.relayerAddress);
}

getGasCostsForChain(chainId: number): TransactionCostEstimate {
getGasCostsForChain(chainId: number): { [token: string]: TransactionCostEstimate } {
return this.totalGasCosts[chainId];
}

Expand Down Expand Up @@ -609,23 +609,11 @@ export class ProfitClient {
const outputAmount = toBN(100); // Avoid rounding to zero but ensure the relayer has sufficient balance to estimate.
const currentTime = getCurrentTime();

// Prefer USDC on mainnet because it's consistent in terms of gas estimation (no unwrap conditional).
// Prefer WETH on testnet because it's more likely to be configured for the destination SpokePool.
// The relayer _cannot_ be the recipient because the SpokePool skips the ERC20 transfer. Instead, use
// the main RL address because it has all supported tokens and approvals in place on all chains.
const testSymbols = {
[CHAIN_IDs.ALEPH_ZERO]: "USDT", // USDC is not yet supported on AlephZero, so revert to USDT. @todo: Update.
[CHAIN_IDs.BLAST]: "USDB",
[CHAIN_IDs.INK]: "WETH", // USDC deferred on Ink.
[CHAIN_IDs.LISK]: "USDT", // USDC is not yet supported on Lisk, so revert to USDT. @todo: Update.
[CHAIN_IDs.REDSTONE]: "WETH", // Redstone only supports WETH.
[CHAIN_IDs.SONEIUM]: "WETH", // USDC deferred on Soneium.
[CHAIN_IDs.WORLD_CHAIN]: "WETH", // USDC deferred on World Chain.
[CHAIN_IDs.LENS_SEPOLIA]: "WETH", // No USD token on Lens Sepolia
};
const ignoredTokens = ["BADGER", "BOBA"];
const l1Tokens = hubPoolClient.getL1Tokens().filter(({ symbol }) => !ignoredTokens.includes(symbol));

const prodRelayer = process.env.RELAYER_FILL_SIMULATION_ADDRESS ?? PROD_RELAYER;
const [defaultTestSymbol, relayer] =
this.hubPoolClient.chainId === CHAIN_IDs.MAINNET ? ["USDC", prodRelayer] : ["WETH", TEST_RELAYER];
const relayer = this.hubPoolClient.chainId === CHAIN_IDs.MAINNET ? prodRelayer : TEST_RELAYER;

// @dev The relayer _cannot_ be the recipient because the SpokePool skips the ERC20 transfer. Instead,
// use the main RL address because it has all supported tokens and approvals in place on all chains.
Expand All @@ -648,22 +636,42 @@ export class ProfitClient {
toLiteChain: false,
};

// Pre-fetch total gas costs for relays on enabled chains.
const totalGasCostsToLog = Object.fromEntries(
await sdkUtils.mapAsync(enabledChainIds, async (destinationChainId) => {
const symbol = testSymbols[destinationChainId] ?? defaultTestSymbol;
const hubToken = TOKEN_SYMBOLS_MAP[symbol].addresses[this.hubPoolClient.chainId];
const outputToken =
const spokeTokens = Object.fromEntries(
enabledChainIds.map((destinationChainId) => {
const spokeTokens =
destinationChainId === hubPoolClient.chainId
? hubToken
: hubPoolClient.getL2TokenForL1TokenAtBlock(hubToken, destinationChainId);
assert(isDefined(outputToken), `Chain ${destinationChainId} SpokePool is not configured for ${symbol}`);
? l1Tokens.map(({ address }) => address)
: l1Tokens
.map(({ address }) => {
try {
return hubPoolClient.getL2TokenForL1TokenAtBlock(address, destinationChainId);
} catch {
return undefined;
}
})
.filter(isDefined);
return [destinationChainId, spokeTokens];
})
);

type GasCostLog = sdkUtils.TransactionCostEstimate & {
scaledNativeGasCost: BigNumber;
scaledTokenGasCost: BigNumber;
gasPadding: string;
gasMultiplier: string;
};

// Pre-fetch total gas costs for relays on enabled chains.
const totalGasCostsToLog: { [destinationChainId: number]: { [token: string]: GasCostLog } } = {};
await sdkUtils.mapAsync(enabledChainIds, async (destinationChainId) => {
this.totalGasCosts[destinationChainId] ??= {};
await sdkUtils.mapAsync(spokeTokens[destinationChainId], async (outputToken) => {
const deposit = { ...sampleDeposit, destinationChainId, outputToken };
const gasCosts = await this._getTotalGasCost(deposit, relayer);
// The scaledNativeGasCost is approximately what the relayer will set as the `gasLimit` when submitting
// fills on the destination chain.
const scaledNativeGasCost = gasCosts.nativeGasCost.mul(this.gasPadding).div(fixedPointAdjustment);

// The scaledTokenGasCost is the estimated gas cost of submitting a fill on the destination chain and is used
// in the this.estimateFillCost function to determine whether a deposit is profitable to fill. Therefore,
// the scaledTokenGasCost should be safely lower than the quote API's tokenGasCosts in order for the relayer
Expand All @@ -673,19 +681,19 @@ export class ProfitClient {
.div(fixedPointAdjustment)
.mul(this.gasMultiplier)
.div(fixedPointAdjustment);
this.totalGasCosts[destinationChainId] = gasCosts;
return [
destinationChainId,
{
...gasCosts,
scaledNativeGasCost,
scaledTokenGasCost,
gasPadding: formatEther(this.gasPadding),
gasMultiplier: formatEther(this.gasMultiplier),
},
];
})
);

this.totalGasCosts[destinationChainId][outputToken] = gasCosts; // XXX verify

totalGasCostsToLog[destinationChainId] ??= {};
totalGasCostsToLog[destinationChainId][outputToken] = {
...gasCosts,
scaledNativeGasCost,
scaledTokenGasCost,
gasPadding: formatEther(this.gasPadding),
gasMultiplier: formatEther(this.gasMultiplier),
};
});
});

this.logger.debug({
at: "ProfitClient",
Expand Down
30 changes: 13 additions & 17 deletions src/relayer/Relayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -675,15 +675,9 @@ export class Relayer {
l1Token,
lpFees
);
const {
relayerFeePct,
gasCost,
gasLimit: _gasLimit,
lpFeePct: realizedLpFeePct,
gasPrice,
} = repaymentChainProfitability;
const { relayerFeePct, gasCost, gasLimit, lpFeePct, gasPrice } = repaymentChainProfitability;
if (!isDefined(repaymentChainId)) {
profitClient.captureUnprofitableFill(deposit, realizedLpFeePct, relayerFeePct, gasCost);
profitClient.captureUnprofitableFill(deposit, lpFeePct, relayerFeePct, gasCost);
} else {
const { blockNumber, outputToken, outputAmount } = deposit;
const fillAmountUsd = profitClient.getFillAmountInUsd(deposit);
Expand All @@ -709,8 +703,7 @@ export class Relayer {
// Update local balance to account for the enqueued fill.
tokenClient.decrementLocalBalance(destinationChainId, outputToken, outputAmount);

const gasLimit = isMessageEmpty(resolveDepositMessage(deposit)) ? undefined : _gasLimit;
this.fillRelay(deposit, repaymentChainId, realizedLpFeePct, gasPrice, gasLimit);
this.fillRelay(deposit, repaymentChainId, lpFeePct, gasPrice, gasLimit);
}
} else if (selfRelay) {
// Prefer exiting early here to avoid fast filling any deposits we send. This approach assumes that we always
Expand All @@ -734,7 +727,7 @@ export class Relayer {
deposit,
destinationChainId,
lpFeePct,
this.clients.profitClient.getGasCostsForChain(destinationChainId).gasPrice
this.clients.profitClient.getGasCostsForChain(destinationChainId)[deposit.outputToken].gasPrice
);
} else {
// TokenClient.getBalance returns that we don't have enough balance to submit the fast fill.
Expand Down Expand Up @@ -992,7 +985,7 @@ export class Relayer {
deposit: Deposit,
repaymentChainId: number,
realizedLpFeePct: BigNumber,
gasPrice: BigNumber,
gasPrice?: BigNumber,
gasLimit?: BigNumber
): void {
const { spokePoolClients } = this.clients;
Expand Down Expand Up @@ -1394,7 +1387,7 @@ export class Relayer {
deposit: Deposit,
repaymentChainId: number,
realizedLpFeePct: BigNumber,
gasPrice: BigNumber
gasPrice?: BigNumber
): string {
let mrkdwn =
this.constructBaseFillMarkdown(deposit, realizedLpFeePct, gasPrice) +
Expand All @@ -1412,7 +1405,7 @@ export class Relayer {
return mrkdwn;
}

private constructBaseFillMarkdown(deposit: Deposit, _realizedLpFeePct: BigNumber, _gasPriceGwei: BigNumber): string {
private constructBaseFillMarkdown(deposit: Deposit, _realizedLpFeePct: BigNumber, gasPrice?: BigNumber): string {
const { symbol, decimals } = this.clients.hubPoolClient.getTokenInfoForDeposit(deposit);
const srcChain = getNetworkName(deposit.originChainId);
const dstChain = getNetworkName(deposit.destinationChainId);
Expand All @@ -1429,11 +1422,14 @@ export class Relayer {
const { symbol: outputTokenSymbol, decimals: outputTokenDecimals } =
this.clients.hubPoolClient.getTokenInfoForAddress(deposit.outputToken, deposit.destinationChainId);
const _outputAmount = createFormatFunction(2, 4, false, outputTokenDecimals)(deposit.outputAmount.toString());

msg +=
` and output ${_outputAmount} ${outputTokenSymbol}, with depositor ${depositor}.` +
` Realized LP fee: ${realizedLpFeePct}%, total fee: ${totalFeePct}%. Gas price used in profit calc: ${formatGwei(
_gasPriceGwei.toString()
)} Gwei.`;
` Realized LP fee: ${realizedLpFeePct}%, total fee: ${totalFeePct}%.`;

if (isDefined(gasPrice)) {
msg += ` Gas price: ${formatGwei(gasPrice.toString())} Gwei.`;
}

return msg;
}
Expand Down
42 changes: 21 additions & 21 deletions test/ProfitClient.ConsiderProfitability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ describe("ProfitClient: Consider relay profit", () => {
const tokenGasCost = nativeGasCost.mul(gasPrice).div(toBN(10).pow(9));

profitClient.setTokenPrice(gasToken.address, gasTokenPriceUsd);
profitClient.setGasCost(chainId, { nativeGasCost, tokenGasCost, gasPrice });
profitClient.setGasCost(chainId, v3DepositTemplate.outputToken, { nativeGasCost, tokenGasCost, gasPrice });

return { nativeGasCost, tokenGasCost, gasPrice, gasTokenPriceUsd };
};
Expand All @@ -103,13 +103,16 @@ describe("ProfitClient: Consider relay profit", () => {

// Quirk: Use the chainId as the gas price in Gwei. This gives a range of
// gas prices to test with, since there's a spread in the chainId numbers.
const gasCost: { [chainId: number]: TransactionCostEstimate } = Object.fromEntries(
const gasCost: { [chainId: number]: { [token: string]: TransactionCostEstimate } } = Object.fromEntries(
chainIds.map((chainId) => {
const nativeGasCost = toBN(100_000); // Assume 100k gas for a single fill
const gasTokenPrice = toBN(chainId);
const gasPrice = gasTokenPrice;
const tokenGasCost = nativeGasCost.mul(gasPrice);
return [chainId, { nativeGasCost, tokenGasCost, gasPrice }];
const _tokenGasCost = nativeGasCost.mul(gasPrice);
const tokenGasCost = Object.fromEntries(
Object.values(tokens).map(({ address }) => [address, { nativeGasCost, tokenGasCost: _tokenGasCost, gasPrice }])
);
return [chainId, tokenGasCost];
})
);

Expand Down Expand Up @@ -260,8 +263,8 @@ describe("ProfitClient: Consider relay profit", () => {

it("Return uint256Max when gas cost fails to be fetched", async () => {
const destinationChainId = 137;
profitClient.setGasCost(destinationChainId, undefined);
const deposit = { ...v3DepositTemplate, destinationChainId };
profitClient.setGasCost(destinationChainId, deposit.outputToken, undefined);
const { nativeGasCost, tokenGasCost } = await profitClient.getTotalGasCost(deposit);
expect(nativeGasCost.eq(uint256Max)).to.be.true;
expect(tokenGasCost.eq(uint256Max)).to.be.true;
Expand All @@ -280,9 +283,9 @@ describe("ProfitClient: Consider relay profit", () => {

spyLogger.debug({ message: `Verify exception on chain ${destinationChainId} gas cost estimation failure.` });
const destinationGasCost = await profitClient.getTotalGasCost(deposit);
profitClient.setGasCost(destinationChainId, undefined);
profitClient.setGasCost(destinationChainId, deposit.outputToken, undefined);
await assertPromiseError(profitClient.calculateFillProfitability(deposit, zeroLPFee, minRelayerFeePct));
profitClient.setGasCost(destinationChainId, destinationGasCost);
profitClient.setGasCost(destinationChainId, deposit.outputToken, destinationGasCost);

spyLogger.debug({ message: `Verifying exception on chain ${destinationChainId} token price lookup failure.` });
const l1TokenPrice = profitClient.getPriceOfToken(l1Token.address);
Expand All @@ -302,11 +305,11 @@ describe("ProfitClient: Consider relay profit", () => {

for (const originChainId of chainIds) {
for (const destinationChainId of chainIds.filter((chainId) => chainId !== originChainId)) {
const { nativeGasCost: baseNativeGasCost, gasPrice } = gasCost[destinationChainId];
const { outputToken } = v3DepositTemplate;

for (const token of Object.values(tokens)) {
const inputToken = randomAddress();
const outputToken = randomAddress();
const { nativeGasCost: baseNativeGasCost, gasPrice } = gasCost[destinationChainId][token.address];

const outputAmount = toBN(1).mul(bn10.pow(token.decimals));
const inputAmount = outputAmount
Expand Down Expand Up @@ -340,7 +343,7 @@ describe("ProfitClient: Consider relay profit", () => {
const nativeGasCost = baseNativeGasCost.mul(gasCostMultiplier).div(fixedPoint);
const tokenGasCost = nativeGasCost.mul(gasPrice);
const gasCostUsd = tokenGasCost.mul(gasTokenPriceUsd).div(fixedPoint);
profitClient.setGasCost(destinationChainId, { nativeGasCost, tokenGasCost, gasPrice });
profitClient.setGasCost(destinationChainId, deposit.outputToken, { nativeGasCost, tokenGasCost, gasPrice });

const gasCostPct = gasCostUsd.mul(fixedPoint).div(outputAmountUsd);

Expand Down Expand Up @@ -375,30 +378,27 @@ describe("ProfitClient: Consider relay profit", () => {

for (const originChainId of chainIds) {
for (const destinationChainId of chainIds.filter((chainId) => chainId !== originChainId)) {
const { tokenGasCost } = gasCost[destinationChainId];
const gasToken = profitClient.resolveGasToken(destinationChainId);
const gasTokenPriceUsd = profitClient.getPriceOfToken(gasToken.symbol);
const gasCostUsd = tokenGasCost.mul(gasTokenPriceUsd).div(bn10.pow(gasToken.decimals));

for (const token of Object.values(tokens)) {
const inputToken = randomAddress();
const outputToken = randomAddress();
const { tokenGasCost } = gasCost[destinationChainId][token.address];
const gasToken = profitClient.resolveGasToken(destinationChainId);
const gasTokenPriceUsd = profitClient.getPriceOfToken(gasToken.symbol);
const gasCostUsd = tokenGasCost.mul(gasTokenPriceUsd).div(bn10.pow(gasToken.decimals));

const outputAmount = toBN(1).mul(bn10.pow(token.decimals));
const outputAmount = bn10.pow(token.decimals);
const inputAmount = outputAmount
.mul(fixedPoint)
.div(fixedPoint.sub(lpFeePct.add(relayerFeePct).add(gasFeePct)));
const deposit = {
...v3DepositTemplate,
originChainId,
destinationChainId,
inputToken,
inputToken: randomAddress(),
inputAmount,
outputToken,
outputToken: token.address,
outputAmount,
};
hubPoolClient.setTokenMapping(token.address, deposit.originChainId, deposit.inputToken);
hubPoolClient.mapTokenInfo(deposit.outputToken, token.symbol, token.decimals);
hubPoolClient.mapTokenInfo(token.address, token.symbol, token.decimals);
const tokenPriceUsd = profitClient.getPriceOfToken(token.symbol);

// Normalise any tokens with <18 decimals to 18 decimals.
Expand Down
Loading
Loading