import { withPaymentInterceptor } from 'x402-axios';
import { createWalletClient, http, privateKeyToAccount } from 'viem';
import { base } from 'viem/chains';
import axios from 'axios';
class SwapExecutor {
constructor(privateKey) {
this.walletClient = createWalletClient({
chain: base,
transport: http(),
account: privateKeyToAccount(privateKey)
});
this.client = withPaymentInterceptor(
axios.create({ baseURL: 'http://localhost:3002' }),
this.walletClient
);
}
async executeSwap(params) {
// First do dry run to check estimate
const dryRun = await this.client.post('/api/execute_swap', {
...params, dry_run: true
});
console.log('Estimated output:', dryRun.data.tasks[0].estimate);
// Execute real swap
const result = await this.client.post('/api/execute_swap', {
...params, dry_run: false
});
// Monitor and sign transaction
return this.monitorPipeline(result.data.pipeline_id);
}
async monitorPipeline(pipelineId) {
while (true) {
const status = await this.client.post('/api/get_transaction_status', {
pipeline_id: pipelineId
});
const task = status.data.tasks[0];
if (task.status === 'sign_pending') {
const hash = await this.walletClient.sendTransaction(task.tx_data);
console.log('Transaction sent:', hash);
} else if (task.status === 'success') {
console.log('Swap completed!');
return status.data;
} else if (task.status === 'failed') {
throw new Error('Transaction failed: ' + task.error);
}
await new Promise(r => setTimeout(r, 2000));
}
}
}
// Usage
const executor = new SwapExecutor(process.env.PRIVATE_KEY);
await executor.executeSwap({
from_chain: 'base',
from_token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
from_amount: '10',
to_chain: 'base',
to_token: '0x4200000000000000000000000000000000000006',
wallet_address: executor.walletClient.account.address,
slippage: 2.0
});