@recta/client 0.1.8 → 0.1.10

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
@@ -12,13 +12,16 @@ evaluate → authorizeFee → execute → report
12
12
 
13
13
  It never receives a key. Before it signs or sends anything it checks it locally, and those checks cannot be turned off.
14
14
 
15
+ No code to write? [`@recta/mcp`](https://www.npmjs.com/package/@recta/mcp) runs this same flow as a local MCP server, and
16
+ Recta Preflight (<https://api.recta.build/preflight>) is a free hosted check with no wallet at all.
17
+
15
18
  ## Install
16
19
 
17
20
  ```
18
21
  npm install @recta/client viem
19
22
  ```
20
23
 
21
- `viem` (>= 2.38.3, < 3) is the only dependency, and you choose its version.
24
+ `viem` (>= 2.38.3, < 3) is a peer dependency: you choose and pin its version. The package has no other dependency.
22
25
 
23
26
  ## Use
24
27
 
@@ -36,9 +39,9 @@ const recta = createRectaClient({
36
39
  referrer: "0x…", // optional: the integrator that ships this agent (see "Referral for integrators")
37
40
  });
38
41
 
39
- // Dry run: evaluates and checks, signs no permit, sends no transaction. With Recta's collection on it stops at the
40
- // fee permit, before the transactions exist (Recta hands them out only after the permit is signed): `preview.fee`
41
- // carries the permit it would sign and `funds`, whether this wallet can pay it (see "Paying the fee").
42
+ // Dry run: evaluates and checks, signs no permit, sends no transaction. It stops at the fee permit, before the
43
+ // transactions exist (Recta hands them out only after the permit is signed): `preview.fee` carries the permit it
44
+ // would sign and `funds`, whether this wallet can pay it (see "Paying the fee").
42
45
  const preview = await recta.run(request, { dryRun: true });
43
46
 
44
47
  // The whole flow.
@@ -53,93 +56,56 @@ your signer's address. Each step is also available alone: `evaluate`, `authorize
53
56
  An EOA signs its requests as EIP-191 signatures recovered to the sender's address. A smart account on Base signs
54
57
  through `smartAccountSigner` (see "Smart accounts").
55
58
 
56
- ## Referral for integrators
57
-
58
- If you ship Recta inside a plugin, framework or agent template, set your own EVM address once as the `referrer` and
59
- every agent that runs your integration carries it. Recta fixes it at the agent's first signed evaluation and never
60
- changes it afterwards. You earn 20 % of the fees Recta actually collects from those agents (confirmed on chain) for
61
- 12 months, up to 200 USDC per agent, whether or not you pay fees yourself. One level only. The agent still pays exactly
62
- 5 % of its verified saving: your share comes out of Recta's 5 %, never on top of it.
63
-
64
- The referrer travels in the query of the agent's own signed requests, so nobody relaying them can add, drop or change
65
- it. It is ignored when it is the agent's own address. Terms and your balance: `GET /v1/referrals/balance`, signed by
66
- your address, once Recta's referral program is on (it starts together with fee collection).
59
+ ## Preflight in front of the bridge you already use
67
60
 
68
- ### Smart accounts
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.
69
66
 
70
- A smart account on Base works through `smartAccountSigner`: any viem smart account (for example
71
- `toCoinbaseSmartAccount` from `viem/account-abstraction`) and an ERC-4337 bundler client on Base, with a paymaster if
72
- one sponsors your gas:
67
+ LI.FI SDK:
73
68
 
74
69
  ```ts
75
- import { createPublicClient, http } from "viem";
76
- import { base } from "viem/chains";
77
- import { createBundlerClient, toCoinbaseSmartAccount } from "viem/account-abstraction";
78
- import { privateKeyToAccount } from "viem/accounts";
79
- import { createRectaClient, smartAccountSigner, viemChainReader } from "@recta/client";
70
+ import { executeRoute } from "@lifi/sdk";
71
+ import { withPreflight, lifiTransfer } from "@recta/client";
80
72
 
81
- const client = createPublicClient({ chain: base, transport: http(BASE_RPC) });
82
- const account = await toCoinbaseSmartAccount({ client, owners: [privateKeyToAccount(OWNER_KEY)], version: "1.1" });
83
- const bundlerClient = createBundlerClient({ account, client, transport: http(BUNDLER_URL) });
84
-
85
- const recta = createRectaClient({
86
- signer: smartAccountSigner({ account, bundlerClient }),
87
- chain: viemChainReader((chainId) => publicClients[chainId]),
88
- limits: { maxPermitUsdcAtomic: 5_000_000n, maxNativeValueWei: 10n ** 15n, minOutputBps: 9900 },
73
+ const execute = withPreflight(executeRoute, (route) => lifiTransfer(route), {
74
+ onPreflight: ({ answer }) => console.log(answer?.outcome, answer?.saving_usdc),
75
+ // stopOnSaving: true, // throw RectaSavingFoundError before bridging when Recta proves a saving
89
76
  });
77
+ await execute(route);
90
78
  ```
91
79
 
92
- - The account is the `sender`, holds the USDC and pays the fee. Recta accepts a smart account on Base only, so its
93
- transfers must start from Base; any other source is refused before any request.
94
- - Requests carry `x-recta-signer-chain: 8453` and are signed in Recta's v2 text, which also names the account and the
95
- chain. Recta asks the account on Base whether the signature holds (ERC-1271, or ERC-6492 while it is not deployed).
96
- - A fee or debt permit is signed only once the account is deployed on Base (Permit2 cannot deploy it): otherwise
97
- `RectaCheckError` `account_not_deployed`. Its first user operation deploys it, for example the bounded approval from
98
- `feeApproval()`.
99
- - Each checked route transaction is one user operation: the committed call, call gas limited to the committed gas
100
- limit, fees capped by the committed fee caps. The bundler client (and its paymaster) prepares it, and the signer
101
- checks it again before the account signs. Nothing is signed if they changed the call, the sender, the call gas, the
102
- fee caps or the init code, or if verification, pre-verification and paymaster gas exceed `maxOverheadGas` (default
103
- `DEFAULT_USER_OPERATION_OVERHEAD_GAS`, 1 500 000). A failed operation throws even when its bundle transaction
104
- succeeded. A receipt that does not arrive in time throws an error naming the operation: look it up before sending
105
- again.
106
- - Recta recognizes the operation in a bundle sent straight to an ERC-4337 EntryPoint (v0.6, v0.7 or v0.8). A bundler
107
- that relays through another contract first is not recognized.
108
- - `report` never sends a smart account's `approval_tx_hash`: the approval is the account's operation, not the
109
- committed transaction field by field, so Recta counts it at its committed upper bound.
110
-
111
- ### Coinbase CDP accounts
112
-
113
- A [Coinbase CDP](https://docs.cdp.coinbase.com) EVM server account (an EOA whose key stays in CDP) works through
114
- `cdpSigner`. This package does not depend on the CDP SDK:
80
+ A tool of the Vercel AI SDK (or any `{ execute(input) }` tool): its result gets a `recta_preflight` field, so the model
81
+ sees the cost, the arrival and any proven saving. With `stopOnSaving`, a proven saving returns
82
+ `{ status: "RECTA_SAVING_FOUND", recta_preflight }` instead of bridging, and the model can call the tool again with
83
+ `skip_preflight: true` to bridge anyway.
115
84
 
116
85
  ```ts
117
- import { CdpClient } from "@coinbase/cdp-sdk";
118
- import { createRectaClient, cdpSigner, viemChainReader } from "@recta/client";
86
+ import { withPreflightTool, transferFromChainTokens } from "@recta/client";
119
87
 
120
- const cdp = new CdpClient();
121
- const account = await cdp.evm.getOrCreateAccount({ name: "my-agent" });
122
-
123
- const recta = createRectaClient({
124
- signer: cdpSigner({ account }),
125
- chain: viemChainReader((chainId) => publicClients[chainId]),
126
- limits: { maxPermitUsdcAtomic: 5_000_000n, maxNativeValueWei: 10n ** 15n, minOutputBps: 9900 },
127
- });
88
+ const bridgeTool = withPreflightTool(myBridgeTool, (input) =>
89
+ transferFromChainTokens({ fromChainId: input.fromChainId, toChainId: input.toChainId, fromToken: input.token, toToken: input.destinationToken, fromAmount: input.amount, baseline_provider: "across" }),
90
+ );
128
91
  ```
129
92
 
130
- CDP signs Recta's requests and the fee permit. On Ethereum, Base, Arbitrum, Optimism, Polygon and Avalanche, CDP also
131
- sends each route transaction once this package has checked it. On any other chain, pass `walletClientFor` as well:
132
- CDP then signs the transaction and your RPC sends it.
93
+ `preflight(transfer)` makes one check directly; `transferFromChainTokens` and `lifiTransfer` turn chain ids, token
94
+ addresses and atomic amounts into Recta's network and asset keys. Requests carry `recta-client/<version> (preflight)`
95
+ and nothing else about you. 3 free checks a day per IP address.
133
96
 
134
- To limit the account to Recta's contracts at CDP's side too, apply the
135
- [CDP Policy Engine policy Recta serves](https://api.recta.build/v1/golden-corridor/wallet-policy/cdp). CDP refuses
136
- anything that policy does not allow, and it allows sending only on those six chains: with the policy applied, a route
137
- on any other chain is refused by CDP unless you add your own rule for it.
97
+ ## Which route to declare
98
+
99
+ `baseline_provider` is the route your agent would use without Recta. Declare the one it really uses: the saving and
100
+ the 5 % are measured against it, so declaring a worse route only makes you pay more. The fit check
101
+ (`GET https://api.recta.build/v1/golden-corridor/fit`) lists the routes you can declare for each corridor in
102
+ `declarable_baselines`.
103
+
104
+ If your agent bridges through LI.FI (its public API or an aggregator built on it), declare `lifi` wherever the fit
105
+ check lists it; it is refused with `latency_class` SECONDS or MINUTES. Recta reads LI.FI's own transaction, its fee
106
+ included.
138
107
 
139
- The saving is measured against `baseline_provider`: the route your agent would use without Recta. Declare the one it
140
- really uses. If your agent bridges through LI.FI (its public API or an aggregator built on it), declare `lifi`
141
- wherever the fit check (`GET /v1/golden-corridor/fit`) lists it in `declarable_baselines`; it is refused with
142
- `latency_class` SECONDS or MINUTES. Recta reads LI.FI's own transaction, its fee included. If that route is already the cheapest, Recta answers with no saving and charges nothing.
108
+ If your route is already the cheapest, Recta answers with no saving and charges nothing: keep your route.
143
109
 
144
110
  ## Paying the fee: USDC and the Permit2 allowance on Base
145
111
 
@@ -229,10 +195,6 @@ the declared messaging fee, within `maxNativeValueWei`.
229
195
  `RectaDebtError` with the offer. The package never signs a debt by itself: call `payDebt(offer)` if you agree (same
230
196
  checks, exact amount).
231
197
 
232
- ## What each request identifies
233
-
234
- Every request this package sends carries the User-Agent `recta-client/<version>`, so Recta can count real use of the package apart from other clients. It names the package and its version only: never an address, a key or a request body.
235
-
236
198
  ## Safety
237
199
 
238
200
  - **The key.** This package never receives a key: your signer signs and sends. Where the key lives is your choice of
@@ -240,9 +202,9 @@ Every request this package sends carries the User-Agent `recta-client/<version>`
240
202
  - **How much, and to whom.** The amount and the recipient are the ones your request names; the package checks that the
241
203
  route delivers exactly there, but it does not cap them. Cap them in your own code, or in your wallet's policy (a rule
242
204
  on the deposit call's recipient and amount, if your wallet supports one, and a daily limit; Recta's wallet policy
243
- limits contracts and approvals, not the amount or recipient a bridge deposit names). `@recta/mcp`'s local server (`npx @recta/mcp`, from 0.1.14) refuses a transfer
244
- above `RECTA_MAX_AMOUNT` (default 1000 tokens) or to a recipient that is neither the wallet nor in
245
- `RECTA_ALLOWED_RECIPIENTS`.
205
+ limits contracts and approvals, not the amount or recipient a bridge deposit names). `@recta/mcp`'s local server
206
+ (`npx @recta/mcp`, from 0.1.14) refuses a transfer above `RECTA_MAX_AMOUNT` (default 1000 tokens) or to a recipient
207
+ that is neither the wallet nor in `RECTA_ALLOWED_RECIPIENTS`.
246
208
  - **What Recta can take.** Only the fee permit, within `maxPermitUsdcAtomic`: exactly 5 % of the saving verified on
247
209
  chain, never more than the permit, nothing without a saving.
248
210
  - **Which contracts.** Exact-amount approvals to, and deposits into, the pinned bridge contracts (no message or hook at
@@ -274,6 +236,95 @@ Every request this package sends carries the User-Agent `recta-client/<version>`
274
236
  contract it does not know. A corridor or contract Recta adds later is served by the API at once, but refused by
275
237
  this package until a new release pins it.
276
238
 
239
+ ## Smart accounts
240
+
241
+ A smart account on Base works through `smartAccountSigner`: any viem smart account (for example
242
+ `toCoinbaseSmartAccount` from `viem/account-abstraction`) and an ERC-4337 bundler client on Base, with a paymaster if
243
+ one sponsors your gas:
244
+
245
+ ```ts
246
+ import { createPublicClient, http } from "viem";
247
+ import { base } from "viem/chains";
248
+ import { createBundlerClient, toCoinbaseSmartAccount } from "viem/account-abstraction";
249
+ import { privateKeyToAccount } from "viem/accounts";
250
+ import { createRectaClient, smartAccountSigner, viemChainReader } from "@recta/client";
251
+
252
+ const client = createPublicClient({ chain: base, transport: http(BASE_RPC) });
253
+ const account = await toCoinbaseSmartAccount({ client, owners: [privateKeyToAccount(OWNER_KEY)], version: "1.1" });
254
+ const bundlerClient = createBundlerClient({ account, client, transport: http(BUNDLER_URL) });
255
+
256
+ const recta = createRectaClient({
257
+ signer: smartAccountSigner({ account, bundlerClient }),
258
+ chain: viemChainReader((chainId) => publicClients[chainId]),
259
+ limits: { maxPermitUsdcAtomic: 5_000_000n, maxNativeValueWei: 10n ** 15n, minOutputBps: 9900 },
260
+ });
261
+ ```
262
+
263
+ - The account is the `sender`, holds the USDC and pays the fee. Recta accepts a smart account on Base only, so its
264
+ transfers must start from Base; any other source is refused before any request.
265
+ - Requests carry `x-recta-signer-chain: 8453` and are signed in Recta's v2 text, which also names the account and the
266
+ chain. Recta asks the account on Base whether the signature holds (ERC-1271, or ERC-6492 while it is not deployed).
267
+ - A fee or debt permit is signed only once the account is deployed on Base (Permit2 cannot deploy it): otherwise
268
+ `RectaCheckError` `account_not_deployed`. Its first user operation deploys it, for example the bounded approval from
269
+ `feeApproval()`.
270
+ - Each checked route transaction is one user operation: the committed call, call gas limited to the committed gas
271
+ limit, fees capped by the committed fee caps. The bundler client (and its paymaster) prepares it, and the signer
272
+ checks it again before the account signs. Nothing is signed if they changed the call, the sender, the call gas, the
273
+ fee caps or the init code, or if verification, pre-verification and paymaster gas exceed `maxOverheadGas` (default
274
+ `DEFAULT_USER_OPERATION_OVERHEAD_GAS`, 1 500 000). A failed operation throws even when its bundle transaction
275
+ succeeded. A receipt that does not arrive in time throws an error naming the operation: look it up before sending
276
+ again.
277
+ - Recta recognizes the operation in a bundle sent straight to an ERC-4337 EntryPoint (v0.6, v0.7 or v0.8). A bundler
278
+ that relays through another contract first is not recognized.
279
+ - `report` never sends a smart account's `approval_tx_hash`: the approval is the account's operation, not the
280
+ committed transaction field by field, so Recta counts it at its committed upper bound.
281
+
282
+ ## Coinbase CDP accounts
283
+
284
+ A [Coinbase CDP](https://docs.cdp.coinbase.com) EVM server account (an EOA whose key stays in CDP) works through
285
+ `cdpSigner`. This package does not depend on the CDP SDK:
286
+
287
+ ```ts
288
+ import { CdpClient } from "@coinbase/cdp-sdk";
289
+ import { createRectaClient, cdpSigner, viemChainReader } from "@recta/client";
290
+
291
+ const cdp = new CdpClient();
292
+ const account = await cdp.evm.getOrCreateAccount({ name: "my-agent" });
293
+
294
+ const recta = createRectaClient({
295
+ signer: cdpSigner({ account }),
296
+ chain: viemChainReader((chainId) => publicClients[chainId]),
297
+ limits: { maxPermitUsdcAtomic: 5_000_000n, maxNativeValueWei: 10n ** 15n, minOutputBps: 9900 },
298
+ });
299
+ ```
300
+
301
+ CDP signs Recta's requests and the fee permit. On Ethereum, Base, Arbitrum, Optimism, Polygon and Avalanche, CDP also
302
+ sends each route transaction once this package has checked it. On any other chain, pass `walletClientFor` as well:
303
+ CDP then signs the transaction and your RPC sends it.
304
+
305
+ To limit the account to Recta's contracts at CDP's side too, apply the
306
+ [CDP Policy Engine policy Recta serves](https://api.recta.build/v1/golden-corridor/wallet-policy/cdp). CDP refuses
307
+ anything that policy does not allow, and it allows sending only on those six chains: with the policy applied, a route
308
+ on any other chain is refused by CDP unless you add your own rule for it.
309
+
310
+ ## Referral for integrators
311
+
312
+ If you ship Recta inside a plugin, framework or agent template, set your own EVM address once as the `referrer` and
313
+ every agent that runs your integration carries it. Recta fixes it at the agent's first signed evaluation and never
314
+ changes it afterwards. You earn 20 % of the fees Recta actually collects from those agents (confirmed on chain) for
315
+ 12 months, up to 200 USDC per agent, whether or not you pay fees yourself. One level only. The agent still pays exactly
316
+ 5 % of its verified saving: your share comes out of Recta's 5 %, never on top of it.
317
+
318
+ The referrer travels in the query of the agent's own signed requests, so nobody relaying them can add, drop or change
319
+ it. It is ignored when it is the agent's own address.
320
+
321
+ Your reward is applied as a discount on your own Recta fees, or paid in USDC on Base once it reaches 10 USDC. Terms,
322
+ your balance and the agents you referred: `GET https://api.recta.build/v1/referrals/balance`, signed by your address.
323
+
324
+ ## What each request identifies
325
+
326
+ Every request this package sends carries the User-Agent `recta-client/<version>`, so Recta can count real use of the package apart from other clients. It names the package and its version only: never an address, a key or a request body.
327
+
277
328
  ## Provenance
278
329
 
279
330
  Every release is published from [RectaBuild/recta](https://github.com/RectaBuild/recta) by GitHub Actions with npm
package/dist/client.js CHANGED
@@ -156,10 +156,10 @@ export function createRectaClient(options) {
156
156
  return a.body;
157
157
  }
158
158
  /**
159
- * Step 2: the decision's committed transactions. With Recta's collection on, the artifact first asks for the fee
159
+ * Step 2: the decision's committed transactions. The artifact first asks for the fee
160
160
  * permit: it is checked, rebuilt, and signed only if it passes and the payer holds the permit's amount in USDC on
161
161
  * Base with at least that allowance to Permit2 (otherwise RectaCheckError `fee_balance` / `fee_allowance`, nothing
162
- * signed; see `feeApproval`); then it is stored and the answer carries the artifact. With `dryRun` and collection on,
162
+ * signed; see `feeApproval`); then it is stored and the answer carries the artifact. With `dryRun`,
163
163
  * it stops at the permit, before the artifact exists, and returns the typed data it would sign and the payer's funds:
164
164
  * the transactions can only be inspected after the permit is signed. Pass the evaluation's `request` so a route that
165
165
  * starts from USDC on Base reserves its own amount from the balance; `execute` checks the funds again either way.
@@ -351,7 +351,7 @@ export function createRectaClient(options) {
351
351
  }
352
352
  /**
353
353
  * The four steps in a row. With `dryRun`, it evaluates and checks but signs no permit and sends no transaction: it
354
- * stops at the permit (collection on) or after checking the artifact (collection off).
354
+ * stops at the permit (or, on a service that does not collect, after checking the artifact).
355
355
  */
356
356
  async function run(request, opts = {}) {
357
357
  const decision = await evaluate(request, opts.idempotencyKey === undefined ? {} : { idempotencyKey: opts.idempotencyKey });
@@ -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.8";
10
+ export declare const CLIENT_VERSION = "0.1.10";
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.8";
12
+ export declare const USER_AGENT = "recta-client/0.1.10";
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.8";
10
+ export const CLIENT_VERSION = "0.1.10";
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, 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, PREFLIGHT_PATH, PREFLIGHT_USER_AGENT } from "./preflight.js";
@@ -0,0 +1,128 @@
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.10 (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
+ readonly destination_asset?: string;
17
+ /** Whole tokens as a decimal string: "1000" with USDC is 1,000 USDC. */
18
+ readonly amount: string;
19
+ /** The route you would use (lifi, across, stargate_v2, cctp_v2_standard…). Absent: LI.FI, or Across where LI.FI does not apply. */
20
+ readonly baseline_provider?: string;
21
+ /** Your sending address, for the most exact figure. */
22
+ readonly sender?: string;
23
+ readonly recipient?: string;
24
+ }
25
+ export interface PreflightRouteEstimate {
26
+ readonly total_cost_usdc?: unknown;
27
+ readonly arrival?: unknown;
28
+ readonly [key: string]: unknown;
29
+ }
30
+ /** Recta's answer, as JSON, plus the HTTP status. `outcome` is set when Recta decided. */
31
+ export interface PreflightAnswer {
32
+ readonly http_status: number;
33
+ /** SAVING_FOUND, NO_SAVING, NOT_PROVEN or NO_SAVING_EXPECTED. */
34
+ readonly outcome?: string;
35
+ /** The proven saving (a lower bound), in USDC, when outcome is SAVING_FOUND. */
36
+ readonly saving_usdc?: string;
37
+ readonly your_route?: PreflightRouteEstimate;
38
+ readonly via_recta?: PreflightRouteEstimate | null;
39
+ /** How to get Recta's route: `body_to_sign`, `how`, `with_mcp`. */
40
+ readonly execute_via_recta?: Record<string, unknown>;
41
+ readonly message?: string;
42
+ readonly [key: string]: unknown;
43
+ }
44
+ export interface PreflightOptions {
45
+ readonly fetch?: typeof fetch;
46
+ /** Give up after this long (default 10 000 ms). The bridge is never held longer than this. */
47
+ readonly timeoutMs?: number;
48
+ }
49
+ /** One preflight. Network failures, timeouts and non-JSON replies throw; a refusal (4xx/5xx JSON) is returned as is. */
50
+ export declare function preflight(transfer: PreflightTransfer, options?: PreflightOptions): Promise<PreflightAnswer>;
51
+ /** A decimal string of whole tokens from an atomic amount: ("1000000000", 6) → "1000". */
52
+ export declare function decimalAmount(atomic: string | bigint, decimals: number): string;
53
+ export interface ChainTokenTransfer {
54
+ readonly fromChainId: number | string;
55
+ readonly toChainId: number | string;
56
+ readonly fromToken: string;
57
+ readonly toToken: string;
58
+ /** Atomic units of fromToken, as the SDKs pass it ("1000000000" is 1,000 USDC). */
59
+ readonly fromAmount: string | bigint;
60
+ readonly fromAddress?: string;
61
+ readonly toAddress?: string;
62
+ readonly baseline_provider?: string;
63
+ }
64
+ /**
65
+ * The preflight transfer for a transfer named by chain ids and token addresses, or undefined when Recta does not serve
66
+ * that corridor (then there is nothing to check, and the bridge runs as it would).
67
+ */
68
+ export declare function transferFromChainTokens(t: ChainTokenTransfer): PreflightTransfer | undefined;
69
+ type LifiToken = string | {
70
+ readonly address: string;
71
+ };
72
+ /**
73
+ * The preflight transfer for what LI.FI's SDK and API take or return, compared against LI.FI itself: a quote or routes
74
+ * request (`getQuote`, `getRoutes`, `GET /v1/quote`: fromChain, toChain, fromToken, toToken, fromAmount, fromAddress,
75
+ * toAddress) or a `Route` passed to `executeRoute` (fromChainId, toChainId, fromToken.address, toToken.address…).
76
+ */
77
+ export declare function lifiTransfer(request: {
78
+ readonly fromChain?: number | string;
79
+ readonly fromChainId?: number | string;
80
+ readonly toChain?: number | string;
81
+ readonly toChainId?: number | string;
82
+ readonly fromToken?: LifiToken;
83
+ readonly fromTokenAddress?: string;
84
+ readonly toToken?: LifiToken;
85
+ readonly toTokenAddress?: string;
86
+ readonly fromAmount: string | bigint;
87
+ readonly fromAddress?: string;
88
+ readonly toAddress?: string;
89
+ }): PreflightTransfer | undefined;
90
+ /** Thrown by a wrapped call with `stopOnSaving` when Recta proves a cheaper route: the bridge was not called. */
91
+ export declare class RectaSavingFoundError extends Error {
92
+ readonly answer: PreflightAnswer;
93
+ constructor(answer: PreflightAnswer);
94
+ }
95
+ export interface WithPreflightOptions extends PreflightOptions {
96
+ /** Every answer (or the error when the preflight could not be made). Never awaited longer than the bridge needs. */
97
+ readonly onPreflight?: (result: {
98
+ readonly transfer: PreflightTransfer;
99
+ readonly answer?: PreflightAnswer;
100
+ readonly error?: unknown;
101
+ }) => void;
102
+ /**
103
+ * Off by default: the bridge always runs. On: when Recta proves a saving, the wrapped call throws
104
+ * RectaSavingFoundError before the bridge is called, so the agent can choose Recta's route.
105
+ */
106
+ readonly stopOnSaving?: boolean;
107
+ }
108
+ /**
109
+ * `bridge` with Recta Preflight in front: each call first asks the preflight about the transfer `toTransfer` reads
110
+ * from the call's arguments (undefined: not a corridor Recta serves, no check), then calls `bridge` with the same
111
+ * arguments and returns its result unchanged. A failed or slow preflight never blocks the bridge.
112
+ *
113
+ * const executeRoute = withPreflight(lifi.executeRoute, (route) => lifiTransfer(route));
114
+ */
115
+ export declare function withPreflight<A extends unknown[], R>(bridge: (...args: A) => Promise<R>, toTransfer: (...args: A) => PreflightTransfer | undefined, options?: WithPreflightOptions): (...args: A) => Promise<R>;
116
+ /** The part of a preflight answer worth showing a model next to the bridge's own result. */
117
+ export declare function preflightSummary(answer: PreflightAnswer): Record<string, unknown>;
118
+ /**
119
+ * A tool (Vercel AI SDK `tool()`, or any `{ execute(input, ...rest) }`) with Recta Preflight in front of `execute`.
120
+ * The tool's result gets a `recta_preflight` field (when it is a plain object) so the model sees the cost, arrival and
121
+ * any proven saving. With `stopOnSaving`, a proven saving returns `{ status: "RECTA_SAVING_FOUND", recta_preflight }`
122
+ * instead of bridging, so the model can choose; call the tool again with `skip_preflight: true` in its input to bridge
123
+ * anyway (the field is removed before `execute` sees it).
124
+ */
125
+ export declare function withPreflightTool<T extends {
126
+ execute?: (input: never, ...rest: never[]) => unknown;
127
+ }>(tool: T, toTransfer: (input: Parameters<NonNullable<T["execute"]>>[0]) => PreflightTransfer | undefined, options?: WithPreflightOptions): T;
128
+ export {};
@@ -0,0 +1,182 @@
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
+ /** One preflight. Network failures, timeouts and non-JSON replies throw; a refusal (4xx/5xx JSON) is returned as is. */
13
+ export async function preflight(transfer, options = {}) {
14
+ const body = {};
15
+ for (const [k, v] of Object.entries(transfer))
16
+ if (typeof v === "string" && v !== "")
17
+ body[k] = v;
18
+ const f = options.fetch ?? fetch;
19
+ const response = await f(`${RECTA_ORIGIN}${PREFLIGHT_PATH}`, {
20
+ method: "POST",
21
+ headers: { accept: "application/json", "content-type": "application/json", "user-agent": PREFLIGHT_USER_AGENT },
22
+ body: JSON.stringify(body),
23
+ signal: AbortSignal.timeout(options.timeoutMs ?? 10_000),
24
+ });
25
+ const parsed = JSON.parse(await response.text());
26
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
27
+ throw new Error(`preflight answered ${response.status} without a JSON object`);
28
+ return { ...parsed, http_status: response.status };
29
+ }
30
+ let tokenIndex;
31
+ let networkIndex;
32
+ function indexes() {
33
+ if (tokenIndex === undefined || networkIndex === undefined) {
34
+ const tokens = new Map();
35
+ const networks = new Map();
36
+ for (const [key, route] of Object.entries(PINNED_ROUTES)) {
37
+ const [from, to] = key.split(">");
38
+ const [srcNet, srcAsset] = from.split(":");
39
+ const [dstNet, dstAsset] = to.split(":");
40
+ networks.set(route.source_chain_id, srcNet);
41
+ tokens.set(`${route.source_chain_id}:${route.source_token.toLowerCase()}`, { network: srcNet, asset: srcAsset });
42
+ tokens.set(`${dstNet}:${route.output_token.toLowerCase()}`, { network: dstNet, asset: dstAsset });
43
+ }
44
+ tokenIndex = tokens;
45
+ networkIndex = networks;
46
+ }
47
+ return { tokens: tokenIndex, networks: networkIndex };
48
+ }
49
+ /** A decimal string of whole tokens from an atomic amount: ("1000000000", 6) → "1000". */
50
+ export function decimalAmount(atomic, decimals) {
51
+ const v = BigInt(atomic);
52
+ const unit = 10n ** BigInt(decimals);
53
+ const frac = (v % unit).toString().padStart(decimals, "0").replace(/0+$/, "");
54
+ return frac === "" ? (v / unit).toString() : `${v / unit}.${frac}`;
55
+ }
56
+ /**
57
+ * The preflight transfer for a transfer named by chain ids and token addresses, or undefined when Recta does not serve
58
+ * that corridor (then there is nothing to check, and the bridge runs as it would).
59
+ */
60
+ export function transferFromChainTokens(t) {
61
+ const { tokens, networks } = indexes();
62
+ const fromId = Number(t.fromChainId);
63
+ const toNetwork = networks.get(Number(t.toChainId));
64
+ const source = tokens.get(`${fromId}:${t.fromToken.toLowerCase()}`);
65
+ if (source === undefined || toNetwork === undefined)
66
+ return undefined;
67
+ const destination = tokens.get(`${toNetwork}:${t.toToken.toLowerCase()}`);
68
+ if (destination === undefined)
69
+ return undefined;
70
+ const route = PINNED_ROUTES[`${source.network}:${source.asset}>${destination.network}:${destination.asset}`];
71
+ if (route === undefined)
72
+ return undefined;
73
+ return {
74
+ source_network: source.network,
75
+ source_asset: source.asset,
76
+ destination_network: destination.network,
77
+ destination_asset: destination.asset,
78
+ amount: decimalAmount(t.fromAmount, route.source_decimals),
79
+ ...(t.baseline_provider === undefined ? {} : { baseline_provider: t.baseline_provider }),
80
+ ...(t.fromAddress === undefined ? {} : { sender: t.fromAddress }),
81
+ ...(t.toAddress === undefined ? {} : { recipient: t.toAddress }),
82
+ };
83
+ }
84
+ const addressOf = (t) => (t === undefined ? undefined : typeof t === "string" ? t : t.address);
85
+ /**
86
+ * The preflight transfer for what LI.FI's SDK and API take or return, compared against LI.FI itself: a quote or routes
87
+ * request (`getQuote`, `getRoutes`, `GET /v1/quote`: fromChain, toChain, fromToken, toToken, fromAmount, fromAddress,
88
+ * toAddress) or a `Route` passed to `executeRoute` (fromChainId, toChainId, fromToken.address, toToken.address…).
89
+ */
90
+ export function lifiTransfer(request) {
91
+ const fromChainId = request.fromChain ?? request.fromChainId;
92
+ const toChainId = request.toChain ?? request.toChainId;
93
+ const fromToken = addressOf(request.fromToken) ?? request.fromTokenAddress;
94
+ const toToken = addressOf(request.toToken) ?? request.toTokenAddress;
95
+ if (fromChainId === undefined || toChainId === undefined || fromToken === undefined || toToken === undefined)
96
+ return undefined;
97
+ return transferFromChainTokens({
98
+ fromChainId,
99
+ toChainId,
100
+ fromToken,
101
+ toToken,
102
+ fromAmount: request.fromAmount,
103
+ baseline_provider: "lifi",
104
+ ...(request.fromAddress === undefined ? {} : { fromAddress: request.fromAddress }),
105
+ ...(request.toAddress === undefined ? {} : { toAddress: request.toAddress }),
106
+ });
107
+ }
108
+ // --- The wrapper ---
109
+ /** Thrown by a wrapped call with `stopOnSaving` when Recta proves a cheaper route: the bridge was not called. */
110
+ export class RectaSavingFoundError extends Error {
111
+ answer;
112
+ constructor(answer) {
113
+ 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.`);
114
+ this.answer = answer;
115
+ this.name = "RectaSavingFoundError";
116
+ }
117
+ }
118
+ /** The preflight for one call, or undefined; never throws (a failed preflight never blocks the bridge). */
119
+ async function check(transfer, options) {
120
+ if (transfer === undefined)
121
+ return undefined;
122
+ try {
123
+ const answer = await preflight(transfer, options);
124
+ options.onPreflight?.({ transfer, answer });
125
+ return answer;
126
+ }
127
+ catch (error) {
128
+ options.onPreflight?.({ transfer, error });
129
+ return undefined;
130
+ }
131
+ }
132
+ /**
133
+ * `bridge` with Recta Preflight in front: each call first asks the preflight about the transfer `toTransfer` reads
134
+ * from the call's arguments (undefined: not a corridor Recta serves, no check), then calls `bridge` with the same
135
+ * arguments and returns its result unchanged. A failed or slow preflight never blocks the bridge.
136
+ *
137
+ * const executeRoute = withPreflight(lifi.executeRoute, (route) => lifiTransfer(route));
138
+ */
139
+ export function withPreflight(bridge, toTransfer, options = {}) {
140
+ return async (...args) => {
141
+ const answer = await check(toTransfer(...args), options);
142
+ if (options.stopOnSaving === true && answer?.outcome === "SAVING_FOUND")
143
+ throw new RectaSavingFoundError(answer);
144
+ return bridge(...args);
145
+ };
146
+ }
147
+ /** The part of a preflight answer worth showing a model next to the bridge's own result. */
148
+ export function preflightSummary(answer) {
149
+ return {
150
+ outcome: answer.outcome ?? `HTTP ${answer.http_status}`,
151
+ ...(answer.saving_usdc === undefined ? {} : { saving_usdc: answer.saving_usdc }),
152
+ ...(answer.your_route === undefined ? {} : { your_route: answer.your_route }),
153
+ ...(answer.via_recta === undefined || answer.via_recta === null ? {} : { via_recta: answer.via_recta }),
154
+ ...(answer.outcome === "SAVING_FOUND" && answer.execute_via_recta !== undefined ? { execute_via_recta: answer.execute_via_recta } : {}),
155
+ ...(answer.message === undefined ? {} : { message: answer.message }),
156
+ };
157
+ }
158
+ /**
159
+ * A tool (Vercel AI SDK `tool()`, or any `{ execute(input, ...rest) }`) with Recta Preflight in front of `execute`.
160
+ * The tool's result gets a `recta_preflight` field (when it is a plain object) so the model sees the cost, arrival and
161
+ * any proven saving. With `stopOnSaving`, a proven saving returns `{ status: "RECTA_SAVING_FOUND", recta_preflight }`
162
+ * instead of bridging, so the model can choose; call the tool again with `skip_preflight: true` in its input to bridge
163
+ * anyway (the field is removed before `execute` sees it).
164
+ */
165
+ export function withPreflightTool(tool, toTransfer, options = {}) {
166
+ const execute = tool.execute;
167
+ if (execute === undefined)
168
+ return tool;
169
+ const wrapped = async (input, ...rest) => {
170
+ const skip = typeof input === "object" && input !== null && input["skip_preflight"] === true;
171
+ const clean = skip ? Object.fromEntries(Object.entries(input).filter(([k]) => k !== "skip_preflight")) : input;
172
+ const answer = skip ? undefined : await check(toTransfer(clean), options);
173
+ if (answer !== undefined && options.stopOnSaving === true && answer.outcome === "SAVING_FOUND") {
174
+ 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." };
175
+ }
176
+ const result = await execute.call(tool, clean, ...rest);
177
+ if (answer === undefined || typeof result !== "object" || result === null || Array.isArray(result))
178
+ return result;
179
+ return { ...result, recta_preflight: preflightSummary(answer) };
180
+ };
181
+ return { ...tool, execute: wrapped };
182
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recta/client",
3
- "version": "0.1.8",
3
+ "version": "0.1.10",
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)",