EVM Example#
Create an Approval#
// approval.ts
import { client } from './DexClient';
// Helper function to convert human-readable amounts to base units
export function toBaseUnits(amount: string, decimals: number): string {
// Remove any decimal point and count the decimal places
const [integerPart, decimalPart = ''] = amount.split('.');
const currentDecimals = decimalPart.length;
// Combine integer and decimal parts, removing the decimal point
let result = integerPart + decimalPart;
// Add zeros if we need more decimal places
if (currentDecimals < decimals) {
result = result + '0'.repeat(decimals - currentDecimals);
}
// Remove digits if we have too many decimal places
else if (currentDecimals > decimals) {
result = result.slice(0, result.length - (currentDecimals - decimals));
}
// Remove leading zeros
result = result.replace(/^0+/, '') || '0';
return result;
}
/**
* Example: Approve a token for swapping
*/
async function executeApproval(tokenAddress: string, amount: string) {
try {
// Get token information using quote
console.log("Getting token information...");
const tokenInfo = await client.dex.getQuote({
chainId: '8453', // Base Chain
fromTokenAddress: tokenAddress,
toTokenAddress: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', // Native token
amount: '1000000', // Use a reasonable amount for quote
slippage: '0.5'
});
const tokenDecimals = parseInt(tokenInfo.data[0].fromToken.decimal);
const rawAmount = toBaseUnits(amount, tokenDecimals);
console.log(`\nApproval Details:`);
console.log(`--------------------`);
console.log(`Token: ${tokenInfo.data[0].fromToken.tokenSymbol}`);
console.log(`Amount: ${amount} ${tokenInfo.data[0].fromToken.tokenSymbol}`);
console.log(`Amount in base units: ${rawAmount}`);
// Execute the approval
console.log("\nExecuting approval...");
const result = await client.dex.executeApproval({
chainId: '8453', // Base Chain
tokenContractAddress: tokenAddress,
approveAmount: rawAmount
});
if ('alreadyApproved' in result) {
console.log("\nToken already approved for the requested amount!");
return { success: true, alreadyApproved: true };
} else {
console.log("\nApproval completed successfully!");
console.log("Transaction Hash:", result.transactionHash);
console.log("Explorer URL:", result.explorerUrl);
return result;
}
} catch (error) {
if (error instanceof Error) {
console.error('Error executing approval:', error.message);
}
throw error;
}
}
// Run if this file is executed directly
if (require.main === module) {
// Example usage: ts-node approval.ts 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 1000
const args = process.argv.slice(2);
if (args.length !== 2) {
console.log("Usage: ts-node approval.ts <tokenAddress> <amountToApprove>");
console.log("\nExamples:");
console.log(" # Approve 1000 USDC");
console.log(` ts-node approval.ts 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 1000`);
process.exit(1);
}
const [tokenAddress, amount] = args;
executeApproval(tokenAddress, amount)
.then(() => process.exit(0))
.catch((error) => {
console.error('Error:', error);
process.exit(1);
});
}
export { executeApproval };
Create a Swap#
// swap.ts
import { client } from './DexClient';
/**
* Example: Execute a swap from ETH to USDC on Base chain
*/
async function executeSwap() {
try {
if (!process.env.EVM_PRIVATE_KEY) {
throw new Error('Missing EVM_PRIVATE_KEY in .env file');
}
// You can change this to any EVM chain
// For example, for Base, use chainId: '8453'
// For example, for baseSepolia, use chainId: '84532'
// You can also use SUI, use chainId: '784'
// When using another Chain, you need to change the fromTokenAddress and toTokenAddress to the correct addresses for that chain
const swapResult = await client.dex.executeSwap({
chainId: '8453', // Base chain ID
fromTokenAddress: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', // Native ETH
toTokenAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC on Base
amount: String(10 * 10 ** 14), // .0001 ETH
slippage: '0.5', // 0.5% slippage
userWalletAddress: process.env.EVM_WALLET_ADDRESS!
});
console.log('Swap executed successfully:');
console.log(JSON.stringify(swapResult, null, 2));
return swapResult;
} catch (error) {
if (error instanceof Error) {
console.error('Error executing swap:', error.message);
// API errors include details in the message
if (error.message.includes('API Error:')) {
const match = error.message.match(/API Error: (.*)/);
if (match) console.error('API Error Details:', match[1]);
}
}
throw error;
}
}
// Run if this file is executed directly
if (require.main === module) {
executeSwap()
.then(() => process.exit(0))
.catch((error) => {
console.error('Error:', error);
process.exit(1);
});
}
export { executeSwap };
Get a Quote#
const quote = await client.dex.getQuote({
chainId: '8453', // Base Chain
fromTokenAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC
toTokenAddress: '0x4200000000000000000000000000000000000006', // WETH
amount: '1000000', // 1 USDC (in smallest units)
slippage: '0.5' // 0.5%
});
Table of contents