import { readFile } from 'node:fs/promises'; const [file] = process.argv.slice(2); if (!file) throw new Error('Usage: node prepare-payout-ledger.mjs ledger.json'); const ledger = JSON.parse(await readFile(file, 'utf8')); const hash = /^0x[0-9a-f]{64}$/i; if (!Array.isArray(ledger) || ledger.length < 1 || ledger.length > 200 || ledger.some(row => typeof row?.transaction_hash !== 'string' || !hash.test(row.transaction_hash))) { throw new Error('Supply an array of 1 to 200 payout rows with valid transaction hashes.'); } const expected = ledger.map(({ reference, transaction_hash, log_index, recipient, amount_micros }) => ({ reference, transaction_hash, log_index, recipient, amount_micros })); const endpoint = process.env.PAYOUT_BASE_RPC || 'https://mainnet.base.org'; const usdc = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'; const transfer = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'; let id = 0; async function rpc(method, params = []) { const requestId = ++id; const response = await fetch(endpoint, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(12000), headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: requestId, method, params }), }); if (!response.ok) throw new Error(`Base RPC returned HTTP ${response.status} for ${method}.`); const reply = await response.json(); if (reply.id !== requestId || reply.result === undefined || reply.error) { throw new Error(`Base RPC did not return a valid result for ${method}.`); } return reply.result; } if (await rpc('eth_chainId') !== '0x2105') throw new Error('The RPC must serve Base mainnet.'); const finalized = await rpc('eth_getBlockByNumber', ['finalized', false]); if (typeof finalized?.number !== 'string') throw new Error('The RPC must provide the latest finalized Base block.'); const receipts = []; const transactions = new Set(expected.map(row => row.transaction_hash.toLowerCase())); for (const transaction of transactions) { const receipt = await rpc('eth_getTransactionReceipt', [transaction]); if (receipt === null) { console.error(`No receipt returned for ${transaction}.`); continue; } if (receipt.transactionHash?.toLowerCase() !== transaction || typeof receipt.blockNumber !== 'string' || !['0x0', '0x1'].includes(receipt.status) || !Array.isArray(receipt.logs)) { throw new Error(`Invalid receipt for ${transaction}.`); } if (BigInt(receipt.blockNumber) > BigInt(finalized.number)) { throw new Error(`Receipt is newer than the RPC's finalized block: ${transaction}.`); } const { transactionHash, status, logs } = receipt; const usdcTransfers = logs.filter(log => log.address?.toLowerCase() === usdc && log.topics?.[0]?.toLowerCase() === transfer) .map(({ address, topics, data, logIndex, removed, transactionHash }) => ({ address, topics, data, logIndex, removed, transactionHash })); receipts.push({ transactionHash, status, logs: usdcTransfers }); } process.stdout.write(JSON.stringify({ expected, receipts }) + '\n');