Contracts using XE
XE.sol lets any EVM contract hold an XE account, pay, call XE Services and get the answer back, pushed by a relayer or claimed with XE's signatures.
XE.sol lets a contract on an EVM chain use XE: hold XE and XUSD, pay XE accounts, lease compute, call XE Services and send messages from XE to other chains. Answers come back two ways: pushed by a relayer, or claimed by anyone with XE's signatures.
It deploys nothing and has no owner, admin, upgrade path or fee switch. Your contract talks to Hyperlane's Mailbox, and XE verifies it with Hyperlane's validators.
See a Base contract ask XE · A Base market that settles on XE's answer
#Setup
Copy src/xe/ from xe-kit evm/ into your project. It's four files with no dependencies, for Solidity ^0.8.22.
| File | What |
|---|---|
XE.sol | The library: config, remote account derivation, command encoders, quoting, sending, decoders, claim verification (verifyResult) |
XEClient.sol | The contract to inherit: handle with every check, interchainSecurityModule(), the _xe* send helpers, the _xePull* claim helpers, the hooks |
XEChains.sol | Ready-made configs (baseSepoliaXESim()) |
IXEHyperlane.sol | The four Hyperlane interfaces it needs |
XEChains has Base Sepolia today. For the other testnets, build the config from the deployment's addresses:
XE.Config memory arbitrumSepolia = XE.Config({ mailbox: 0x598facE78a4302f11E3de0bee1894Da0b2Cb71F8, merkleTreeHook: 0xAD34A66Bf6dB18E858F6B686557075568c6E031C, xeDomain: XE.SIM_DOMAIN, // 22599 xeIsm: 0xE8a25deb1520535e7e53e7529F044a10885440e2}); XE.Config memory optimismSepolia = XE.Config({ mailbox: 0x6966b0E55883d49BFB24539356a2f8A673E02039, merkleTreeHook: 0x86fb9F1c124fB20ff130C41a79a432F770f67AFD, xeDomain: XE.SIM_DOMAIN, xeIsm: 0xD5Ade28E6dE5d1fE2eEa0364B30da65F4b40856E});#The model
Your contract owns an XE account, its remote account:
xeAccount = sha256("xe/remote-account/v1" ‖ origin u32 ‖ address(this) as 32 bytes ‖ lineage 0)No key can control it. The contract commands it with Hyperlane messages, and XE executes each command as an ordinary block. Fund the account on XE before you send commands that spend: send XE or XUSD to xeAccount().
#Sending
All helpers live on XEClient. The same functions exist on XE for contracts that don't inherit it.
| Helper | Executes on XE as | Notes |
|---|---|---|
_xePay(to, amount, asset, memo, opts) | send from your XE account | XE.ASSET_XE or XE.ASSET_XUSD; memo up to 64 bytes |
_xeLease(XE.Lease, opts) | lease, paying XUSD up to maxCost | Then _xeLeaseCancel, _xeLeaseForceSettle, _xeLeaseRenew |
_xeDispatch(destination, recipient, gasLimit, body, opts) | dispatch from your XE account | To any chain XE reaches; point it at the ICA router to call contracts there |
_xeDispatchBack(body, gasLimit, opts) | dispatch back to this contract | Arrives in _onXEMessage |
_xeRequest(XE.ServiceRequest, opts) | service_request | Ask an XE service; see below |
_xeSendMessage(xeAccount, body) | message_receive on that account | Data only; moves no value |
_xeSetRepresentative(rep, opts) | remote_call | Off unless the DAO's sys.remote policy allows it |
_xeCommand(body) | the op in the body | For ops later modules add |
XE.Options has three fields:
flags:XE.RECEIPT_ON_SUCCESS,XE.RECEIPT_ON_FAILURE(both areXE.RECEIPTS),XE.WAIT_FOR_FUNDS.deadline: unix seconds; 0 means none. XE accepts timestamps within about an hour, so use hours.receiptGasLimit: the gas a relayer should give yourhandlefor the receipt.
Amounts are u64 micro-units: 1 XE is 1,000,000. Each helper returns the command id, which is the Hyperlane message id, and emits one event (XEPaySent, XEServiceRequested and so on). Helpers refuse before sending anything XE would fail as malformed (XEInvalidCommand).
#Fees
Every send pays exactly mailbox.quoteDispatch(...) from the contract's balance, which includes msg.value. Otherwise it reverts XEInsufficientFee(required, available). Today that's the Mailbox's protocol fee only: 0 on Base Sepolia and Arbitrum Sepolia, 1 wei on Optimism Sepolia. Quote with _xeQuoteCommand(body). Nothing on XE costs a fee: blocks carry proof of work, which the relayer computes.
#Asking an XE service
_xeRequest sends a service_request from your XE account. XE.inlineRequest builds the common case: inline input, the result sent back to this contract.
XE.ServiceRequest memory r = XE.inlineRequest( serviceId, // bytes32: the service's id question, // bytes: the inline input XE.ASSET_XE, // must be the service's price asset, else SERVICE_TERMS maxPrice, // escrowed from your XE account; the rest is refunded uint64(block.timestamp + 6 hours), // the request's deadline (at most 7 days) 300_000 // gas hint for the result's handle);bytes32 commandId = _xeRequest(r, XE.Options({flags: 0, deadline: uint64(block.timestamp + 6 hours), receiptGasLimit: 120_000}));What comes back, in order:
- The receipt.
XEClientalways asks for both receipts on a request. Executed:executedInis the XE request block, which is therequestIdthe result will carry. Failed:_onXEResult(XE.Receipt)with the code, such asCODE_SERVICE_TERMS(0x0130) orCODE_INSUFFICIENT_FUNDS. - The result. Once providers answer and the request settles, XE sends the body of
onXEResult(requestId, serviceId, status, output, outputHash, verification, agreement, n, attestationHash, providers)(selector0x0dbe89b2).XEClientdecodes it and calls_onXEResult(XE.ServiceResult)withcommandIdfilled in.
| Field | Values |
|---|---|
status | 1 agreed, 2 failed, 3 timeout, 4 cancelled |
verification & 0x7f | 1 quorum, 2 tee, 3 tee + quorum, 4 optimistic, 5 zk, 6 aggregate (feeds) |
verification & 0x80 | set when the providers were selected by the beacon |
output | The agreed output, up to 1,024 bytes. For a judgment: abi.encode(bool yes, uint8 confidence) |
outputHash | SHA-256 of the output; zero unless agreed |
agreement, n | Agreeing providers, and providers selected |
attestationHash | For TEE modes, the aggregate of the hardware attestations every node verified |
Only the ledger builds onXEResult bodies: no plain dispatch may start with that selector. So a result is a fact of the ledger, whoever delivers it. A result of your own request is matched to your command. A result of someone else's request is taken only if _xeAcceptsResult(s) returns true.
#Push
A relayer calls Mailbox.process(metadata, message). The Mailbox asks your contract for its ISM, verifies XE's signatures with it, and calls handle. XEClient checks the rest and runs your hook. The relayer pays the gas.
XEServiceConsumer (xe-kit evm/examples/XEServiceConsumer.sol) keeps only quorum-agreed answers:
contract XEServiceConsumer is XEClient { bytes32 public immutable serviceId; bytes8 public immutable priceAsset; struct Answer { bool done; uint8 status; // XE.SERVICE_*; 0 = the request itself failed (see code) uint16 code; // receipt code when the request failed bytes32 outputHash; // zero unless agreed by a quorum bytes output; } mapping(bytes32 commandId => Answer) public answers; constructor(XE.Config memory cfg, bytes32 serviceId_, bytes8 priceAsset_) XEClient(cfg) { serviceId = serviceId_; priceAsset = priceAsset_; } function ask(bytes calldata question, uint64 maxPrice) external payable returns (bytes32 commandId) { commandId = _xeRequest( XE.inlineRequest(serviceId, question, priceAsset, maxPrice, uint64(block.timestamp + 6 hours), 300_000), XE.Options({flags: 0, deadline: uint64(block.timestamp + 6 hours), receiptGasLimit: 120_000}) ); } // The request itself failed on XE (SERVICE_TERMS, INSUFFICIENT_FUNDS, ...). function _onXEResult(XE.Receipt memory r) internal override { if (r.code != XE.CODE_EXECUTED) answers[r.commandId] = Answer(true, 0, r.code, bytes32(0), ""); } function _onXEResult(XE.ServiceResult memory s) internal override { bool agreed = s.status == XE.SERVICE_AGREED && (s.verification & 0x7f) == XE.VERIFY_QUORUM; answers[s.commandId] = Answer(true, s.status, 0, agreed ? s.outputHash : bytes32(0), agreed ? s.output : bytes("")); }}On XE Sim Interop, XE's relayer pushes receipts and results to contracts whose XE account is on its allowlist. A request can also pay a relayer from its escrow (ServiceRequest.relayer and relayerFee). For any other contract, use claim, or relay the message yourself: Mailbox.process is permissionless.
#Claim
Anyone hands your contract XE's validator-signed message, and your contract verifies it itself against the same XE ISM, without the Mailbox and without waiting for a relayer. The caller pays the gas, inside the transaction that uses the answer.
XEPullConsumer (xe-kit evm/examples/XEPullConsumer.sol) is a yes/no bounty. open escrows ETH and asks a judgment service. When XE settles, the payee, or anyone, calls claim with the receipt and the result:
/// The request's receipt first, then its result (or only the result if the receipt was already/// delivered). Each is verified against the XE ISM; anyone may call.function claim(bytes[] calldata messages, bytes[] calldata metadata) external { if (messages.length != metadata.length) revert LengthMismatch(); for (uint256 i = 0; i < messages.length; i++) { _xePull(messages[i], metadata[i]); }} function _onXEResult(XE.Receipt memory r) internal override { if (r.code != XE.CODE_EXECUTED) _settle(r.commandId, false); // refund} function _onXEResult(XE.ServiceResult memory s) internal override { _settle(s.commandId, _isYes(s));} function _isYes(XE.ServiceResult memory s) internal view returns (bool) { if (s.status != XE.SERVICE_AGREED || s.agreement < minAgreement) return false; if ((s.verification & 0x7f) != XE.VERIFY_QUORUM || s.output.length != 64) return false; (uint256 yes, uint256 confidence) = abi.decode(s.output, (uint256, uint256)); return yes == 1 && confidence <= type(uint8).max;}Three helpers, all on XEClient:
| Helper | Does |
|---|---|
_xePull(message, metadata) | Verifies and runs _onXEResult, exactly like handle |
_xePullReceipt(message, metadata) | Verifies a receipt and returns it, without the hook, for inline use |
_xePullServiceResult(message, metadata) | Verifies a result and returns it, without the hook: "pay out with this result" |
XE.verifyResult(cfg, localDomain, target, message, metadata) is the stateless building block for contracts that don't inherit XEClient. It leaves sender policy and replay state to you.
Only receipts and service results can be claimed: they carry an id that makes them one-shot whichever way they arrive. Plain messages are push-only.
#Building a claim
The message is in the remote account's outbox on XE. Its metadata comes from the validators' public checkpoints.
import { InteropReader, parseSignedCheckpoint, recoverCheckpointSigner, buildMessageIdMetadata, bytesToHex,} from "@xe-network/protocol/interop"; const NODE = "https://xe-sim-interop.enter-38b.workers.dev";const CHECKPOINTS = "https://pub-2ecc7a400398474da5c9ce2451b47186.r2.dev/xe-sim-0002"; // 1. The receipt and the result, from the contract's XE account outboxconst reader = new InteropReader(async (path) => (await fetch(NODE + path)).json());const { count } = await reader.outbox(xeAccount);const messages = await reader.outboxMessages(xeAccount, 0, count);const m = messages.find((x) => x.id === resultMessageId)!; // 2. Each validator's signed checkpoint for that messageconst signatures = [];for (const n of [1, 2, 3]) { const url = `${CHECKPOINTS}/validator-${n}/checkpoint_${xeAccount}_${m.fields.nonce}_with_id.json`; const res = await fetch(url); if (!res.ok) continue; // not signed yet const { checkpoint, signature } = parseSignedCheckpoint(await res.json()); const validator = recoverCheckpointSigner(checkpoint, signature); if (validator) signatures.push({ checkpoint, validator, signature });} // 3. Metadata for the ISM: two signatures, in the ISM's validator orderconst { metadata } = buildMessageIdMetadata({ checkpoint: signatures[0].checkpoint, validators: ismValidators, // ISM.validatorsAndThreshold(message) threshold: 2, signatures,});await consumer.claim([bytesToHex(m.message)], [metadata]);Check each checkpoint's message id against the message before you use it. Validators sign only once the XE block is final, usually within seconds of the settle.
#Push and claim together
Push and claim share one record of answered requests, so an answer applies once:
- Claimed first. The later Mailbox delivery of the same message succeeds, so relayers aren't stuck, and changes nothing (
XEDuplicateIgnored). - Pushed first. A claim of it reverts
XEAlreadyDelivered. Any other message with an answered id revertsXEAlreadyAnswered.
A result is accepted only after the receipt of its request, because the receipt's executedIn is the request id. Claim both in one transaction, receipt first.
#Attestations
An attestation is a third way to bring an answer in, built for use inside the transaction that needs it. It's a 352-byte EIP-712 statement of a final, agreed outcome, signed by the same validator keys. It needs no Mailbox and no ISM: any contract checks it for about 10,000 gas.
struct Attestation { // XEAttest.Attestation bytes32 validatorSet; // keccak256(abi.encode(uint32 xeDomain, uint8 threshold, address[] validators)) uint32 xeDomain; bytes32 serviceId; bytes32 requestId; bytes32 outputHash; // SHA-256 of the agreed output bytes32 subject; // keccak256 of the request's inline input uint64 issuedAt; // the request's time, unix seconds uint64 expiresAt; // min(request deadline, issuedAt + 1 hour) uint8 verification; uint8 agreement; uint8 n;}Inherit XEAttestVerifier (xe-kit evm/src/xe/XEAttest.sol) with the validator set, then call _verifyAttestation(att, signatures). It checks the set, the network, the expiry and exactly threshold signatures in ascending signer order. The domain has no chain id and no contract, so one attestation serves every chain. Your contract must therefore check the rest: the service, the subject against its own context, the output against outputHash, and the agreement. Act only if XE says yes walks through it.
On XE Sim Interop the set id is 0xcc89efb103f46d38042c0c458954b366996677279b91d14c27821fad6d7e916d (2 of the 3 validators). Each validator serves its signature at GET /attestations/{requestId} (Reference). Attestations cover only agreed outcomes of requests with inline input.
#Choosing push or claim
| Push | Claim (ISM) | Claim (attestation) | |
|---|---|---|---|
| Who delivers | A relayer calls Mailbox.process | Anyone calls your function with (message, metadata) | Anyone calls your function with (attestation, signatures, output) |
| Verified by | The Mailbox, with the ISM your contract names | Your contract, calling the XE ISM's verify | Your contract, with ecrecover |
| When | When a relayer gets to it | As soon as the validators have signed | As soon as the validators have signed, until it expires (at most 1 hour) |
| Who pays gas | The relayer | The caller | The caller |
| Gas (Base Sepolia fork, 3-of-4 test ISM) | About 197k to process a receipt | About 97k to claim a receipt | About 10k to verify 2 of 3, plus about 6k of calldata |
| What it carries | Receipts, results, plain messages | Receipts and results | Agreed results with inline input |
| Size | Body up to 4,096 bytes; output up to 1,024 | Same | 352 bytes plus the output |
| If nobody relays | You wait, or relay it yourself | Not affected | Not affected |
| Runs inline | No: a separate transaction calls your hook | Yes, with the typed helpers | Yes |
Rules of thumb:
- Push when the contract should react on its own and you don't want users to pay gas: settling a request in the background, updating state no user is waiting on.
- Claim when the user who benefits is already sending a transaction: claim a payout, settle a market, unlock an escrow. It doesn't depend on a relayer's schedule or allowlist, so nobody can hold your answer back.
- Attestation when the answer gates the transaction itself: a swap, a mint, a withdrawal that should go through only with XE's approval. Or when one answer serves several chains.
#What handle and the claim helpers check
| Check | On failure |
|---|---|
| Push: the caller is the configured Mailbox | XENotMailbox |
| Claim: Hyperlane v3, destination this chain, recipient this contract, not delivered by the Mailbox | XENotAMessage, XEWrongDestination, XEWrongRecipient, XEAlreadyDelivered |
| A threshold of XE validators signed the message id | The ISM reverts (!threshold) |
| The origin is XE's domain | XEWrongOrigin |
Receipts come from this contract's XE account; results from any XE account; plain messages from this contract's account or one _xeAccepts | XEUntrustedSender |
| A receipt or result names an awaited request with the same op | XEUnexpectedAnswer |
| Answered once | Push: ignored (XEDuplicateIgnored). Claim: XEAlreadyAnswered |
| Claim: a receipt or a service result | XENotAResult |
| Not reentered | XEReentrantCall |
A reverting hook reverts the delivery or the claim. The message stays deliverable and can be pushed or claimed again. Keep hooks cheap and bounded.
#Pitfalls
- Call XE.sol from the contract that owns the account. A shared dispatcher's callers all share its one XE account.
- Commands are asynchronous and unordered. Wait for a receipt before a dependent command.
- Receipts aren't guaranteed. Don't lock funds with no exit. Give every command a deadline.
- Proxies.
XEClientbinds its XE account in the constructor, so it's for non-upgradeable contracts. - Static ISM. A validator rotation means a new ISM and a redeploy on today's testnets.
- Fund the right asset. A request escrows the service's price asset. On XE Sim Interop most test services are priced in XE.
#Limits
| Limit | Value |
|---|---|
| Message body | 4,096 bytes |
| Inline service output | 1,024 bytes |
| Memo | 64 bytes |
| Request deadline | At most 7 days, and at most the service's max_deadline_secs |
| Deadline precision | About one hour |
| One op per command | Batches aren't supported |
Deployed examples on Base Sepolia, both for xe-test.is-even-length-xe:
| Contract | Address |
|---|---|
XEServiceConsumer (push) | 0x95fF768895d9DBc2C7E3c326ef78aAd5C26368b0 |
XEPullConsumer (claim) | 0xa2dB1FfafaF87100507CcD120Af793f49044656c |