Build a Trading Agent
This guide shows your agent can request odds for a wager it would like to place on a forecast.
Start auctions and receive bids
const ws = new WebSocket('ws://localhost:3001/auction');
ws.onopen = () => {
ws.send(JSON.stringify({
type: 'auction.start',
payload: {
maker: '0xMaker...',
wager: '1000000000000000000',
resolver: '0xResolver...',
predictedOutcomes: ['0xabc...'],
makerNonce: 1,
},
}));
};
ws.onmessage = (ev) => {
const msg = JSON.parse(String(ev.data));
if (msg.type === 'auction.ack') {
console.log('auctionId =', msg.payload.auctionId);
}
if (msg.type === 'auction.bids') {
const best = pickBest(msg.payload.bids);
console.log('best bid =', best);
}
};
function pickBest(bids) {
const now = Math.floor(Date.now()/1000);
const valid = bids.filter(b => b.takerDeadline > now);
valid.sort((a, b) => BigInt(b.takerWager) - BigInt(a.takerWager) > 0n ? 1 : -1);
return valid[0];
}
Makers initiate auctions by sending auction.start
. The relayer broadcasts auction.started
with parameters including auctionId
, maker
, wager
, resolver
, and predictedOutcomes
.
Accept a Bid
After selecting a bid, call PredictionMarket.mint
using the current auction parameters and the selected bid fields.
import { writeContract } from 'viem/actions';
import { erc20Abi } from 'viem';
import { abi as PredictionMarketAbi } from './PredictionMarket.abi';
// Approve maker collateral for PredictionMarket to pull
await writeContract({
address: '0xCollateralToken...',
abi: erc20Abi,
functionName: 'approve',
args: ['0xPredictionMarket...', '1000000000000000000'], // makerCollateral
});
const bestBid = /* from auction.bids */
{
taker: '0xTaker...',
takerWager: '500000000000000000',
takerDeadline: Math.floor(Date.now()/1000) + 60,
takerSignature: '0x' + '11'.repeat(32) + '22'.repeat(32),
makerNonce: 1,
};
const mintReq = {
encodedPredictedOutcomes: '0xabc...',
resolver: '0xResolver...',
makerCollateral: '1000000000000000000',
takerCollateral: bestBid.takerWager,
maker: '0xMaker...',
taker: bestBid.taker,
takerSignature: bestBid.takerSignature,
takerDeadline: String(bestBid.takerDeadline),
refCode: '0x' + '00'.repeat(32),
makerNonce: String(bestBid.makerNonce),
};
await writeContract({
address: '0xPredictionMarket...',
abi: PredictionMarketAbi,
functionName: 'mint',
args: [mintReq],
});