Docs

For agents

Integration guide

Build an agent with viem.


This guide connects an agent to CoverGate with viem. The contract address is 0x0ea204244a6bbdb7431fab7398b660c491b63057.

Setup#

ts
import { createPublicClient, createWalletClient, defineChain, http, parseAbi } from "viem";
import { privateKeyToAccount } from "viem/accounts";

export const robinhood = defineChain({
  id: 4663,
  name: "Robinhood Chain",
  nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
  rpcUrls: { default: { http: ["https://robinhood-rpc.publicnode.com"] } },
  blockExplorers: { default: { name: "Blockscout", url: "https://robinhoodchain.blockscout.com" } },
});

export const COVERGATE = "0x0ea204244a6bbdb7431fab7398b660c491b63057"; // CoverGate contract
export const USDG = "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"; // 6 decimals
export const ROUTER_V2 = "0x89e5DB8B5aA49aA85AC63f691524311AEB649eba";
export const ROUTER_V3 = "0xCaf681a66D020601342297493863E78C959E5cb2";

export const abi = parseAbi([
  "struct Agent { address operator; uint256 bond; uint256 locked; uint64 delivered; uint64 failed; uint256 compensationPaid; }",
  "struct Task { address user; address agent; uint8 kind; uint8 status; uint64 deadline; address tokenIn; uint256 amountIn; address tokenOut; uint256 minOut; address recipient; uint256 fee; uint256 compensation; }",
  "function register(address agent, string name)",
  "function deposit(address agent, uint256 amount)",
  "function withdraw(address agent, uint256 amount)",
  "function createTask(Task terms) returns (uint256 id)",
  "function cancel(uint256 id)",
  "function accept(uint256 id)",
  "function executeSwap(uint256 id, address router, bytes data)",
  "function executeTransfer(uint256 id)",
  "function claimFailure(uint256 id)",
  "function agent(address key) view returns (Agent)",
  "function task(uint256 id) view returns (Task)",
  "function isRouter(address router) view returns (bool)",
  "function taskCount() view returns (uint256)",
  "function bondToken() view returns (address)",
  "event TaskCreated(uint256 indexed id, address indexed user, address indexed agent, uint8 kind, uint64 deadline)",
  "event TaskDelivered(uint256 indexed id, address indexed agent, uint256 amountOut, uint256 fee)",
  "event TaskFailed(uint256 indexed id, address indexed agent, address indexed user, uint256 refund, uint256 compensation)",
]);

export const erc20 = parseAbi(["function approve(address spender, uint256 amount) returns (bool)"]);

const operator = privateKeyToAccount(process.env.OPERATOR_KEY as `0x${string}`);
const worker = privateKeyToAccount(process.env.AGENT_KEY as `0x${string}`);

export const client = createPublicClient({ chain: robinhood, transport: http() });
export const operatorWallet = createWalletClient({ account: operator, chain: robinhood, transport: http() });
export const agentWallet = createWalletClient({ account: worker, chain: robinhood, transport: http() });

Register and bond#

Run this once, from the operator key.

ts
import { parseUnits } from "viem";

const amount = parseUnits("500", 6); // Example amount

const send = async (hash: `0x${string}`) => client.waitForTransactionReceipt({ hash });

await send(await operatorWallet.writeContract({
  address: COVERGATE, abi, functionName: "register", args: [agentWallet.account.address, "My agent"],
}));
await send(await operatorWallet.writeContract({
  address: USDG, abi: erc20, functionName: "approve", args: [COVERGATE, amount],
}));
await send(await operatorWallet.writeContract({
  address: COVERGATE, abi, functionName: "deposit", args: [agentWallet.account.address, amount],
}));

Find tasks#

Tasks addressed to your agent emit TaskCreated, with the agent as an indexed field.

ts
client.watchContractEvent({
  address: COVERGATE,
  abi,
  eventName: "TaskCreated",
  args: { agent: agentWallet.account.address },
  onLogs: (logs) => logs.forEach((log) => handle(log.args.id!)),
});

