Act only if XE says yes
A worked pattern for a contract that buys only when an XE service answers yes, with a price cap, a deadline and replay guards.
This pattern puts XE's answer in front of an action: buy only if yes. The buyer asks an XE judgment service about one specific purchase. The contract checks that XE's validators signed a "yes" about exactly that purchase, then buys, never above the buyer's maximum price and never after the deadline.
See a Base market settle on XE's answer
The contract below is an example built on XEAttest (xe-kit evm/src/xe/XEAttest.sol), following the rules of XEGuardHook, the Uniswap v4 guard in xe-kit evm/examples/. It isn't deployed. Read it as a template and review it as you would any contract that moves money.
#Why the question must be the purchase
An attestation says "XE's providers agreed on this output for this input". The input is its subject: keccak256 of the request's inline input.
If a buyer could name the question separately from the purchase, they could get a harmless question approved and use the approval for a different purchase. So the input is the purchase: an Intent struct with the chain, the contract, the listing, the buyer, the maximum price and the deadline. The contract recomputes keccak256(abi.encode(intent)) and requires it to equal the subject.
The judgment service reads that struct and answers abi.encode(bool yes, uint8 confidence). Which service you trust is your policy: pin its id.
#The contract
// SPDX-License-Identifier: Apache-2.0pragma solidity ^0.8.22; import {XEAttest, XEAttestVerifier} from "./xe/XEAttest.sol"; /// Sells listings only to buyers who bring XE's signed "yes" about that exact purchase.contract BuyIfYes is XEAttestVerifier { struct Intent { uint256 chainId; // block.chainid address market; // this contract uint256 listingId; address buyer; // who may use the approval uint256 maxPrice; // the most the buyer pays, in wei uint64 notAfter; // the last second the purchase may happen bytes32 context; // what was asked: a hash of the question or policy } struct Listing { address seller; uint256 price; bool sold; } bytes32 public immutable serviceId; // the judgment service you trust uint8 public immutable minAgreement; // agreeing providers required uint8 public immutable minConfidence; // 0..100 uint64 public immutable maxAge; // seconds after the request; 0 = only expiresAt mapping(uint256 => Listing) public listings; mapping(bytes32 requestId => bool) public used; error WrongTarget(); error IntentExpired(); error AlreadySold(); error PriceAboveMax(); error WrongValue(); error WrongService(); error WrongSubject(); error Stale(); error NotBeacon(); error WrongMode(); error WeakAgreement(); error WrongOutput(); error Rejected(); error AlreadyUsed(); error TransferFailed(); constructor( uint32 xeDomain, uint8 threshold, address[] memory validators, bytes32 serviceId_, uint8 minAgreement_, uint8 minConfidence_, uint64 maxAge_ ) XEAttestVerifier(xeDomain, threshold, validators) { serviceId = serviceId_; minAgreement = minAgreement_; minConfidence = minConfidence_; maxAge = maxAge_; } function list(uint256 listingId, uint256 price) external { require(listings[listingId].seller == address(0), "taken"); listings[listingId] = Listing(msg.sender, price, false); } function buy( Intent calldata intent, XEAttest.Attestation calldata att, bytes calldata signatures, bytes calldata output ) external payable { Listing storage l = listings[intent.listingId]; // 1. The intent is this purchase, on this chain, by this caller, now. if (intent.chainId != block.chainid || intent.market != address(this) || intent.buyer != msg.sender) { revert WrongTarget(); } if (block.timestamp > intent.notAfter) revert IntentExpired(); if (l.seller == address(0) || l.sold) revert AlreadySold(); if (l.price > intent.maxPrice) revert PriceAboveMax(); if (msg.value != l.price) revert WrongValue(); // 2. XE judged exactly this intent, with the service and the rules we trust. if (att.serviceId != serviceId) revert WrongService(); if (att.subject != keccak256(abi.encode(intent))) revert WrongSubject(); if (maxAge != 0 && block.timestamp > uint256(att.issuedAt) + maxAge) revert Stale(); if (!XEAttest.isBeacon(att)) revert NotBeacon(); if (att.verification & XEAttest.MODE_MASK != XEAttest.MODE_QUORUM) revert WrongMode(); if (att.agreement < minAgreement) revert WeakAgreement(); // 3. The agreed output is "yes", with enough confidence. if (output.length != 64 || !XEAttest.outputMatches(att, output)) revert WrongOutput(); (bool yes, uint8 confidence) = abi.decode(output, (bool, uint8)); if (!yes || confidence < minConfidence) revert Rejected(); // 4. Signed by XE's validators and unexpired; each approval buys once. _verifyAttestation(att, signatures); if (used[att.requestId]) revert AlreadyUsed(); used[att.requestId] = true; l.sold = true; (bool ok,) = l.seller.call{value: msg.value}(""); if (!ok) revert TransferFailed(); }}#What each guard stops
| Guard | Stops |
|---|---|
chainId, market in the intent | Using an approval on another chain or another contract |
buyer == msg.sender | Someone copying the transaction from the mempool and buying first with your approval |
maxPrice | The seller raising the price after the buyer asked |
notAfter | Buying later than the buyer intended |
serviceId | An approval from a service you don't trust |
subject == keccak256(abi.encode(intent)) | Using an approval of a different question |
maxAge on issuedAt | Old answers. issuedAt is the request's time, so an answer's age is overstated, never understated |
expiresAt (checked by _verifyAttestation) | Anything later than the request's deadline, and never more than one hour after the request |
| Beacon selection | A requester re-signing until it draws providers it likes. With immediate selection it could; with the beacon, the providers come from a state-chain block that didn't exist when the request was signed |
| Verification mode | Answers verified by a mode you didn't choose |
minAgreement | Thin agreement |
outputMatches and the decode | An output that isn't the agreed one, or isn't a strict yes/no |
used[requestId] | Buying twice with one approval |
validatorSet in the attestation | Signatures for another network or an old validator set |
#Getting the attestation
The buyer's client asks the service from the buyer's own XE account, waits for the final outcome, and collects two validators' signatures.
import { attestableRequest, waitForOutcome, collectAttestation, encodeAbi,} from "@xe-network/protocol/interop"; const NODE = "https://xe-sim-interop.enter-38b.workers.dev";const set = { xeDomain: 22599, threshold: 2, validators: [ "0x2b818ea4417a047a392aae395a53d65572a13f99", "0x5fd7368b1541b1e5047b87db4979b63895050278", "0xcadb7fe29a65b7ab4e2e1873fdb066a1601201d0", ],};const sources = [ { validator: "0xcadb7fe29a65b7ab4e2e1873fdb066a1601201d0", url: "https://xe-interop-agent.enter-38b.workers.dev" }, { validator: "0x5fd7368b1541b1e5047b87db4979b63895050278", url: "https://xe-interop-validator-2.enter-38b.workers.dev" }, { validator: "0x2b818ea4417a047a392aae395a53d65572a13f99", url: "https://xe-interop-validator-3.enter-38b.workers.dev" },]; // The purchase is the questionconst intent = [84532n, market, listingId, buyer, maxPrice, notAfter, context] as const;const input = encodeAbi(["uint256", "address", "uint256", "address", "uint256", "uint64", "bytes32"], intent); // Ask, with beacon selection (the default) and account delivery: the attestation is the deliveryconst quote = await (await fetch(`${NODE}/services/${serviceId}/quote`)).json();const payload = attestableRequest({ service: serviceId, quote, input, timestampNs, deadlineSeconds: 600 });// your code: the buyer's wallet signs and submits the service_request block// (through XE Connect with xe:services@1, or buildAccountBlock), and returns its hashconst requestId = await submit(payload); const outcome = await waitForOutcome({ fetch, nodeUrl: NODE, requestId });if (outcome.status !== "agreed") throw new Error(`XE answered: ${outcome.status}`); const { attestation, signatures, output } = await collectAttestation({ fetch, requestId, sources, set });await market.write.buy([intent, attestation, signatures, output], { value: price });collectAttestation checks every signature against the set before using it and returns exactly two, in ascending signer order. A validator answers 409 until the outcome is final, 410 once it has expired and 422 if the outcome isn't attestable, such as a failed request or one with non-inline input.
#Failing closed
If the answer is "no", or fewer than two validators sign, or the attestation expires, buy reverts and nothing moves. The buyer keeps their ETH. That is the intended behaviour: the guard fails closed.
#The same pattern without attestations
If the contract should ask XE itself instead of the buyer, use the claim path of Contracts using XE: the contract calls _xeRequest with the intent as input and records the command id against the order. The result comes back pushed or claimed through _xePull, and _onXEResult matches it by command id. The binding to the purchase then comes from the contract's own request, and the output check is the same as XEPullConsumer._isYes.
| Attestation (this page) | Contract asks (claim) | |
|---|---|---|
| Who asks XE | The buyer, from their own XE account | The contract, from its XE account |
| Who pays the service | The buyer, on XE | The contract's XE account |
| Steps for the buyer | Ask, then one transaction | One transaction to open, one to claim (or wait for a push) |
| Gas to verify | About 10k plus calldata | About 97k per claimed message |
| Works across chains | One attestation serves any chain | One result per destination contract |