import { ethers } from 'ethers';
import axios from 'axios';
const API_URL = 'https://li.quest/v1';
// 配置
const PRIVATE_KEY = 'YOUR_PRIVATE_KEY';
const RPC_URL = 'https://mainnet.base.org';
const signer = new ethers.Wallet(PRIVATE_KEY, new ethers.JsonRpcProvider(RPC_URL));
// 获取报价
async function getComposerQuote(fromAddress: string) {
const response = await axios.get(`${API_URL}/quote`, {
params: {
fromChain: 8453,
toChain: 8453,
fromToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
toToken: '0x7BfA7C4f149E7415b73bdeDfe609237e29CBF34A',
fromAmount: '1000000',
fromAddress,
toAddress: fromAddress,
},
});
return response.data;
}
// 设置授权
async function ensureAllowance(tokenAddress: string, approvalAddress: string, amount: string) {
const ERC20_ABI = ['function approve(address, uint256)', 'function allowance(address, address) view returns (uint256)'];
const erc20 = new ethers.Contract(tokenAddress, ERC20_ABI, signer);
const address = await signer.getAddress();
const allowance = await erc20.allowance(address, approvalAddress);
if (allowance < BigInt(amount)) {
const tx = await erc20.approve(approvalAddress, amount);
await tx.wait();
console.log('授权已设置');
}
}
// 主函数
async function main() {
const address = await signer.getAddress();
try {
// 1. 获取报价
const quote = await getComposerQuote(address);
console.log('收到报价,工具:', quote.tool);
// 2. 设置授权
await ensureAllowance(
quote.action.fromToken.address,
quote.estimate.approvalAddress,
quote.action.fromAmount
);
// 3. 执行交易
const tx = await signer.sendTransaction(quote.transactionRequest);
console.log('交易已发送:', tx.hash);
const receipt = await tx.wait();
console.log('交易已确认:', receipt.transactionHash);
} catch (error) {
console.error('错误:', error.response?.data || error.message);
}
}
main();