@recta/client 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -56,6 +56,49 @@ your signer's address. Each step is also available alone: `evaluate`, `authorize
56
56
  An EOA signs its requests as EIP-191 signatures recovered to the sender's address. A smart account on Base signs
57
57
  through `smartAccountSigner` (see "Smart accounts").
58
58
 
59
+ ## Preflight in front of the bridge you already use
60
+
61
+ `withPreflight` runs Recta Preflight, free and unsigned, before every call to the bridge your agent already makes, so
62
+ the check happens on each transfer without the model having to remember it. It reports the route's total cost and
63
+ arrival time, and whether Recta proves a cheaper route (for example Base → Arbitrum, 1,000 USDC: 2.39 USDC cheaper than
64
+ LI.FI, measured on 2026-11-19). By default the bridge always runs, with the same arguments and the same result; a
65
+ failed or slow preflight (10 s at most) never blocks it. A transfer outside Recta's corridors is not checked.
66
+
67
+ A transfer you build yourself needs `source_network`, `source_asset`, `destination_network`, `destination_asset` and
68
+ `amount` (whole tokens; a string, a positive number or a bigint). From 0.1.11 a missing or unusable field throws
69
+ `PreflightInputError` before any request instead of sending an incomplete body, and without `onPreflight` the first
70
+ failed or refused preflight of each wrapped call is reported once with `console.warn` (`quiet: true` hides it).
71
+
72
+ LI.FI SDK:
73
+
74
+ ```ts
75
+ import { executeRoute } from "@lifi/sdk";
76
+ import { withPreflight, lifiTransfer } from "@recta/client";
77
+
78
+ const execute = withPreflight(executeRoute, (route) => lifiTransfer(route), {
79
+ onPreflight: ({ answer }) => console.log(answer?.outcome, answer?.saving_usdc),
80
+ // stopOnSaving: true, // throw RectaSavingFoundError before bridging when Recta proves a saving
81
+ });
82
+ await execute(route);
83
+ ```
84
+
85
+ A tool of the Vercel AI SDK (or any `{ execute(input) }` tool): its result gets a `recta_preflight` field, so the model
86
+ sees the cost, the arrival and any proven saving. With `stopOnSaving`, a proven saving returns
87
+ `{ status: "RECTA_SAVING_FOUND", recta_preflight }` instead of bridging, and the model can call the tool again with
88
+ `skip_preflight: true` to bridge anyway.
89
+
90
+ ```ts
91
+ import { withPreflightTool, transferFromChainTokens } from "@recta/client";
92
+
93
+ const bridgeTool = withPreflightTool(myBridgeTool, (input) =>
94
+ transferFromChainTokens({ fromChainId: input.fromChainId, toChainId: input.toChainId, fromToken: input.token, toToken: input.destinationToken, fromAmount: input.amount, baseline_provider: "across" }),
95
+ );
96
+ ```
97
+
98
+ `preflight(transfer)` makes one check directly; `transferFromChainTokens` and `lifiTransfer` turn chain ids, token
99
+ addresses and atomic amounts into Recta's network and asset keys. Requests carry `recta-client/<version> (preflight)`
100
+ and nothing else about you. 3 free checks a day per IP address.
101
+
59
102
  ## Which route to declare
60
103
 
61
104
  `baseline_provider` is the route your agent would use without Recta. Declare the one it really uses: the saving and
@@ -7,9 +7,9 @@
7
7
  */
8
8
  export declare const RECTA_ORIGIN = "https://api.recta.build";
9
9
  /** This package's version (equal to package.json, checked in CI). */
10
- export declare const CLIENT_VERSION = "0.1.9";
10
+ export declare const CLIENT_VERSION = "0.1.11";
11
11
  /** Sent on every request so Recta can count real use of this package apart from other clients (no address, no key). */
12
- export declare const USER_AGENT = "recta-client/0.1.9";
12
+ export declare const USER_AGENT = "recta-client/0.1.11";
13
13
  /** The fee: x402 `upto` on Base, a Permit2 `permitWitnessTransferFrom`. All lowercase. */
14
14
  export declare const FEE_CHAIN_ID = 8453;
