|
| 1 | +import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum'; |
| 2 | +import type { AztecNode } from '@aztec/aztec.js/node'; |
| 3 | +import { createEthereumChain } from '@aztec/ethereum/chain'; |
| 4 | +import { createExtendedL1Client } from '@aztec/ethereum/client'; |
| 5 | +import { Fr } from '@aztec/aztec.js/fields'; |
| 6 | +import { ProtocolContractAddress } from '@aztec/aztec.js/protocol'; |
| 7 | +import { getNonNullifiedL1ToL2MessageWitness } from '@aztec/stdlib/messaging'; |
| 8 | +import { FeeAssetHandlerAbi } from '@aztec/l1-artifacts/FeeAssetHandlerAbi'; |
| 9 | +import type { AztecAddress } from '@aztec/aztec.js/addresses'; |
| 10 | +import type { Logger } from '@aztec/foundation/log'; |
| 11 | +import { getContract } from 'viem'; |
| 12 | +import configManager from '../../config/config.js'; |
| 13 | + |
| 14 | +const MAX_POLL_ATTEMPTS = 40; // 40 * 30s = 20 minutes max |
| 15 | + |
| 16 | +export async function bridgeL1FeeJuice( |
| 17 | + node: AztecNode, |
| 18 | + recipient: AztecAddress, |
| 19 | + amount: bigint, |
| 20 | + logger: Logger, |
| 21 | +) { |
| 22 | + const { l1RpcUrl, l1ChainId } = configManager.getNetworkConfig(); |
| 23 | + const l1PrivateKey = process.env.L1_PRIVATE_KEY; |
| 24 | + |
| 25 | + if (!l1PrivateKey) { |
| 26 | + throw new Error('L1_PRIVATE_KEY env var is required for testnet fee juice bridging. Must be a Sepolia-funded private key prefixed with 0x.'); |
| 27 | + } |
| 28 | + |
| 29 | + const key = l1PrivateKey.startsWith('0x') ? l1PrivateKey : `0x${l1PrivateKey}`; |
| 30 | + const chain = createEthereumChain([l1RpcUrl], l1ChainId); |
| 31 | + |
| 32 | + logger.info(`🌉 Bridging ${amount} fee juice from L1 to ${recipient}...`); |
| 33 | + |
| 34 | + const l1Client = createExtendedL1Client(chain.rpcUrls, key, chain.chainInfo); |
| 35 | + const portal = await L1FeeJuicePortalManager.new(node, l1Client, logger); |
| 36 | + const tokenManager = portal.getTokenManager(); |
| 37 | + |
| 38 | + // Check if we already have enough tokens on L1 |
| 39 | + const balance = await tokenManager.getL1TokenBalance(l1Client.account.address); |
| 40 | + if (balance < amount) { |
| 41 | + // Mint tokens and wait for confirmation. |
| 42 | + // Upstream L1TokenManager.mint() doesn't wait for the tx receipt, |
| 43 | + // causing nonce conflicts with the subsequent approve transaction. |
| 44 | + logger.info(`🪙 Minting fee juice tokens on L1...`); |
| 45 | + const handler = getContract({ |
| 46 | + address: tokenManager.handlerAddress!.toString() as `0x${string}`, |
| 47 | + abi: FeeAssetHandlerAbi, |
| 48 | + client: l1Client, |
| 49 | + }); |
| 50 | + const mintHash = await handler.write.mint([l1Client.account.address]); |
| 51 | + logger.info(`⏳ Waiting for mint tx to confirm: ${mintHash}`); |
| 52 | + await l1Client.waitForTransactionReceipt({ hash: mintHash }); |
| 53 | + logger.info(`✅ Mint confirmed on L1`); |
| 54 | + } else { |
| 55 | + logger.info(`💰 L1 account already has ${balance} tokens, skipping mint`); |
| 56 | + } |
| 57 | + |
| 58 | + // Create a fresh L1 client so viem picks up the current on-chain nonce. |
| 59 | + // The mint (or prior runs) may have incremented it beyond what the |
| 60 | + // original client has cached. Public RPC nodes may have eventual consistency, |
| 61 | + // so wait briefly for the nonce to propagate. |
| 62 | + await new Promise(resolve => setTimeout(resolve, 3_000)); |
| 63 | + const freshClient = createExtendedL1Client(chain.rpcUrls, key, chain.chainInfo); |
| 64 | + const freshPortal = await L1FeeJuicePortalManager.new(node, freshClient, logger); |
| 65 | + const claim = await freshPortal.bridgeTokensPublic(recipient, amount, false); |
| 66 | + |
| 67 | + logger.info(`✅ Fee juice bridged! Claim amount: ${claim.claimAmount}, message hash: ${claim.messageHash}`); |
| 68 | + logger.info(`⏳ Waiting for L1-to-L2 message to be available on L2...`); |
| 69 | + |
| 70 | + const pollInterval = 30_000; |
| 71 | + for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt++) { |
| 72 | + const witness = await getNonNullifiedL1ToL2MessageWitness( |
| 73 | + node, |
| 74 | + ProtocolContractAddress.FeeJuice, |
| 75 | + Fr.fromHexString(claim.messageHash), |
| 76 | + claim.claimSecret, |
| 77 | + ).catch(() => undefined); |
| 78 | + |
| 79 | + if (witness) { |
| 80 | + logger.info(`✅ L1-to-L2 message is available on L2!`); |
| 81 | + return claim; |
| 82 | + } |
| 83 | + |
| 84 | + logger.info(`⏳ Message not yet available, checking again in ${pollInterval / 1000}s... (${attempt + 1}/${MAX_POLL_ATTEMPTS})`); |
| 85 | + await new Promise(resolve => setTimeout(resolve, pollInterval)); |
| 86 | + } |
| 87 | + |
| 88 | + throw new Error(`L1-to-L2 message not available after ${MAX_POLL_ATTEMPTS} attempts (${MAX_POLL_ATTEMPTS * 30}s)`); |
| 89 | +} |
0 commit comments