Skip to content
ON CHAIN
Menu

How Intent-Based Cross-Chain Swaps Work, and How to Build One Safely

Instead of routing a swap through a bridge step by step, the user signs what they want and solvers compete to deliver it. Here is how that works, and the safety checks that matter most.

By OnChain Team9 min read

In an intent-based cross-chain swap, the user does not execute a route. They sign a message that says what they want, for example "1,000 USDC on Ethereum for at least 6.95 SOL on Solana, delivered before this deadline", and lock the input in an escrow. A solver delivers the output to the user on the destination chain from its own funds, then proves the fill and is repaid from the escrow. The user's signed minimum is the floor: no solver can be paid for delivering less. This guide explains the moving parts and builds a simplified version of each: the signed intent, the escrow, the fill and a front end that checks everything before asking for a signature.

The contracts below are deliberately small and not audited. They show the mechanics; a production system needs an audit and a proper cross-chain verification layer.

Why intents instead of routes?

A route-based bridge asks the user to approve and sign each hop, and the user carries the risk of every step. With intents, the user signs once and gets either the promised output or their money back. Solvers, who hold inventory on many chains, take on execution and price risk, and compete on price. The trade-off is that you now depend on a settlement mechanism that can prove what happened on another chain.

ERC-7683 standardises the interfaces for cross-chain intents so different solver networks can fill the same orders. The example below follows the same ideas with simpler types.

The lifecycle

One signature on the origin chain, delivery on the destination chain
ORIGIN CHAINDESTINATION CHAINUSERUserSigns one intentAppPinned-contractchecksON-CHAINEscrowLocks input, checksminimumEXTERNALSolverCompetes to fillON-CHAINFill recorderPays the userUSERUser walletReceives the outputEXTERNALVerifierProves the fillsign EIP-712open()order visiblefill()output tokensFilled eventsettle(): repay solverrefund if unfilled

Main flowSecondaryFailure pathSwipe to see the whole diagram →

Step 1: Define the intent as typed data

EIP-712 lets wallets show users a readable summary of what they are signing, instead of an opaque hash. Recipient and output token are bytes32 so they can hold non-EVM addresses, such as a 32-byte Solana public key.

src/IntentTypes.solSolidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

struct Intent {
    address user;
    address inputToken;
    uint256 inputAmount;
    uint256 destinationChainId;
    bytes32 outputToken;
    uint256 minOutputAmount;
    bytes32 recipient;
    uint64 fillDeadline;
    uint256 nonce;
}

Step 2: Build the escrow on the origin chain

The escrow verifies the signature, pulls the input, and later releases it to the solver or back to the user.

src/IntentEscrow.solSolidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Intent} from "./IntentTypes.sol";

/// Illustrative example. Not audited.
contract IntentEscrow is EIP712, ReentrancyGuard {
    using SafeERC20 for IERC20;

    bytes32 public constant INTENT_TYPEHASH = keccak256(
        "Intent(address user,address inputToken,uint256 inputAmount,"
        "uint256 destinationChainId,bytes32 outputToken,uint256 minOutputAmount,"
        "bytes32 recipient,uint64 fillDeadline,uint256 nonce)"
    );
    uint64 public constant REFUND_GRACE = 1 hours; // gives a slow proof time to arrive

    enum Status {
        None,
        Open,
        Settled,
        Refunded
    }

    address public immutable verifier; // attests fills from the destination chain
    mapping(bytes32 => Status) public status;
    mapping(address => mapping(uint256 => bool)) public nonceUsed;

    event Opened(
        bytes32 indexed orderId,
        address indexed user,
        uint256 inputAmount,
        uint256 minOutputAmount
    );
    event Settled(
        bytes32 indexed orderId,
        address indexed solver,
        uint256 filledAmount
    );
    event Refunded(bytes32 indexed orderId);

    error BadSignature();
    error Expired();
    error NonceUsed();
    error WrongStatus();
    error NotVerifier();
    error UnderFilled();
    error WrongRecipient();
    error TooEarly();

    constructor(address verifier_) EIP712("IntentEscrow", "1") {
        verifier = verifier_;
    }

    function orderId(Intent calldata i) public view returns (bytes32) {
        return
            _hashTypedDataV4(
                keccak256(
                    abi.encode(
                        INTENT_TYPEHASH,
                        i.user,
                        i.inputToken,
                        i.inputAmount,
                        i.destinationChainId,
                        i.outputToken,
                        i.minOutputAmount,
                        i.recipient,
                        i.fillDeadline,
                        i.nonce
                    )
                )
            );
    }

    /// Anyone may submit the signed intent, so a relayer can pay the gas.
    /// The user must have approved this contract to spend inputAmount.
    function open(
        Intent calldata i,
        bytes calldata signature
    ) external nonReentrant returns (bytes32 id) {
        if (block.timestamp > i.fillDeadline) revert Expired();
        if (nonceUsed[i.user][i.nonce]) revert NonceUsed();
        id = orderId(i);
        if (ECDSA.recover(id, signature) != i.user) revert BadSignature();

        nonceUsed[i.user][i.nonce] = true;
        status[id] = Status.Open;
        IERC20(i.inputToken).safeTransferFrom(i.user, address(this), i.inputAmount);
        emit Opened(id, i.user, i.inputAmount, i.minOutputAmount);
    }

    /// Called by the verifier once the fill is proven on the destination chain.
    /// The minimum is enforced here, against the amount that was actually delivered.
    function settle(
        Intent calldata i,
        address solver,
        uint256 filledAmount,
        bytes32 filledRecipient
    ) external nonReentrant {
        if (msg.sender != verifier) revert NotVerifier();
        bytes32 id = orderId(i);
        if (status[id] != Status.Open) revert WrongStatus();
        if (filledAmount < i.minOutputAmount) revert UnderFilled();
        if (filledRecipient != i.recipient) revert WrongRecipient();

        status[id] = Status.Settled;
        IERC20(i.inputToken).safeTransfer(solver, i.inputAmount);
        emit Settled(id, solver, filledAmount);
    }

    /// If no fill is proven in time, the input goes back to the user.
    function refund(Intent calldata i) external nonReentrant {
        bytes32 id = orderId(i);
        if (status[id] != Status.Open) revert WrongStatus();
        if (block.timestamp <= i.fillDeadline + REFUND_GRACE) revert TooEarly();

        status[id] = Status.Refunded;
        IERC20(i.inputToken).safeTransfer(i.user, i.inputAmount);
        emit Refunded(id);
    }
}