15
15
  export declare const PERMIT2 = "0x000000000022d473030f116ddee9f6b43ac78ba3";
package/dist/constants.js CHANGED
@@ -7,7 +7,7 @@
7
7
  */
8
8
  export const RECTA_ORIGIN = "https://api.recta.build";
9
9
  /** This package's version (equal to package.json, checked in CI). */
10
- export const CLIENT_VERSION = "0.1.9";
10
+ export const CLIENT_VERSION = "0.1.11";
11
11
  /** Sent on every request so Recta can count real use of this package apart from other clients (no address, no key). */
12
12
  export const USER_AGENT = `recta-client/${CLIENT_VERSION}`;
13
13
  /** The fee: x402 `upto` on Base, a Permit2 `permitWitnessTransferFrom`. All lowercase. */
package/dist/index.d.ts CHANGED
@@ -7,3 +7,4 @@ export { parseWalletPolicy, type WalletPolicy, type WalletPolicyNetwork } from "
7
7
  export { viemSigner, viemChainReader, cdpSigner, smartAccountSigner, DEFAULT_USER_OPERATION_OVERHEAD_GAS, CDP_SEND_NETWORKS, type CdpEvmAccountLike, type CdpSendNetwork, type RectaSigner, type RectaChainReader, type RectaTransaction, type RectaTypedData } from "./signer.js";
8
8
  export { RectaCheckError, RectaHttpError, RectaDebtError, RectaSendUnknownError } from "./errors.js";
9
9
  export * as pins from "./constants.js";
10
+ export { preflight, withPreflight, withPreflightTool, preflightSummary, lifiTransfer, transferFromChainTokens, decimalAmount, RectaSavingFoundError, PreflightInputError, preflightBody, PREFLIGHT_PATH, PREFLIGHT_USER_AGENT, type PreflightTransfer, type PreflightAnswer, type PreflightOptions, type PreflightRouteEstimate, type WithPreflightOptions, type ChainTokenTransfer } from "./preflight.js";
package/dist/index.js CHANGED
@@ -7,3 +7,4 @@ export { parseWalletPolicy } from "./policy.js";
7
7
  export { viemSigner, viemChainReader, cdpSigner, smartAccountSigner, DEFAULT_USER_OPERATION_OVERHEAD_GAS, CDP_SEND_NETWORKS } from "./signer.js";
8
8
  export { RectaCheckError, RectaHttpError, RectaDebtError, RectaSendUnknownError } from "./errors.js";
9
9
  export * as pins from "./constants.js";
