-
Notifications
You must be signed in to change notification settings - Fork 6
feat: add signed context oracle support #436
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
hardyjosh
wants to merge
9
commits into
master
Choose a base branch
from
feat/oracle-support
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
9fd313d
Add oracle support to rain.solver
8fabe2e
fix: address review feedback on oracle module
5513fce
fix: use viem instead of ethers for ABI encoding
e0cf6c5
feat: add retry with backoff and per-URL cooloff for oracle fetching
08a544f
refactor: remove retry delays, use fail-fast with cooloff only
4162cbb
refactor: move oracle health state to OracleManager class on OrderMan…
77d52ba
refactor: drop OracleManager class, use SharedState + standalone fns
82ae2c9
refactor: use Result type instead of throwing
1c39eea
refactor: use existing order types, drop redundant SignedContextV1 in…
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import { Pair } from "../order/types"; | ||
| import { SharedState } from "../state"; | ||
| import { Result } from "../common"; | ||
| import { extractOracleUrl, fetchSignedContext } from "."; | ||
|
|
||
| /** | ||
| * If the order has oracle metadata, fetch signed context and inject it | ||
| * into the takeOrder struct. Called with SharedState as `this` to access | ||
| * the oracle health map. | ||
| * | ||
| * Returns Result — callers decide how to handle failures. | ||
| */ | ||
| export async function fetchOracleContext( | ||
| this: SharedState, | ||
| orderDetails: Pair, | ||
| ): Promise<Result<void, string>> { | ||
| const orderMeta = (orderDetails as any).meta; | ||
| if (!orderMeta) return Result.ok(undefined); | ||
|
|
||
| const oracleUrl = extractOracleUrl(orderMeta); | ||
| if (!oracleUrl) return Result.ok(undefined); | ||
|
|
||
| const result = await fetchSignedContext( | ||
| oracleUrl, | ||
| [ | ||
| { | ||
| order: orderDetails.takeOrder.struct.order, | ||
| inputIOIndex: orderDetails.takeOrder.struct.inputIOIndex, | ||
| outputIOIndex: orderDetails.takeOrder.struct.outputIOIndex, | ||
| counterparty: "0x0000000000000000000000000000000000000000", | ||
| }, | ||
| ], | ||
| this.oracleHealth, | ||
| ); | ||
|
|
||
| if (result.isErr()) { | ||
| return Result.err(result.error); | ||
| } | ||
|
|
||
| orderDetails.takeOrder.struct.signedContext = result.value; | ||
| return Result.ok(undefined); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,215 @@ | ||
| import { encodeAbiParameters, hexToBytes } from "viem"; | ||
| import { Result } from "../common"; | ||
| import { Order } from "../order/types"; | ||
|
|
||
| export { fetchOracleContext } from "./fetch"; | ||
|
|
||
| /** | ||
| * Extract oracle URL from order meta bytes. | ||
| * | ||
| * TODO: Replace with SDK's RaindexOrder.extractOracleUrl() once the wasm | ||
| * package includes it. Pending rain.orderbook PR #2478. | ||
| * | ||
| * @param metaHex - Hex string of meta bytes (e.g. "0x1234...") | ||
| * @returns Oracle URL if found, null otherwise | ||
| */ | ||
| export function extractOracleUrl(metaHex: string): string | null { | ||
| // TODO: Implement CBOR decoding to find RaindexSignedContextOracleV1 | ||
| // magic number 0xff7a1507ba4419ca and extract URL. | ||
| return null; | ||
| } | ||
|
|
||
| /** | ||
| * Oracle request entry — mirrors the spec's (OrderV4, uint256, uint256, address) tuple. | ||
| * Uses the existing Order.V3 | Order.V4 types from the order module. | ||
| */ | ||
| export interface OracleOrderRequest { | ||
| order: Order.V3 | Order.V4; | ||
| inputIOIndex: number; | ||
| outputIOIndex: number; | ||
| counterparty: `0x${string}`; | ||
| } | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Oracle health / cooloff | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| /** Per-request timeout */ | ||
| export const ORACLE_TIMEOUT_MS = 5_000; | ||
| /** How long to skip a failing oracle (ms) */ | ||
| export const COOLOFF_DURATION_MS = 5 * 60 * 1_000; | ||
| /** Consecutive failures before entering cooloff */ | ||
| export const COOLOFF_THRESHOLD = 3; | ||
|
|
||
| export type OracleHealthMap = Map<string, { consecutiveFailures: number; cooloffUntil: number }>; | ||
|
|
||
| export function isInCooloff(healthMap: OracleHealthMap, url: string): boolean { | ||
| const state = healthMap.get(url); | ||
| if (!state || state.cooloffUntil === 0) return false; | ||
| if (Date.now() >= state.cooloffUntil) { | ||
| state.cooloffUntil = 0; | ||
| return false; | ||
| } | ||
| return true; | ||
| } | ||
|
|
||
| export function recordOracleSuccess(healthMap: OracleHealthMap, url: string) { | ||
| healthMap.set(url, { consecutiveFailures: 0, cooloffUntil: 0 }); | ||
| } | ||
|
|
||
| export function recordOracleFailure(healthMap: OracleHealthMap, url: string) { | ||
| const state = healthMap.get(url) ?? { consecutiveFailures: 0, cooloffUntil: 0 }; | ||
| state.consecutiveFailures++; | ||
| if (state.consecutiveFailures >= COOLOFF_THRESHOLD) { | ||
| state.cooloffUntil = Date.now() + COOLOFF_DURATION_MS; | ||
| console.warn( | ||
| `Oracle ${url} entered cooloff for ${COOLOFF_DURATION_MS / 1000}s ` + | ||
| `after ${state.consecutiveFailures} consecutive failures`, | ||
| ); | ||
| } | ||
| healthMap.set(url, state); | ||
| } | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // ABI encoding | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| /** | ||
| * ABI parameter definition for the batch oracle request body. | ||
| * Encodes as: abi.encode((OrderV4, uint256, uint256, address)[]) | ||
| * | ||
| * Uses the same struct shape as ABI.Orderbook.V5.OrderV4 / IOV2 / EvaluableV4. | ||
| */ | ||
| const oracleBatchAbiParams = [ | ||
| { | ||
| type: "tuple[]", | ||
| components: [ | ||
| { | ||
| name: "order", | ||
| type: "tuple", | ||
| components: [ | ||
| { name: "owner", type: "address" }, | ||
| { | ||
| name: "evaluable", | ||
| type: "tuple", | ||
| components: [ | ||
| { name: "interpreter", type: "address" }, | ||
| { name: "store", type: "address" }, | ||
| { name: "bytecode", type: "bytes" }, | ||
| ], | ||
| }, | ||
| { | ||
| name: "validInputs", | ||
| type: "tuple[]", | ||
| components: [ | ||
| { name: "token", type: "address" }, | ||
| { name: "vaultId", type: "bytes32" }, | ||
| ], | ||
| }, | ||
| { | ||
| name: "validOutputs", | ||
| type: "tuple[]", | ||
| components: [ | ||
| { name: "token", type: "address" }, | ||
| { name: "vaultId", type: "bytes32" }, | ||
| ], | ||
| }, | ||
| { name: "nonce", type: "bytes32" }, | ||
| ], | ||
| }, | ||
| { name: "inputIOIndex", type: "uint256" }, | ||
| { name: "outputIOIndex", type: "uint256" }, | ||
| { name: "counterparty", type: "address" }, | ||
| ], | ||
| }, | ||
| ] as const; | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Fetch | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| /** | ||
| * Fetch signed contexts from an oracle endpoint (batch format). | ||
| * | ||
| * POSTs abi.encode((OrderV4, uint256, uint256, address)[]) and expects | ||
| * a JSON array of SignedContextV1 objects back, matching request length. | ||
| * | ||
| * Single attempt with a hard timeout — no retries, no in-loop delays. | ||
| * Uses the provided health map for cooloff tracking. | ||
| */ | ||
| export async function fetchSignedContext( | ||
| url: string, | ||
| orders: OracleOrderRequest[], | ||
| healthMap: OracleHealthMap, | ||
| ): Promise<Result<any[], string>> { | ||
| if (isInCooloff(healthMap, url)) { | ||
| return Result.err(`Oracle ${url} is in cooloff, skipping`); | ||
| } | ||
|
|
||
| const tuples = orders.map((req) => ({ | ||
| order: req.order, | ||
| inputIOIndex: BigInt(req.inputIOIndex), | ||
| outputIOIndex: BigInt(req.outputIOIndex), | ||
| counterparty: req.counterparty, | ||
| })); | ||
|
|
||
| const encoded = encodeAbiParameters(oracleBatchAbiParams, [tuples]); | ||
| const body = hexToBytes(encoded); | ||
|
|
||
| const controller = new AbortController(); | ||
| const timeout = setTimeout(() => controller.abort(), ORACLE_TIMEOUT_MS); | ||
|
|
||
| let json: unknown; | ||
| try { | ||
| const response = await fetch(url, { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/octet-stream" }, | ||
| body, | ||
| signal: controller.signal, | ||
| }); | ||
|
|
||
| if (!response.ok) { | ||
| recordOracleFailure(healthMap, url); | ||
| return Result.err(`Oracle request failed: ${response.status} ${response.statusText}`); | ||
| } | ||
|
|
||
| json = await response.json(); | ||
| } catch (err) { | ||
| recordOracleFailure(healthMap, url); | ||
| return Result.err( | ||
| `Oracle fetch error: ${err instanceof Error ? err.message : String(err)}`, | ||
| ); | ||
| } finally { | ||
| clearTimeout(timeout); | ||
| } | ||
|
|
||
| if (!Array.isArray(json)) { | ||
| recordOracleFailure(healthMap, url); | ||
| return Result.err("Oracle response must be an array"); | ||
| } | ||
|
|
||
| if (json.length !== orders.length) { | ||
| recordOracleFailure(healthMap, url); | ||
| return Result.err( | ||
| `Oracle response length (${json.length}) does not match request length (${orders.length})`, | ||
| ); | ||
| } | ||
|
|
||
| // Validate shape of each entry | ||
| for (let i = 0; i < json.length; i++) { | ||
| const entry = json[i]; | ||
| if ( | ||
| typeof entry !== "object" || | ||
| entry === null || | ||
| typeof entry.signer !== "string" || | ||
| !Array.isArray(entry.context) || | ||
| typeof entry.signature !== "string" | ||
| ) { | ||
| recordOracleFailure(healthMap, url); | ||
| return Result.err(`Oracle response[${i}] is not a valid SignedContextV1`); | ||
| } | ||
| } | ||
|
|
||
| recordOracleSuccess(healthMap, url); | ||
| return Result.ok(json); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.