The order ID is the EIP-712 digest, so it already commits to the chain ID and this contract's address. A signature for one deployment cannot be replayed on another.

Step 3: Record the fill on the destination chain

The solver delivers the output directly to the user and emits an event the verifier can prove. This contract never holds funds.

src/FillRecorder.sol (deployed on each EVM destination chain)Solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

contract FillRecorder {
    using SafeERC20 for IERC20;

    mapping(bytes32 => bool) public filled;

    event Filled(
        bytes32 indexed orderId,
        address indexed solver,
        address token,
        uint256 amount,
        bytes32 recipient
    );

    error AlreadyFilled();

    function fill(
        bytes32 orderId,
        IERC20 token,
        uint256 amount,
        address recipient
    ) external {
        if (filled[orderId]) revert AlreadyFilled();
        filled[orderId] = true;
        // solver pays from its own inventory
        token.safeTransferFrom(msg.sender, recipient, amount);
        emit Filled(
            orderId,
            msg.sender,
            address(token),
            amount,
            bytes32(uint256(uint160(recipient)))
        );
    }
}

For a non-EVM destination such as Solana, the same role is played by a program that transfers the tokens and records the order ID.

Step 4: Choose how fills are proven

This is the hardest design decision, and it determines your security. The verifier in the escrow can be:

Approach How it works Trade-off
Trusted attester A known party watches fills and calls settle Simple and fast, but users trust that party
Optimistic A claim is accepted unless someone disputes it within a window Trust-minimised, but solvers wait for the window
Messaging protocol A cross-chain messaging network delivers the fill event Depends on that network's own security model

Whatever you choose, notice that the escrow re-checks the amount and recipient itself. A verifier can only report what happened; it cannot pay a solver for a fill below the user's minimum.

Step 5: Sign the intent in the front end

With viem, signing typed data is one call. The wallet shows the user every field.

sign-intent.tsTypeScript
import { createWalletClient, custom, bytesToHex } from "viem";
import { mainnet } from "viem/chains";
import bs58 from "bs58";

const walletClient = createWalletClient({
  chain: mainnet,
  transport: custom(window.ethereum!),
});

const types = {
  Intent: [
    { name: "user", type: "address" },
    { name: "inputToken", type: "address" },
    { name: "inputAmount", type: "uint256" },
    { name: "destinationChainId", type: "uint256" },
    { name: "outputToken", type: "bytes32" },
    { name: "minOutputAmount", type: "uint256" },
    { name: "recipient", type: "bytes32" },
    { name: "fillDeadline", type: "uint64" },
    { name: "nonce", type: "uint256" },
  ],
} as const;

