async function executePartialRecovery(
status,
originalQuote,
walletClient,
publicClient,
userAddress
) {
// 1. Extract what was received
const received = extractReceivedToken(status);
const intended = originalQuote.action.toToken;
console.log('Partial completion detected');
console.log(`Received: ${received.amount} ${received.symbol}`);
console.log(`Intended: ${intended.symbol}`);
// 2. Check if we need to recover (did user already get intended token?)
if (received.address.toLowerCase() === intended.address.toLowerCase()) {
console.log('Already received intended token - no recovery needed');
return { success: true, recovered: false };
}
// 3. Get recovery quote
console.log('Getting recovery swap quote...');
const recoveryQuote = await getRecoveryQuote(status, originalQuote, userAddress);
// 4. Check if recovery is worthwhile (accounting for gas)
const gasCostEstimate = estimateGasCost(recoveryQuote);
const swapValue = estimateSwapValue(recoveryQuote);
if (gasCostEstimate > swapValue * 0.1) {
console.log('Gas cost too high relative to swap value');
console.log('Recommend keeping received token');
return {
success: true,
recovered: false,
reason: 'Gas cost exceeds 10% of swap value'
};
}
// 5. Execute recovery swap
console.log('Executing recovery swap...');
// Handle approval if needed
await ensureApproval(recoveryQuote, walletClient, publicClient);
// Execute swap
const { hash } = await executeTransaction(
walletClient,
publicClient,
recoveryQuote.transactionRequest
);
console.log(`Recovery swap sent: ${hash}`);
// 6. Poll recovery status (same-chain is usually fast)
const recoveryResult = await pollTransferStatus({
txHash: hash,
bridge: recoveryQuote.tool,
fromChain: received.chainId,
toChain: received.chainId
}, {
maxDuration: 5 * 60 * 1000 // 5 minutes for same-chain
});
return {
success: recoveryResult.success,
recovered: true,
recoveryTxHash: hash,
finalStatus: recoveryResult.status
};
}