Basic Swap Agent

A simple agent that swaps all USDC to wSOL on Polygon.

Example

import { Agent, type AgentContext, type CurrentPosition } from "@circuitorg/agent-sdk";

// Polygon addresses
const USDC = "0x2791bca1f2de4661ed88a30c99a7a9449aa84174";
const WSOL = "0xd93f7e271cb87c23aaa73edc008a79646d1f9912";

async function run(agent: AgentContext): Promise<void> {
  // Find USDC balance
  const usdc = agent.currentPositions.find(p => p.assetAddress === USDC);
  if (!usdc || parseInt(usdc.currentQty) === 0) {
    await agent.log("No USDC to swap");
    return;
  }
  
  // Get quote
  const quote = await agent.swidge.quote({
    from: { network: "ethereum:137", address: agent.sessionWalletAddress },
    to: { network: "ethereum:137", address: agent.sessionWalletAddress },
    amount: usdc.currentQty, // Amount in raw units, 1 USDC would be 1000000 for example
    fromToken: USDC,
    toToken: WSOL, // Omit this if you want to swap to a native token for the given to field's network
    slippage: "10.0"
  });
  
  if (!quote.success || !quote.data) {
    await agent.log(`Quote failed: ${quote.error}`);
    return;
  }
  
  // Execute swap
  const result = await agent.swidge.execute(quote.data);
  if (result.success) {
    await agent.log("Swap completed!");
  } else {
    await agent.log(`Swap failed: ${result.error}`);
  }
}

async function unwind(agent: AgentContext, positions: CurrentPosition[]): Promise<void> {
  await agent.log(`Unwind requested for ${positions.length} positions`);
  // Add unwind logic here to unwind every item in the `positions` parameter
}

const agent = new Agent({
  runFunction: run,
  unwindFunction: unwind,
});

export default agent.getHandler();

How It Works

  1. Check positions: Finds USDC in agent.currentPositions

  2. Get quote: Requests a swap quote from USDC to wSOL

  3. Execute: Executes the swap if the quote succeeds

Last updated