export async function signIntent(quote: {
  escrow: `0x${string}`;
  inputToken: `0x${string}`;
  inputAmount: bigint;
  destinationChainId: bigint;
  outputMint: string; // Solana mint address
  minOutputAmount: bigint;
  solanaRecipient: string; // Solana wallet address
}) {
  const [user] = await walletClient.requestAddresses();
  const message = {
    user,
    inputToken: quote.inputToken,
    inputAmount: quote.inputAmount,
    destinationChainId: quote.destinationChainId,
    outputToken: bytesToHex(bs58.decode(quote.outputMint)), // 32 bytes
    minOutputAmount: quote.minOutputAmount,
    recipient: bytesToHex(bs58.decode(quote.solanaRecipient)),
    fillDeadline: BigInt(Math.floor(Date.now() / 1000) + 10 * 60),
    nonce: BigInt(Date.now()), // use a nonce your backend tracks per user in production
  };

  const signature = await walletClient.signTypedData({
    account: user,
    domain: {
      name: "IntentEscrow",
      version: "1",
      chainId: mainnet.id,
      verifyingContract: quote.escrow,
    },
    types,
    primaryType: "Intent",
    message,
  });
  return { message, signature };
}

Step 6: Check before you ask for a signature

The front end is the user's last line of defence. A compromised API, a malicious script or a bug can all serve a quote that points funds somewhere else. Check the quote against values built into your app before the wallet ever opens.

safety.tsTypeScript
const PINNED: Record<number, { escrow: `0x${string}`; tokens: `0x${string}`[] }> = {
  1: {
    escrow: "0xYourAuditedEscrowAddress",
    tokens: ["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"], // USDC on Ethereum
  },
};

export function assertSafeQuote(
  chainId: number,
  quote: {
    escrow: string;
    inputToken: string;
    minOutputAmount: bigint;
    expectedOutputAmount: bigint;
  },
  maxSlippageBps = 100n,
) {
  const pinned = PINNED[chainId];
  if (!pinned) throw new Error(`Unsupported chain ${chainId}`);
  if (quote.escrow.toLowerCase() !== pinned.escrow.toLowerCase())
    throw new Error("Escrow address mismatch");
  if (!pinned.tokens.some((t) => t.toLowerCase() === quote.inputToken.toLowerCase())) {
    throw new Error("Token not on the allow list");
  }
  // The signed minimum must not sit far below what the user was shown
  const floor = (quote.expectedOutputAmount * (10_000n - maxSlippageBps)) / 10_000n;
  if (quote.minOutputAmount < floor)
    throw new Error("Minimum output is below the allowed slippage");
}

Ship the pinned list with your app bundle, not from your API, so an API compromise cannot change it. Show the minimum output prominently, next to the expected output, because the minimum is the only number the user is guaranteed.

Step 7: Read the outcome from the chain

After submitting, do not rely on your API saying "done". Watch the escrow's events directly and show the user what the chain says.

track.tsTypeScript
import { createPublicClient, http, parseAbiItem } from "viem";
import { mainnet } from "viem/chains";

const client = createPublicClient({ chain: mainnet, transport: http() });

export function trackOrder(
  escrow: `0x${string}`,
  orderId: `0x${string}`,
  onUpdate: (s: string) => void,
) {
  const unwatchSettled = client.watchEvent({
    address: escrow,
    event: parseAbiItem(
      "event Settled(bytes32 indexed orderId, address indexed solver, uint256 filledAmount)",
    ),
    args: { orderId },
    onLogs: (logs) => onUpdate(`Filled: ${logs[0].args.filledAmount} delivered`),
  });
  const unwatchRefunded = client.watchEvent({
    address: escrow,
    event: parseAbiItem("event Refunded(bytes32 indexed orderId)"),
    args: { orderId },
    onLogs: () => onUpdate("Refunded"),
  });
  return () => {
    unwatchSettled();
    unwatchRefunded();
  };
}

If the deadline passes with no fill, offer the refund button. The user should never need support to get their funds back.

Step 8: Test the failure cases

Write tests for the paths users never hope to see: a fill below the minimum (settle must revert), a fill to the wrong recipient, a replayed signature, a refund before the deadline, and a settle after a refund. The escrow's job is to make every one of those impossible.

What we would do

Decide the verification approach first, because it shapes everything else. Keep the escrow minimal and audited, enforce the minimum and recipient in the escrow itself rather than trusting the verifier, and treat front-end checks as part of the security model, not decoration. Where possible, build on an existing standard such as ERC-7683 so solvers can integrate without custom work.

We build cross-chain and DeFi products like this in our DeFi applications work.

Contact

Need this built for your product?

Tell us what you are building and where you are stuck. Email is the fastest way to reach the team.

contact@onchain.ro