async function ensurePermit2Approval(signer, tokenAddress, spender, requiredAmount) {
const permit2 = new ethers.Contract(PERMIT2_ADDRESS, PERMIT2_ABI, signer);
const owner = await signer.getAddress();
// 1. 检查现有的 Permit2 子授权
const [amount, expiration] = await permit2.allowance(owner, tokenAddress, spender);
const now = Math.floor(Date.now() / 1000);
if (amount >= requiredAmount && expiration > now) {
return; // 已授权
}
// 2. 检查对 Permit2 的 ERC-20 授权
const token = new ethers.Contract(tokenAddress, ERC20_ABI, signer);
const tokenAllowance = await token.allowance(owner, PERMIT2_ADDRESS);
if (tokenAllowance < requiredAmount) {
const tx = await token.approve(PERMIT2_ADDRESS, ethers.MaxUint256);
await tx.wait();
}
// 3. 授予 Permit2 子授权
const tx = await permit2.approve(
tokenAddress,
spender,
ethers.MaxUint160,
now + 365 * 86400
);
await tx.wait();
}