Sign and fill orders
Make, list, find, fill and cancel orders, with viem.
Setup
The examples use viem, which includes Robinhood Chain, and the ABI from the ABI page.
import { createPublicClient, createWalletClient, custom, http } from "viem"
import { robinhood } from "viem/chains"
export const MARKET = "0x…" // from Deployments
export const client = createPublicClient({ chain: robinhood, transport: http() })
export const wallet = createWalletClient({ chain: robinhood, transport: custom(window.ethereum) })
export const [account] = await wallet.getAddresses()Sign an order
Orders are EIP-712 typed data under the domain name: "ReturnERC20Loans", version: "4", the chain ID, and the market address.
import { erc20Abi, parseUnits, toHex, zeroAddress } from "viem"
const order = {
side: 1, // Borrow: the maker is the borrower
maker: account,
taker: zeroAddress, // anyone may fill
collateral: NVDA,
collateralAmount: parseUnits("10", 18),
loanToken: USDG,
principal: parseUnits("1000", 6),
repayment: parseUnits("1010", 6),
duration: 30 * 86400,
validUntil: BigInt(Math.floor(Date.now() / 1000) + 86400),
counter: await client.readContract({ address: MARKET, abi: loansAbi, functionName: "counters", args: [account] }),
salt: BigInt(toHex(crypto.getRandomValues(new Uint8Array(32)))),
minFill: parseUnits("1000", 6), // all or nothing
}
const signature = await wallet.signTypedData({
account,
domain: { name: "ReturnERC20Loans", version: "4", chainId: robinhood.id, verifyingContract: MARKET },
types: { Order: [
{ name: "side", type: "uint8" }, { name: "maker", type: "address" }, { name: "taker", type: "address" },
{ name: "collateral", type: "address" }, { name: "collateralAmount", type: "uint128" },
{ name: "loanToken", type: "address" }, { name: "principal", type: "uint96" }, { name: "repayment", type: "uint96" },
{ name: "duration", type: "uint32" }, { name: "validUntil", type: "uint64" }, { name: "counter", type: "uint256" },
{ name: "salt", type: "uint256" }, { name: "minFill", type: "uint96" },
] },
primaryType: "Order",
message: order,
})
// The maker's side moves at fill time: approve it now.
await wallet.writeContract({ account, address: NVDA, abi: erc20Abi, functionName: "approve", args: [MARKET, order.collateralAmount] })Field meanings are on Functions.
- Accounts with code, including EIP-7702 accounts, are validated with ERC-1271, with no fallback to ECDSA.
- Pass the full signature bytes, with no
eth_signprefix.
List an order
Send the order and signature to a taker directly, or publish them with post. It emits Posted with both, and stores nothing. Only the maker can post, and only orders with a zero taker.
await wallet.writeContract({ account, address: MARKET, abi: loansAbi, functionName: "post", args: [order, signature] })Find open orders
Read Posted events from DEPLOY_BLOCK, the block of the market's creation transaction on the block explorer. Keep orders that are unexpired, uncancelled, not fully filled, and signed with the maker's current counter.
const posted = await client.getContractEvents({ address: MARKET, abi: loansAbi, eventName: "Posted", fromBlock: DEPLOY_BLOCK })
const now = BigInt(Math.floor(Date.now() / 1000))
const open = []
for (const { args: { id, order, signature } } of posted) {
const [filled, cancelled] = await client.readContract({ address: MARKET, abi: loansAbi, functionName: "orderState", args: [id] })
const counter = await client.readContract({ address: MARKET, abi: loansAbi, functionName: "counters", args: [order.maker] })
if (!cancelled && filled < order.principal && order.validUntil >= now && order.counter === counter) open.push({ order, signature })
}Fill an order
import { erc20Abi, parseEventLogs } from "viem"
const [preview] = await client.readContract({ address: MARKET, abi: loansAbi, functionName: "previewFill", args: [order, amount, account] })
// The taker supplies the principal (Borrow order) or this fill's collateral (Lend order).
const [token, value] = order.side === 1 ? [order.loanToken, amount] : [order.collateral, preview.collateralAmount]
await wallet.writeContract({ account, address: token, abi: erc20Abi, functionName: "approve", args: [MARKET, value] })
const { request } = await client.simulateContract({ account, address: MARKET, abi: loansAbi, functionName: "fill", args: [order, amount, signature] })
const receipt = await client.waitForTransactionReceipt({ hash: await wallet.writeContract(request) })
const [opened] = parseEventLogs({ abi: loansAbi, logs: receipt.logs, eventName: "Opened" })
const loan = opened.args.loan // every settlement call takes thisThe fee comes out of the principal: the borrower receives amount − fee.
Cancel orders
cancel(order)ends one order's unfilled remainder. Loans already opened are unaffected.incrementCounter()invalidates every order the caller has signed so far.
Revoking an approval only pauses an order. Cancel orders you no longer want.
Last updated