@lifi/compose-spec
Version:
Public wire-format types and schemas for Compose flows
217 lines (199 loc) • 8.63 kB
text/typescript
/**
* Canonical wire-format types for the standalone `POST /simulate` endpoint.
*
* `/simulate` takes a raw, pre-encoded transaction (a `to` address, hex `data`,
* optional native `value`), funds a sender, runs it in one `eth_call`, and
* reports the watched balances before and after, their signed deltas, and the
* inner-call gas. Unlike `POST /compose`, its response body is **un-enveloped**:
* `{ status, block?, timestamp?, ... }` lives at the top level (no `{ data }`
* wrapper).
*
* These are the single source of truth for the request/response shapes. The
* server-side Zod schemas in `@lifi/api-schemas` (`src/routes/simulate.ts`)
* validate the same contract and are kept in lockstep by a compile-time
* conformance assertion (`src/routes/simulate.typecheck.ts`).
*
* Mirrors the hand-authored style of `src/compile.ts`.
*/
import type {
Erc20AllowancePrecondition,
Erc20BalancePrecondition,
NativeBalancePrecondition,
} from './preconditions.js';
/**
* Maximum number of watched `(token, owner)` pairs accepted by `POST /simulate`.
*
* The limit comes from the VM's hard register budget (~123 usable registers,
* checked on the final ISA layout). Each pair costs two result registers — a
* before-read and an after-read — that are both live at the closing abi-encode,
* so the compiler cannot coalesce them; that `2 × N` is the cost that scales.
* Token and owner address literals do not scale it, since constant-propagation
* merges identical-valued literals into one register. The cap leaves headroom
* for the inner-call / gas-measurement / abi-encode scaffolding.
*/
export const SIMULATE_MAX_TRACKED_BALANCES = 40;
/**
* Maximum number of funding `requirements` accepted by `POST /simulate`.
*
* Each requirement triggers a slot-discovery cycle (access-list probe + sentinel
* verification + RPC round trips) in slot-finder, so an unbounded array lets a
* single request amplify into arbitrary upstream RPC work. Bounded here at the
* trust boundary and re-enforced server-side in `rawSimulation.ts`.
*/
export const SIMULATE_MAX_REQUIREMENTS = 40;
/** A `(token, owner)` pair whose balance is watched across the simulation. */
export interface TrackedBalance {
/** Token to watch (use the zero address for native balance). */
readonly token: string;
/** Account whose balance of `token` is watched. */
readonly owner: string;
}
// The funding instructions are the precondition shapes themselves: what the
// simulator seeds is exactly what a compile declared. See `preconditions.ts`
// for the canonical definitions and constructors.
/** Funding instruction: seed an ERC-20 balance on a wallet before simulation. */
export type Erc20BalanceRequirement = Erc20BalancePrecondition;
/** Funding instruction: seed a native balance on a wallet before simulation. */
export type NativeBalanceRequirement = NativeBalancePrecondition;
/** Funding instruction: seed an ERC-20 allowance before simulation. */
export type Erc20AllowanceRequirement = Erc20AllowancePrecondition;
/**
* Funding instruction: seed a Uniswap Permit2 `AllowanceTransfer` allowance
* before simulation, so a `Permit2.transferFrom(owner, _, amount, token)` sent
* by `spender` passes Permit2's own check.
*
* slot-finder writes two overrides: Permit2's `allowance[owner][token][spender]`
* (no expiry, the owner's live nonce kept) and the ERC-20 allowance
* `owner` → Permit2 that the pull spends. It does not fund the owner's token
* balance: add an `Erc20Balance` for that. Only the canonical Permit2 address
* `0x000000000022D473030F116dDEE9F6B43aC78BA3` is supported; on a chain
* without code there the simulation answers HTTP 422.
*
* Unlike the other variants this is not a compile precondition: no op declares
* a Permit2 allowance, so only a `POST /simulate` caller sends one.
*/
export type Permit2AllowanceRequirement = {
readonly type: 'Permit2Allowance';
/** Address whose tokens Permit2 pulls. */
readonly owner: string;
/** ERC-20 token Permit2 pulls. */
readonly token: string;
/** Address that calls `Permit2.transferFrom`. */
readonly spender: string;
/** Permit2 allowance amount, in the token's base units. */
readonly amount: bigint | string;
};
/**
* The funding-instruction union applied before a simulation. Four variants,
* discriminated by `type`.
*/
export type SlotFinderRequirement =
| Erc20BalanceRequirement
| NativeBalanceRequirement
| Erc20AllowanceRequirement
| Permit2AllowanceRequirement;
/** Request body for `POST /simulate`. */
export interface SimulateRequest {
/** EVM chain id. */
readonly chainId: number;
/**
* Sender of the simulated transaction. The VM bytecode is injected here so
* the inner call carries `msg.sender == from`.
*/
readonly from: string;
/** Target contract of the raw transaction. */
readonly to: string;
/** Pre-encoded transaction calldata (`0x`-prefixed hex). */
readonly data: string;
/**
* Native value (wei) sent with the inner call. Accepts `bigint | string`;
* defaults to `"0"` server-side when omitted.
*/
readonly value?: bigint | string;
/**
* Block number to simulate against. Omitted ⇒ the chain head. Named tags
* (e.g. "latest") are rejected with HTTP 400. A pinned block is always
* reported back as `block`/`timestamp`, whatever `reportBlockContext` says.
*/
readonly block?: number;
/**
* Report the `block`/`timestamp` the simulation ran against. Defaults to
* `true`. Resolving them costs the server one extra block-header RPC when
* `block` is omitted; pass `false` to skip it, and the result then carries
* no `block`/`timestamp`.
*/
readonly reportBlockContext?: boolean;
/** Funding instructions applied before simulation (max 40). */
readonly requirements?: readonly SlotFinderRequirement[];
/** Balances to read before and after the transaction (1–40 pairs). */
readonly trackedBalances: readonly TrackedBalance[];
}
/**
* One watched balance in a simulation response. `amount` is a decimal string;
* for `deltas` it is signed (`after - before`).
*/
export interface SimulateBalanceEntry {
readonly token: string;
readonly owner: string;
readonly amount: string;
}
/**
* HTTP 200, `status: "ok"`: the simulation ran successfully. Balance arrays are
* ordered to match the request `trackedBalances`. `gasUsed` is inner-call
* execution gas only. `block`/`timestamp` are present unless the request set
* `reportBlockContext: false` without pinning a `block`.
*
* Note: the array element types are intentionally mutable (`SimulateBalanceEntry[]`,
* not `readonly SimulateBalanceEntry[]`) so they stay structurally identical to
* the Zod-inferred wire types, which `z.array(...)` infers as mutable `T[]`. The
* bidirectional conformance assertion in `@lifi/api-schemas` relies on this.
*/
export interface SimulateOkResult {
readonly status: 'ok';
readonly block?: number;
readonly timestamp?: number;
readonly balancesBefore: SimulateBalanceEntry[];
readonly balancesAfter: SimulateBalanceEntry[];
readonly deltas: SimulateBalanceEntry[];
readonly gasUsed: string;
}
/** Decoded revert diagnostics, when slot-finder can parse the revert reason. */
export interface SimulateRevertDecodeResult {
readonly errorCandidates?: {
readonly decodedErrorSignature: string;
readonly decodedParams: string[];
/** Human-readable description; present when the selector is in the backend's error registry. */
readonly description?: string;
}[];
readonly error?: string;
}
/**
* HTTP 200, `status: "revert"`: the simulation ran but the transaction reverted
* on-chain. A revert is a *successful simulation*, not a transport error.
* `block`/`timestamp` are present under the same rule as on the `ok` arm.
*/
export interface SimulateRevertResult {
readonly status: 'revert';
readonly block?: number;
readonly timestamp?: number;
readonly revertReason?: string;
readonly code?: number;
readonly rawErrorBytes?: string;
readonly decodeResult?: SimulateRevertDecodeResult;
}
/**
* HTTP 422, `status: "error"`: the request was well-formed but the simulation
* could not be set up or run. `message` is intentionally generic.
*/
export interface SimulateSetupErrorResult {
readonly status: 'error';
readonly message: string;
}
/**
* Discriminated result of `POST /simulate`. `switch (result.status)` narrows to
* one member: `ok` and `revert` come back with HTTP 200, `error` with HTTP 422.
*/
export type SimulateResult =
| SimulateOkResult
| SimulateRevertResult
| SimulateSetupErrorResult;