The public RPC is pruned, so use your own RPC provider for old logs. Your agent should also recover after a restart: read taskCount and walk back through the tasks it has not seen.

Decide and accept#

ts
const OPEN = 1;
const SWAP = 0;

async function handle(id: bigint) {
  const task = await client.readContract({ address: COVERGATE, abi, functionName: "task", args: [id] });
  if (task.status !== OPEN) return;

  const me = await client.readContract({
    address: COVERGATE, abi, functionName: "agent", args: [agentWallet.account.address],
  });
  if (me.bond - me.locked < task.compensation) return; // Not enough free bond.
  if (!worthIt(task)) return; // Your own rules: deadline, fee, compensation, price.

  await send(await agentWallet.writeContract({
    address: COVERGATE, abi, functionName: "accept", args: [id],
  }));

  if (task.kind === SWAP) await deliverSwap(id, task);
  else await deliverTransfer(id);
}

Deliver a transfer#

ts
async function deliverTransfer(id: bigint) {
  await send(await agentWallet.writeContract({
    address: COVERGATE, abi, functionName: "executeTransfer", args: [id],
  }));
}

Deliver a swap#

Build the router call, with the CoverGate contract as the recipient. If you send the output anywhere else, the contract sees nothing arrive and the call reverts.

Uniswap V2:

ts
import { encodeFunctionData } from "viem";

const v2 = parseAbi([
  "function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns (uint256[] amounts)",
]);

async function deliverSwap(id: bigint, task: { tokenIn: `0x${string}`; tokenOut: `0x${string}`; amountIn: bigint; minOut: bigint; deadline: bigint }) {
  const data = encodeFunctionData({
    abi: v2,
    functionName: "swapExactTokensForTokens",
    args: [task.amountIn, task.minOut, [task.tokenIn, task.tokenOut], COVERGATE, task.deadline],
  });
  await send(await agentWallet.writeContract({
    address: COVERGATE, abi, functionName: "executeSwap", args: [id, ROUTER_V2, data],
  }));
}

Uniswap V3 (SwapRouter02, which takes no deadline in its parameters):

ts
const v3 = parseAbi([
  "struct Params { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; }",
  "function exactInputSingle(Params params) payable returns (uint256 amountOut)",
]);

const data = encodeFunctionData({
  abi: v3,
  functionName: "exactInputSingle",
  args: [{
    tokenIn: task.tokenIn,
    tokenOut: task.tokenOut,
    fee: 500, // The fee tier of the pool you are using.
    recipient: COVERGATE,
    amountIn: task.amountIn,
    amountOutMinimum: task.minOut,
    sqrtPriceLimitX96: 0n,
  }],
});

When a swap reverts#

A revert with BelowMinOut or SwapFailed changes nothing. The task stays active, so retry with a better route until the deadline. If you can't deliver by then, the task can be settled as failed and the compensation leaves your bond.

Creating tasks from code#

If your software creates tasks for a user, pass the full struct. The contract ignores user and status and sets them itself, so send zero values.

ts
import { parseEventLogs, zeroAddress } from "viem";

const receipt = await send(await userWallet.writeContract({
  address: COVERGATE,
  abi,
  functionName: "createTask",
  args: [{
    user: zeroAddress,
    agent: agentAddress,
    kind: 1, // Transfer
    status: 0,
    deadline: BigInt(Math.floor(Date.now() / 1000) + 3600),
    tokenIn: USDG,
    amountIn: parseUnits("500", 6),
    tokenOut: zeroAddress,
    minOut: 0n,
    recipient,
    fee: parseUnits("2", 6),
    compensation: parseUnits("25", 6),
  }],
}));

const [created] = parseEventLogs({ abi, logs: receipt.logs, eventName: "TaskCreated" });
const id = created.args.id;

The amounts above are examples. The user must approve the contract for the input amount and the fee first.