10
+ export { preflight, withPreflight, withPreflightTool, preflightSummary, lifiTransfer, transferFromChainTokens, decimalAmount, RectaSavingFoundError, PreflightInputError, preflightBody, PREFLIGHT_PATH, PREFLIGHT_USER_AGENT } from "./preflight.js";
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Recta Preflight (POST https://api.recta.build/v1/preflight): a free, unsigned check before a cross-chain USDC/USDT
3
+ * transfer. It answers the route's total cost and arrival time, and whether Recta proves a cheaper route. No key, no
4
+ * wallet; nothing is stored. `withPreflight` puts it in front of the bridge call an agent already makes, so the check
5
+ * runs on every transfer without the model having to remember it.
6
+ */
7
+ export declare const PREFLIGHT_PATH = "/v1/preflight";
8
+ /** Sent on every preflight this package makes, so Recta can count use of the wrapper apart from other clients. */
9
+ export declare const PREFLIGHT_USER_AGENT = "recta-client/0.1.11 (preflight)";
10
+ export interface PreflightTransfer {
11
+ /** Network keys as Recta names them: base, arbitrum, ethereum, optimism, polygon… */
12
+ readonly source_network: string;
13
+ /** USDC, USDT… */
14
+ readonly source_asset: string;
15
+ readonly destination_network: string;
16
+ /** USDC, USDT… (required by the preflight, even when it is the source asset). */
17
+ readonly destination_asset: string;
18
+ /** Whole tokens: "1000" (or 1000) with USDC is 1,000 USDC. */
19
+ readonly amount: string | number | bigint;
20
+ /** The route you would use (lifi, across, stargate_v2, cctp_v2_standard…). Absent: LI.FI, or Across where LI.FI does not apply. */
21
+ readonly baseline_provider?: string;
22
+ /** Your sending address, for the most exact figure. */
23
+ readonly sender?: string;
24
+ readonly recipient?: string;
25
+ }
26
+ export interface PreflightRouteEstimate {
27
+ readonly total_cost_usdc?: unknown;
28
+ readonly arrival?: unknown;
29
+ readonly [key: string]: unknown;
30
+ }
31
+ /** Recta's answer, as JSON, plus the HTTP status. `outcome` is set when Recta decided. */
32
+ export interface PreflightAnswer {
33
+ readonly http_status: number;
34
+ /** SAVING_FOUND, NO_SAVING, NOT_PROVEN or NO_SAVING_EXPECTED. */
35
+ readonly outcome?: string;
36
+ /** The proven saving (a lower bound), in USDC, when outcome is SAVING_FOUND. */
37
+ readonly saving_usdc?: string;
38
+ readonly your_route?: PreflightRouteEstimate;
39
+ readonly via_recta?: PreflightRouteEstimate | null;
40
+ /** How to get Recta's route: `body_to_sign`, `how`, `with_mcp`. */
41
+ readonly execute_via_recta?: Record<string, unknown>;
42
+ readonly message?: string;
43
+ readonly [key: string]: unknown;
44
+ }
45
+ export interface PreflightOptions {
46
+ readonly fetch?: typeof fetch;
47
+ /** Give up after this long (default 10 000 ms). The bridge is never held longer than this. */
48
+ readonly timeoutMs?: number;
49
+ }
50
+ /** Thrown by `preflight` before any request when the transfer lacks a needed field or holds a value it cannot send as given. */
51
+ export declare class PreflightInputError extends Error {
52
+ readonly missing: readonly string[];
53
+ readonly invalid: readonly string[];
54
+ constructor(missing: readonly string[], invalid?: readonly string[]);
55
+ }
56
+ /**
57
+ * What one transfer becomes on the wire: strings as given (trimmed), positive finite numbers and bigints as their exact
58
+ * decimal text (amount: 1000 → "1000"), camelCase names under Recta's (sourceNetwork → source_network). `missing` and
59
+ * `invalid` say what keeps it from being sent; no value is ever replaced by a default or an example.
60
+ */
61
+ export declare function preflightBody(transfer: PreflightTransfer | Readonly<Record<string, unknown>>): {
62
+ readonly body: Record<string, string>;
63
+ readonly missing: readonly string[];
64
+ readonly invalid: readonly string[];
65
+ };
66
+ /**
67
+ * One preflight. A transfer without the fields the preflight needs, or with a value it cannot send as given, throws
68
+ * PreflightInputError before any request; network failures, timeouts and non-JSON replies throw; a refusal
69
+ * (4xx/5xx JSON) is returned as is.
70
+ */
71
+ export declare function preflight(transfer: PreflightTransfer, options?: PreflightOptions): Promise<PreflightAnswer>;
72
+ /** A decimal string of whole tokens from an atomic amount: ("1000000000", 6) → "1000". */
73
+ export declare function decimalAmount(atomic: string | bigint, decimals: number): string;
74
+ export interface ChainTokenTransfer {
75
+ readonly fromChainId: number | string;
76
+ readonly toChainId: number | string;
77
+ readonly fromToken: string;
78
+ readonly toToken: string;
79
+ /** Atomic units of fromToken, as the SDKs pass it ("1000000000" is 1,000 USDC). */
80
+ readonly fromAmount: string | bigint;
81
+ readonly fromAddress?: string;
82
+ readonly toAddress?: string;
83
+ readonly baseline_provider?: string;
84
+ }
85
+ /**
86
+ * The preflight transfer for a transfer named by chain ids and token addresses, or undefined when Recta does not serve
87
+ * that corridor (then there is nothing to check, and the bridge runs as it would).
88
+ */
89
+ export declare function transferFromChainTokens(t: ChainTokenTransfer): PreflightTransfer | undefined;
90
+ type LifiToken = string | {
91
+ readonly address: string;
92
+ };
93
+ /**
94
+ * The preflight transfer for what LI.FI's SDK and API take or return, compared against LI.FI itself: a quote or routes
95
+ * request (`getQuote`, `getRoutes`, `GET /v1/quote`: fromChain, toChain, fromToken, toToken, fromAmount, fromAddress,
96
+ * toAddress) or a `Route` passed to `executeRoute` (fromChainId, toChainId, fromToken.address, toToken.address…).
97
+ */
98
+ export declare function lifiTransfer(request: {
99
+ readonly fromChain?: number | string;
100
+ readonly fromChainId?: number | string;
101
+ readonly toChain?: number | string;
102
+ readonly toChainId?: number | string;
103
+ readonly fromToken?: LifiToken;
104
+ readonly fromTokenAddress?: string;
105
+ readonly toToken?: LifiToken;
106
+ readonly toTokenAddress?: string;
107
+ readonly fromAmount: string | bigint;
108
+ readonly fromAddress?: string;
109
+ readonly toAddress?: string;
110
+ }): PreflightTransfer | undefined;
111
+ /** Thrown by a wrapped call with `stopOnSaving` when Recta proves a cheaper route: the bridge was not called. */
112
+ export declare class RectaSavingFoundError extends Error {
113
+ readonly answer: PreflightAnswer;
114
+ constructor(answer: PreflightAnswer);
115
+ }
116
+ export interface WithPreflightOptions extends PreflightOptions {
117
+ /** Every answer (or the error when the preflight could not be made). Never awaited longer than the bridge needs. */
118
+ readonly onPreflight?: (result: {
119
+ readonly transfer: PreflightTransfer;
120
+ readonly answer?: PreflightAnswer;
121
+ readonly error?: unknown;
122
+ }) => void;
123
+ /**
124
+ * Off by default: the bridge always runs. On: when Recta proves a saving, the wrapped call throws
125
+ * RectaSavingFoundError before the bridge is called, so the agent can choose Recta's route.
126
+ */
127
+ readonly stopOnSaving?: boolean;
128
+ /** Without onPreflight, the first refused or failed preflight is reported once with console.warn; true hides it. */
129
+ readonly quiet?: boolean;
130
+ }
131
+ /**
132
+ * `bridge` with Recta Preflight in front: each call first asks the preflight about the transfer `toTransfer` reads
133
+ * from the call's arguments (undefined: not a corridor Recta serves, no check), then calls `bridge` with the same
134
+ * arguments and returns its result unchanged. A failed or slow preflight never blocks the bridge.
135
+ *
136
+ * const executeRoute = withPreflight(lifi.executeRoute, (route) => lifiTransfer(route));
137
+ */
138
+ export declare function withPreflight<A extends unknown[], R>(bridge: (...args: A) => Promise<R>, toTransfer: (...args: A) => PreflightTransfer | undefined, options?: WithPreflightOptions): (...args: A) => Promise<R>;
139
+ /** The part of a preflight answer worth showing a model next to the bridge's own result. */
140
+ export declare function preflightSummary(answer: PreflightAnswer): Record<string, unknown>;
141
+ /**
142
+ * A tool (Vercel AI SDK `tool()`, or any `{ execute(input, ...rest) }`) with Recta Preflight in front of `execute`.
143
+ * The tool's result gets a `recta_preflight` field (when it is a plain object) so the model sees the cost, arrival and
144
+ * any proven saving. With `stopOnSaving`, a proven saving returns `{ status: "RECTA_SAVING_FOUND", recta_preflight }`
145
+ * instead of bridging, so the model can choose; call the tool again with `skip_preflight: true` in its input to bridge
146
+ * anyway (the field is removed before `execute` sees it).
147
+ */
148
+ export declare function withPreflightTool<T extends {
149
+ execute?: (input: never, ...rest: never[]) => unknown;
150
+ }>(tool: T, toTransfer: (input: Parameters<NonNullable<T["execute"]>>[0]) => PreflightTransfer | undefined, options?: WithPreflightOptions): T;
151
+ export {};
@@ -0,0 +1,265 @@
1
+ import { CLIENT_VERSION, RECTA_ORIGIN } from "./constants.js";
2
+ import { PINNED_ROUTES } from "./pinned-routes.js";
3
+ /**
4
+ * Recta Preflight (POST https://api.recta.build/v1/preflight): a free, unsigned check before a cross-chain USDC/USDT
5
+ * transfer. It answers the route's total cost and arrival time, and whether Recta proves a cheaper route. No key, no
6
+ * wallet; nothing is stored. `withPreflight` puts it in front of the bridge call an agent already makes, so the check
7
+ * runs on every transfer without the model having to remember it.
8
+ */
9
+ export const PREFLIGHT_PATH = "/v1/preflight";
10
+ /** Sent on every preflight this package makes, so Recta can count use of the wrapper apart from other clients. */
11
+ export const PREFLIGHT_USER_AGENT = `recta-client/${CLIENT_VERSION} (preflight)`;
12
+ const REQUIRED_FIELDS = ["source_network", "source_asset", "destination_network", "destination_asset", "amount"];
13
+ const FIELD_ALIASES = {
14
+ sourceNetwork: "source_network",
15
+ sourceAsset: "source_asset",
16
+ destinationNetwork: "destination_network",
17
+ destinationAsset: "destination_asset",
18
+ baselineProvider: "baseline_provider",
19
+ };
20
+ /** Thrown by `preflight` before any request when the transfer lacks a needed field or holds a value it cannot send as given. */
21
+ export class PreflightInputError extends Error {
22
+ missing;
23
+ invalid;
24
+ constructor(missing, invalid = []) {
25
+ const parts = [
26
+ ...(missing.length > 0 ? [`needs ${missing.join(", ")}`] : []),
27
+ ...(invalid.length > 0 ? [`cannot send ${invalid.join("; ")}`] : []),
28
+ ];
29
+ super(`Recta Preflight ${parts.join(" and ")}. Pass { source_network: "base", source_asset: "USDC", destination_network: "arbitrum", destination_asset: "USDC", amount: "1000" } ` +
30
+ `(whole tokens; a positive number or bigint is accepted), or build it with lifiTransfer() / transferFromChainTokens().`);
31
+ this.missing = missing;
32
+ this.invalid = invalid;
33
+ this.name = "PreflightInputError";
34
+ }
35
+ }
36
+ /** A value as the preflight reads it, or a reason it cannot be sent as given. Nothing is ever filled in or guessed. */
37
+ function wireValue(key, v) {
38
+ if (v === undefined || v === null)
39
+ return {};
40
+ if (typeof v === "string")
41
+ return v.trim() === "" ? {} : { value: v.trim() };
42
+ if (typeof v === "bigint")
43
+ return v > 0n ? { value: v.toString() } : { invalid: `${key} = ${v.toString()} (must be positive)` };
44
+ if (typeof v === "number") {
45
+ // String(n) is the shortest decimal that is exactly this number; an exponent form (1e21, 1e-7) is not a plain decimal.
46
+ const text = String(v);
47
+ if (!Number.isFinite(v) || v <= 0)
48
+ return { invalid: `${key} = ${text} (must be a positive finite number)` };
49
+ if (/e/i.test(text))
50
+ return { invalid: `${key} = ${text} (pass it as a decimal string)` };
51
+ if (key === "amount" && Number.isInteger(v) && !Number.isSafeInteger(v))
52
+ return { invalid: `${key} = ${text} (beyond exact number precision: pass a string or bigint)` };
53
+ return { value: text };
54
+ }
55
+ return { invalid: `${key} (a ${typeof v}, not a string or number)` };
56
+ }
57
+ /**
58
+ * What one transfer becomes on the wire: strings as given (trimmed), positive finite numbers and bigints as their exact
59
+ * decimal text (amount: 1000 → "1000"), camelCase names under Recta's (sourceNetwork → source_network). `missing` and
60
+ * `invalid` say what keeps it from being sent; no value is ever replaced by a default or an example.
61
+ */
62
+ export function preflightBody(transfer) {
63
+ const body = {};
64
+ const invalid = [];
65
+ for (const [k, v] of Object.entries(transfer)) {
66
+ const key = FIELD_ALIASES[k] ?? k;
67
+ const read = wireValue(key, v);
68
+ if (read.invalid !== undefined)
69
+ invalid.push(read.invalid);
70
+ if (read.value === undefined)
71
+ continue;
72
+ if (body[key] !== undefined && body[key] !== read.value)
73
+ invalid.push(`${key} given twice with different values (${body[key]}, ${read.value})`);
74
+ else
75
+ body[key] = read.value;
76
+ }
77
+ const missing = REQUIRED_FIELDS.filter((k) => body[k] === undefined && !invalid.some((i) => i.startsWith(`${k} `)));
78
+ return { body, missing, invalid };
79
+ }
80
+ /**
81
+ * One preflight. A transfer without the fields the preflight needs, or with a value it cannot send as given, throws
82
+ * PreflightInputError before any request; network failures, timeouts and non-JSON replies throw; a refusal
83
+ * (4xx/5xx JSON) is returned as is.
84
+ */
85
+ export async function preflight(transfer, options = {}) {
86
+ const { body, missing, invalid } = preflightBody(transfer);
87
+ if (missing.length > 0 || invalid.length > 0)
88
+ throw new PreflightInputError(missing, invalid);
89
+ const f = options.fetch ?? fetch;
90
+ const response = await f(`${RECTA_ORIGIN}${PREFLIGHT_PATH}`, {
91
+ method: "POST",
92
+ headers: { accept: "application/json", "content-type": "application/json", "user-agent": PREFLIGHT_USER_AGENT },
93
+ body: JSON.stringify(body),
94
+ signal: AbortSignal.timeout(options.timeoutMs ?? 10_000),
95
+ });
96
+ const parsed = JSON.parse(await response.text());
97
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
98
+ throw new Error(`preflight answered ${response.status} without a JSON object`);
99
+ return { ...parsed, http_status: response.status };
100
+ }
101
+ let tokenIndex;
102
+ let networkIndex;
103
+ function indexes() {
104
+ if (tokenIndex === undefined || networkIndex === undefined) {
105
+ const tokens = new Map();
106
+ const networks = new Map();
107
+ for (const [key, route] of Object.entries(PINNED_ROUTES)) {
108
+ const [from, to] = key.split(">");
109
+ const [srcNet, srcAsset] = from.split(":");
110
+ const [dstNet, dstAsset] = to.split(":");
111
+ networks.set(route.source_chain_id, srcNet);
112
+ tokens.set(`${route.source_chain_id}:${route.source_token.toLowerCase()}`, { network: srcNet, asset: srcAsset });
113
+ tokens.set(`${dstNet}:${route.output_token.toLowerCase()}`, { network: dstNet, asset: dstAsset });
114
+ }
115
+ tokenIndex = tokens;
116
+ networkIndex = networks;
117
+ }
118
+ return { tokens: tokenIndex, networks: networkIndex };
119
+ }
120
+ /** A decimal string of whole tokens from an atomic amount: ("1000000000", 6) → "1000". */
121
+ export function decimalAmount(atomic, decimals) {
122
+ const v = BigInt(atomic);
123
+ const unit = 10n ** BigInt(decimals);
124
+ const frac = (v % unit).toString().padStart(decimals, "0").replace(/0+$/, "");
125
+ return frac === "" ? (v / unit).toString() : `${v / unit}.${frac}`;
126
+ }
127
+ /**
128
+ * The preflight transfer for a transfer named by chain ids and token addresses, or undefined when Recta does not serve
129
+ * that corridor (then there is nothing to check, and the bridge runs as it would).
130
+ */
131
+ export function transferFromChainTokens(t) {
132
+ const { tokens, networks } = indexes();
133
+ const fromId = Number(t.fromChainId);
134
+ const toNetwork = networks.get(Number(t.toChainId));
135
+ const source = tokens.get(`${fromId}:${t.fromToken.toLowerCase()}`);
136
+ if (source === undefined || toNetwork === undefined)
137
+ return undefined;
138
+ const destination = tokens.get(`${toNetwork}:${t.toToken.toLowerCase()}`);
139
+ if (destination === undefined)
140
+ return undefined;
141
+ const route = PINNED_ROUTES[`${source.network}:${source.asset}>${destination.network}:${destination.asset}`];
142
+ if (route === undefined)
143
+ return undefined;
144
+ return {
145
+ source_network: source.network,
146
+ source_asset: source.asset,
147
+ destination_network: destination.network,
148
+ destination_asset: destination.asset,
149
+ amount: decimalAmount(t.fromAmount, route.source_decimals),
150
+ ...(t.baseline_provider === undefined ? {} : { baseline_provider: t.baseline_provider }),
151
+ ...(t.fromAddress === undefined ? {} : { sender: t.fromAddress }),
152
+ ...(t.toAddress === undefined ? {} : { recipient: t.toAddress }),
153
+ };
154
+ }
155
+ const addressOf = (t) => (t === undefined ? undefined : typeof t === "string" ? t : t.address);
156
+ /**
157
+ * The preflight transfer for what LI.FI's SDK and API take or return, compared against LI.FI itself: a quote or routes
158
+ * request (`getQuote`, `getRoutes`, `GET /v1/quote`: fromChain, toChain, fromToken, toToken, fromAmount, fromAddress,
159
+ * toAddress) or a `Route` passed to `executeRoute` (fromChainId, toChainId, fromToken.address, toToken.address…).
160
+ */
161
+ export function lifiTransfer(request) {
162
+ const fromChainId = request.fromChain ?? request.fromChainId;
163
+ const toChainId = request.toChain ?? request.toChainId;
164
+ const fromToken = addressOf(request.fromToken) ?? request.fromTokenAddress;
165
+ const toToken = addressOf(request.toToken) ?? request.toTokenAddress;
166
+ if (fromChainId === undefined || toChainId === undefined || fromToken === undefined || toToken === undefined)
167
+ return undefined;
168
+ return transferFromChainTokens({
169
+ fromChainId,
170
+ toChainId,
171
+ fromToken,
172
+ toToken,
173
+ fromAmount: request.fromAmount,
174
+ baseline_provider: "lifi",
175
+ ...(request.fromAddress === undefined ? {} : { fromAddress: request.fromAddress }),
176
+ ...(request.toAddress === undefined ? {} : { toAddress: request.toAddress }),
177
+ });
178
+ }
179
+ // --- The wrapper ---
180
+ /** Thrown by a wrapped call with `stopOnSaving` when Recta proves a cheaper route: the bridge was not called. */
181
+ export class RectaSavingFoundError extends Error {
182
+ answer;
183
+ constructor(answer) {
184
+ super(`Recta Preflight proved a cheaper route (saving ${answer.saving_usdc ?? "?"} USDC); the bridge was not called. Sign answer.execute_via_recta.body_to_sign to get it, or call again with the preflight off.`);
185
+ this.answer = answer;
186
+ this.name = "RectaSavingFoundError";
187
+ }
188
+ }
189
+ /** Without onPreflight a refused or failed preflight would go unseen: say so once per wrapped call, on the console. */
190
+ function warnOnce(options, state, problem) {
191
+ if (options.onPreflight !== undefined || options.quiet === true || state.warned)
192
+ return;
193
+ state.warned = true;
194
+ console.warn(`[@recta/client] Recta Preflight did not run: ${problem} The bridge still ran. Pass onPreflight to see every answer, or quiet: true to hide this.`);
195
+ }
196
+ /** The preflight for one call, or undefined; never throws (a failed preflight never blocks the bridge). */
197
+ async function check(transfer, options, state) {
198
+ if (transfer === undefined)
199
+ return undefined;
200
+ try {
201
+ const answer = await preflight(transfer, options);
202
+ options.onPreflight?.({ transfer, answer });
203
+ if (answer.outcome === undefined && answer.http_status >= 400)
204
+ warnOnce(options, state, `HTTP ${answer.http_status}${typeof answer["reason_code"] === "string" ? ` ${answer["reason_code"]}` : ""}${typeof answer.message === "string" ? `: ${answer.message}` : "."}`);
205
+ return answer;
206
+ }
207
+ catch (error) {
208
+ options.onPreflight?.({ transfer, error });
209
+ warnOnce(options, state, error instanceof Error ? error.message : String(error));
210
+ return undefined;
211
+ }
212
+ }
213
+ /**
214
+ * `bridge` with Recta Preflight in front: each call first asks the preflight about the transfer `toTransfer` reads
215
+ * from the call's arguments (undefined: not a corridor Recta serves, no check), then calls `bridge` with the same
216
+ * arguments and returns its result unchanged. A failed or slow preflight never blocks the bridge.
217
+ *
218
+ * const executeRoute = withPreflight(lifi.executeRoute, (route) => lifiTransfer(route));
219
+ */
220
+ export function withPreflight(bridge, toTransfer, options = {}) {
221
+ const state = { warned: false };
222
+ return async (...args) => {
223
+ const answer = await check(toTransfer(...args), options, state);
224
+ if (options.stopOnSaving === true && answer?.outcome === "SAVING_FOUND")
225
+ throw new RectaSavingFoundError(answer);
226
+ return bridge(...args);
227
+ };
228
+ }
229
+ /** The part of a preflight answer worth showing a model next to the bridge's own result. */
230
+ export function preflightSummary(answer) {
231
+ return {
232
+ outcome: answer.outcome ?? `HTTP ${answer.http_status}`,
233
+ ...(answer.saving_usdc === undefined ? {} : { saving_usdc: answer.saving_usdc }),
234
+ ...(answer.your_route === undefined ? {} : { your_route: answer.your_route }),
235
+ ...(answer.via_recta === undefined || answer.via_recta === null ? {} : { via_recta: answer.via_recta }),
236
+ ...(answer.outcome === "SAVING_FOUND" && answer.execute_via_recta !== undefined ? { execute_via_recta: answer.execute_via_recta } : {}),
237
+ ...(answer.message === undefined ? {} : { message: answer.message }),
238
+ };
239
+ }
240
+ /**
241
+ * A tool (Vercel AI SDK `tool()`, or any `{ execute(input, ...rest) }`) with Recta Preflight in front of `execute`.
242
+ * The tool's result gets a `recta_preflight` field (when it is a plain object) so the model sees the cost, arrival and
243
+ * any proven saving. With `stopOnSaving`, a proven saving returns `{ status: "RECTA_SAVING_FOUND", recta_preflight }`
244
+ * instead of bridging, so the model can choose; call the tool again with `skip_preflight: true` in its input to bridge
245
+ * anyway (the field is removed before `execute` sees it).
246
+ */
247
+ export function withPreflightTool(tool, toTransfer, options = {}) {
248
+ const execute = tool.execute;
249
+ if (execute === undefined)
250
+ return tool;
251
+ const state = { warned: false };
252
+ const wrapped = async (input, ...rest) => {
253
+ const skip = typeof input === "object" && input !== null && input["skip_preflight"] === true;
254
+ const clean = skip ? Object.fromEntries(Object.entries(input).filter(([k]) => k !== "skip_preflight")) : input;
255
+ const answer = skip ? undefined : await check(toTransfer(clean), options, state);
256
+ if (answer !== undefined && options.stopOnSaving === true && answer.outcome === "SAVING_FOUND") {
257
+ return { status: "RECTA_SAVING_FOUND", recta_preflight: preflightSummary(answer), note: "Recta proved a cheaper route; the bridge was not called. Sign recta_preflight.execute_via_recta.body_to_sign to get it, or call this tool again with skip_preflight: true to bridge anyway." };
258
+ }
259
+ const result = await execute.call(tool, clean, ...rest);
260
+ if (answer === undefined || typeof result !== "object" || result === null || Array.isArray(result))
261
+ return result;
262
+ return { ...result, recta_preflight: preflightSummary(answer) };
263
+ };
264
+ return { ...tool, execute: wrapped };
265
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recta/client",
3
- "version": "0.1.9",
3
+ "version": "0.1.11",
4
4
  "description": "Client for Recta (api.recta.build): evaluate a cross-chain stablecoin transfer, authorize Recta's 5 %-of-verified-saving fee, execute the committed route and report it, with local checks before every signature.",
5
5
  "license": "MIT",
6
6
  "author": "Recta (https://recta.build)",