@recta/client 0.1.7 → 0.1.9

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,18 @@ 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).
67
-
68
- ### Smart accounts
69
-
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:
73
-
74
- ```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";
80
-
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 },
89
- });
90
- ```
91
-
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:
115
-
116
- ```ts
117
- import { CdpClient } from "@coinbase/cdp-sdk";
118
- import { createRectaClient, cdpSigner, viemChainReader } from "@recta/client";
119
-
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
- });
128
- ```
59
+ ## Which route to declare
129
60
 
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.
61
+ `baseline_provider` is the route your agent would use without Recta. Declare the one it really uses: the saving and
62
+ the 5 % are measured against it, so declaring a worse route only makes you pay more. The fit check
63
+ (`GET https://api.recta.build/v1/golden-corridor/fit`) lists the routes you can declare for each corridor in
64
+ `declarable_baselines`.
133
65
 
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.
66
+ If your agent bridges through LI.FI (its public API or an aggregator built on it), declare `lifi` wherever the fit
67
+ check lists it; it is refused with `latency_class` SECONDS or MINUTES. Recta reads LI.FI's own transaction, its fee
68
+ included.
138
69
 
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.
70
+ If your route is already the cheapest, Recta answers with no saving and charges nothing: keep your route.
143
71
 
144
72
  ## Paying the fee: USDC and the Permit2 allowance on Base
145
73
 
@@ -177,6 +105,21 @@ Since 0.1.4 `RectaChainReader` requires `readFeeFunds`; `createRectaClient` refu
177
105
  A custom `RectaChainReader` must implement `readFeeFunds(owner)`; when it cannot read Base it must throw, and the permit
178
106
  is then not signed (a dry run reports `funds: null` and the reason).
179
107
 
108
+ ## When a send goes wrong
109
+
110
+ `execute()` sends the route's transactions in order. With a local key (`viemSigner`), the approval and the transfer
111
+ leave back to back on consecutive nonces, so they fit in Recta's 60-second window even on Ethereum; other wallets wait
112
+ for each receipt. Errors say what happened:
113
+
114
+ - `RectaSendUnknownError` (`check` `transaction_unknown`): a transaction may have been sent and its outcome is not
115
+ known. `sentTxHashes` lists every hash already sent, `resultId` the evaluation, and `transferSent` is `NO` only when the
116
+ transfer was certainly never sent (otherwise `UNKNOWN`). Look them up on chain (with no hash,
117
+ the account's latest transactions) before sending anything again, by Recta or any other route. If the transfer
118
+ succeeded, report it with `report(resultId, originTxHash)`.
119
+ - `RectaCheckError` `transaction_failed`: the named transaction was mined and reverted.
120
+ - `wallet_*` checks (the MetaMask signer): their message says what was sent.
121
+ - Any other `RectaCheckError`: nothing was signed or sent.
122
+
180
123
  ## What is checked before signing
181
124
 
182
125
  **Pins.** The package carries Recta's fee addresses in its own code: Permit2, x402's `upto` proxy, USDC on Base,
@@ -214,9 +157,36 @@ the declared messaging fee, within `maxNativeValueWei`.
214
157
  `RectaDebtError` with the offer. The package never signs a debt by itself: call `payDebt(offer)` if you agree (same
215
158
  checks, exact amount).
216
159
 
217
- ## What each request identifies
218
-
219
- 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.
160
+ ## Safety
161
+
162
+ - **The key.** This package never receives a key: your signer signs and sends. Where the key lives is your choice of
163
+ signer (`viemSigner` with your own account, `cdpSigner` with the key kept at Coinbase, `smartAccountSigner`).
164
+ - **How much, and to whom.** The amount and the recipient are the ones your request names; the package checks that the
165
+ route delivers exactly there, but it does not cap them. Cap them in your own code, or in your wallet's policy (a rule
166
+ on the deposit call's recipient and amount, if your wallet supports one, and a daily limit; Recta's wallet policy
167
+ limits contracts and approvals, not the amount or recipient a bridge deposit names). `@recta/mcp`'s local server
168
+ (`npx @recta/mcp`, from 0.1.14) refuses a transfer above `RECTA_MAX_AMOUNT` (default 1000 tokens) or to a recipient
169
+ that is neither the wallet nor in `RECTA_ALLOWED_RECIPIENTS`.
170
+ - **What Recta can take.** Only the fee permit, within `maxPermitUsdcAtomic`: exactly 5 % of the saving verified on
171
+ chain, never more than the permit, nothing without a saving.
172
+ - **Which contracts.** Exact-amount approvals to, and deposits into, the pinned bridge contracts (no message or hook at
173
+ the destination), and a bounded USDC approval to Permit2 on Base for the fee (`feeApproval`). The bridges are run by
174
+ third parties and some of their contracts are upgradeable proxies: the package pins their addresses, not their code.
175
+ - **If the price moves.** The route transaction fixes the least the recipient gets (`minOutputBps`) and its gas price
176
+ ceilings; a decision already past its expiry is refused before the first transaction is sent. The fee is computed on
177
+ the saving of the transfer as executed.
178
+ - **Replays.** A signed request carries its time (within 5 minutes of Recta's clock, either way) and its body's hash,
179
+ and an evaluation its idempotency key: a repeat returns the stored decision. A fee permit has a Permit2 nonce and can
180
+ be used once. Route transactions use your wallet's own nonce.
181
+ - **What Recta records.** Each evaluation (sender, recipient, amount, corridor) and its decision; Recta does not delete
182
+ these records today. A verified saving is published in the public savings ledger with both transaction hashes. Recta's
183
+ log lines for evaluations and executions carry no wallet address, transfer amount or transaction hash; Cloudflare, which hosts Recta, sees each request's IP
184
+ address and keeps its request logs, whose URLs can include an address, 7 days.
185
+ - **Review.** Audited adversarially by Recta, with the fee contract simulated against Base's real Permit2; no
186
+ independent external audit yet. Recta's server is not open source; this package is. Start with small amounts.
187
+ - **Changes and supply chain.** Pin the exact version you reviewed and check `npm audit signatures`: Recta's routes,
188
+ contracts and fee addresses are pinned in each release, and a service that no longer matches them is refused, never
189
+ followed. It has no dependency of its own: `viem` is a peer range, so pin it too.
220
190
 
221
191
  ## Limits of this version
222
192
 
@@ -228,6 +198,95 @@ Every request this package sends carries the User-Agent `recta-client/<version>`
228
198
  contract it does not know. A corridor or contract Recta adds later is served by the API at once, but refused by
229
199
  this package until a new release pins it.
230
200
 
201
+ ## Smart accounts
202
+
203
+ A smart account on Base works through `smartAccountSigner`: any viem smart account (for example
204
+ `toCoinbaseSmartAccount` from `viem/account-abstraction`) and an ERC-4337 bundler client on Base, with a paymaster if
205
+ one sponsors your gas:
206
+
207
+ ```ts
208
+ import { createPublicClient, http } from "viem";
209
+ import { base } from "viem/chains";
210
+ import { createBundlerClient, toCoinbaseSmartAccount } from "viem/account-abstraction";
211
+ import { privateKeyToAccount } from "viem/accounts";
212
+ import { createRectaClient, smartAccountSigner, viemChainReader } from "@recta/client";
213
+
214
+ const client = createPublicClient({ chain: base, transport: http(BASE_RPC) });
215
+ const account = await toCoinbaseSmartAccount({ client, owners: [privateKeyToAccount(OWNER_KEY)], version: "1.1" });
216
+ const bundlerClient = createBundlerClient({ account, client, transport: http(BUNDLER_URL) });
217
+
218
+ const recta = createRectaClient({
219
+ signer: smartAccountSigner({ account, bundlerClient }),
220
+ chain: viemChainReader((chainId) => publicClients[chainId]),
221
+ limits: { maxPermitUsdcAtomic: 5_000_000n, maxNativeValueWei: 10n ** 15n, minOutputBps: 9900 },
222
+ });
223
+ ```
224
+
225
+ - The account is the `sender`, holds the USDC and pays the fee. Recta accepts a smart account on Base only, so its
226
+ transfers must start from Base; any other source is refused before any request.
227
+ - Requests carry `x-recta-signer-chain: 8453` and are signed in Recta's v2 text, which also names the account and the
228
+ chain. Recta asks the account on Base whether the signature holds (ERC-1271, or ERC-6492 while it is not deployed).
229
+ - A fee or debt permit is signed only once the account is deployed on Base (Permit2 cannot deploy it): otherwise
230
+ `RectaCheckError` `account_not_deployed`. Its first user operation deploys it, for example the bounded approval from
231
+ `feeApproval()`.
232
+ - Each checked route transaction is one user operation: the committed call, call gas limited to the committed gas
233
+ limit, fees capped by the committed fee caps. The bundler client (and its paymaster) prepares it, and the signer
234
+ checks it again before the account signs. Nothing is signed if they changed the call, the sender, the call gas, the
235
+ fee caps or the init code, or if verification, pre-verification and paymaster gas exceed `maxOverheadGas` (default
236
+ `DEFAULT_USER_OPERATION_OVERHEAD_GAS`, 1 500 000). A failed operation throws even when its bundle transaction
237
+ succeeded. A receipt that does not arrive in time throws an error naming the operation: look it up before sending
238
+ again.
239
+ - Recta recognizes the operation in a bundle sent straight to an ERC-4337 EntryPoint (v0.6, v0.7 or v0.8). A bundler
240
+ that relays through another contract first is not recognized.
241
+ - `report` never sends a smart account's `approval_tx_hash`: the approval is the account's operation, not the
242
+ committed transaction field by field, so Recta counts it at its committed upper bound.
243
+
244
+ ## Coinbase CDP accounts
245
+
246
+ A [Coinbase CDP](https://docs.cdp.coinbase.com) EVM server account (an EOA whose key stays in CDP) works through
247
+ `cdpSigner`. This package does not depend on the CDP SDK:
248
+
249
+ ```ts
250
+ import { CdpClient } from "@coinbase/cdp-sdk";
251
+ import { createRectaClient, cdpSigner, viemChainReader } from "@recta/client";
252
+
253
+ const cdp = new CdpClient();
254
+ const account = await cdp.evm.getOrCreateAccount({ name: "my-agent" });
255
+
256
+ const recta = createRectaClient({
257
+ signer: cdpSigner({ account }),
258
+ chain: viemChainReader((chainId) => publicClients[chainId]),
259
+ limits: { maxPermitUsdcAtomic: 5_000_000n, maxNativeValueWei: 10n ** 15n, minOutputBps: 9900 },
260
+ });
261
+ ```
262
+
263
+ CDP signs Recta's requests and the fee permit. On Ethereum, Base, Arbitrum, Optimism, Polygon and Avalanche, CDP also
264
+ sends each route transaction once this package has checked it. On any other chain, pass `walletClientFor` as well:
265
+ CDP then signs the transaction and your RPC sends it.
266
+
267
+ To limit the account to Recta's contracts at CDP's side too, apply the
268
+ [CDP Policy Engine policy Recta serves](https://api.recta.build/v1/golden-corridor/wallet-policy/cdp). CDP refuses
269
+ anything that policy does not allow, and it allows sending only on those six chains: with the policy applied, a route
270
+ on any other chain is refused by CDP unless you add your own rule for it.
271
+
272
+ ## Referral for integrators
273
+
274
+ If you ship Recta inside a plugin, framework or agent template, set your own EVM address once as the `referrer` and
275
+ every agent that runs your integration carries it. Recta fixes it at the agent's first signed evaluation and never
276
+ changes it afterwards. You earn 20 % of the fees Recta actually collects from those agents (confirmed on chain) for
277
+ 12 months, up to 200 USDC per agent, whether or not you pay fees yourself. One level only. The agent still pays exactly
278
+ 5 % of its verified saving: your share comes out of Recta's 5 %, never on top of it.
279
+
280
+ The referrer travels in the query of the agent's own signed requests, so nobody relaying them can add, drop or change
281
+ it. It is ignored when it is the agent's own address.
282
+
283
+ Your reward is applied as a discount on your own Recta fees, or paid in USDC on Base once it reaches 10 USDC. Terms,
284
+ your balance and the agents you referred: `GET https://api.recta.build/v1/referrals/balance`, signed by your address.
285
+
286
+ ## What each request identifies
287
+
288
+ 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.
289
+
231
290
  ## Provenance
232
291
 
233
292
  Every release is published from [RectaBuild/recta](https://github.com/RectaBuild/recta) by GitHub Actions with npm
package/dist/client.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { keccak256 } from "viem";
2
2
  import { checkExecutionArtifact } from "./artifact.js";
3
3
  import { FEE_CHAIN_ID, ISSUED_AT_HEADER, PATHS, RECTA_ORIGIN, SIGNATURE_HEADER, SIGNED_REQUEST_PREFIX, SIGNER_CHAIN_HEADER, SIGNER_HEADER, SMART_ACCOUNT_SIGNED_REQUEST_PREFIX, USER_AGENT } from "./constants.js";
4
- import { RectaCheckError, RectaDebtError, RectaHttpError } from "./errors.js";
4
+ import { RectaCheckError, RectaDebtError, RectaHttpError, RectaSendUnknownError } from "./errors.js";
5
5
  import { checkFeePermit } from "./fee.js";
6
6
  import { assertFeeReady, feeReadiness, permit2ApprovalTransaction, routeReserveOf, safeErrorText } from "./funds.js";
7
7
  import { parseWalletPolicy } from "./policy.js";
@@ -55,6 +55,15 @@ const resultIdOf = (v) => {
55
55
  throw new RectaCheckError("result_id", "not a Recta result id");
56
56
  return v;
57
57
  };
58
+ /** A send whose outcome is not known (owner rule 2026-11-11): every hash already sent and the result_id, and the
59
+ * instruction to look them up (and the account's nonce) before anything is sent again. */
60
+ function unknownSend(resultId, sent, what, transferSent) {
61
+ const hashes = sent.length === 0 ? "No transaction hash came back" : `${sent.map((s) => `${s.role} ${s.hash}`).join(", ")} sent`;
62
+ // Fable A-1 on #23: whether the transfer was attempted is said by the caller, never deduced from the hashes (a
63
+ // transfer whose send failed has no hash and may still have been broadcast).
64
+ const may = transferSent === "NO" ? "the transfer was not sent, but the approval's outcome is not known" : "the transfer may have moved funds";
65
+ return new RectaSendUnknownError(`${hashes} for ${resultId}, then ${what}: ${may}, so look ${sent.length === 0 ? "the account's latest transactions (its nonce)" : "these hashes"} up on chain (and report the EXECUTION if it succeeded) before sending anything again`, resultId, sent.map((s) => ({ ...s })), transferSent);
66
+ }
58
67
  /**
59
68
  * Recta's flow for an agent that holds its own EOA or smart account (on Base): evaluate → authorizeFee → execute → report. Every step can be
60
69
  * called alone. Nothing is signed or sent before this package's own checks pass (see `checkFeePermit` and
@@ -147,10 +156,10 @@ export function createRectaClient(options) {
147
156
  return a.body;
148
157
  }
149
158
  /**
150
- * 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
151
160
  * permit: it is checked, rebuilt, and signed only if it passes and the payer holds the permit's amount in USDC on
152
161
  * Base with at least that allowance to Permit2 (otherwise RectaCheckError `fee_balance` / `fee_allowance`, nothing
153
- * 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`,
154
163
  * it stops at the permit, before the artifact exists, and returns the typed data it would sign and the payer's funds:
155
164
  * the transactions can only be inspected after the permit is signed. Pass the evaluation's `request` so a route that
156
165
  * starts from USDC on Base reserves its own amount from the balance; `execute` checks the funds again either way.
@@ -215,7 +224,8 @@ export function createRectaClient(options) {
215
224
  await walletPolicy();
216
225
  return checkExecutionArtifact(artifact, { resultId: resultIdOf(resultId), request, limits: { signer: payer, nowUnix: nowUnix(), maxNativeValueWei: limits.maxNativeValueWei, minOutputBps: limits.minOutputBps } });
217
226
  }
218
- /** Step 3: checks, then sends the transactions in order, each mined successfully before the next. */
227
+ /** Step 3: checks, then sends the transactions in order: each mined successfully before the next, or, with a signer
228
+ * that can (`sendInSequence`), all of them back to back and then awaited (`executeInSequence`). */
219
229
  async function execute(resultId, artifact, request) {
220
230
  // The last moment before anything is sent: with a fee authorized for this decision, the payer must still hold it
221
231
  // in USDC on Base (plus the transfer itself when it starts from Base USDC) with the Permit2 allowance for it.
@@ -223,12 +233,35 @@ export function createRectaClient(options) {
223
233
  if (fee !== undefined)
224
234
  assertFeeReady(feeReadiness(await chain.readFeeFunds(signer.address), fee, routeReserveOf(request)));
225
235
  const checked = await check(resultId, artifact, request);
236
+ if (signer.sendInSequence !== undefined && checked.transactions.length > 1)
237
+ return executeInSequence(resultId, checked, signer.sendInSequence.bind(signer));
226
238
  let approvalTxHash;
239
+ const sent = [];
227
240
  for (const tx of checked.transactions) {
228
241
  const { role, ...send } = tx;
229
- const hash = await signer.sendTransaction(send);
230
- if (!(await chain.waitForSuccess(tx.chainId, hash)))
231
- throw new RectaCheckError("transaction_failed", `${role} transaction ${hash} reverted`);
242
+ let hash;
243
+ try {
244
+ hash = await signer.sendTransaction(send);
245
+ }
246
+ catch (e) {
247
+ // Fable M-3 on #22 (owner rule 2026-11-11): a send that failed without a hash may still have been broadcast.
248
+ // A wallet's own RectaCheckError (MetaMask's journal and recovery, which key on its own checks) passes as it is:
249
+ // that wallet waits inside its own send, so a hash before this one is already mined and in its journal.
250
+ if (e instanceof RectaCheckError)
251
+ throw e;
252
+ // An APPROVAL send that failed means the transfer was never asked for; anything else may have left.
253
+ throw unknownSend(resultId, sent, `sending the ${role} failed without a hash (${safeErrorText(e).slice(0, 200)})`, role === "APPROVAL" ? "NO" : "UNKNOWN");
254
+ }
255
+ sent.push({ role, chainId: tx.chainId, hash });
256
+ let ok;
257
+ try {
258
+ ok = await chain.waitForSuccess(tx.chainId, hash);
259
+ }
260
+ catch (e) {
261
+ throw unknownSend(resultId, sent, `waiting for a receipt failed (${safeErrorText(e).slice(0, 200)})`, role === "APPROVAL" ? "NO" : "UNKNOWN");
262
+ }
263
+ if (!ok)
264
+ throw new RectaCheckError("transaction_failed", `${role} transaction ${hash} reverted${role === "APPROVAL" ? ": nothing else was sent" : ": nothing was moved by it"}`);
232
265
  if (role === "APPROVAL")
233
266
  approvalTxHash = hash;
234
267
  else
@@ -236,6 +269,45 @@ export function createRectaClient(options) {
236
269
  }
237
270
  throw new RectaCheckError("transaction_order", "the artifact has no execution");
238
271
  }
272
+ /**
273
+ * Recta's saving holds for a short horizon after its anchor block (60 s). On Ethereum, waiting for the approval's
274
+ * receipt before sending the deposit took the deposit past it (Recta BIT-OPS-182: mined 72 s after the anchor, nothing
275
+ * accrued). A signer that can (`sendInSequence`: a local key) sends the approval and the deposit one after another on
276
+ * consecutive nonces, and they are awaited only then. From the first hash on, every failure names every hash sent:
277
+ * whether the deposit moved funds is then UNKNOWN until the chain says so, and nothing may be sent again before.
278
+ */
279
+ async function executeInSequence(resultId, checked, sendInSequence) {
280
+ const sent = [];
281
+ // In sequence the transfer may have been handed to the node at any point: never "NO".
282
+ const unknown = (what) => unknownSend(resultId, sent, what, "UNKNOWN");
283
+ const roles = checked.transactions.map((t) => t.role);
284
+ try {
285
+ await sendInSequence(checked.transactions.map(({ role: _role, ...send }) => send), (i, hash) => { sent.push({ role: roles[i], chainId: checked.transactions[i].chainId, hash }); });
286
+ }
287
+ catch (e) {
288
+ if (e instanceof RectaCheckError && sent.length === 0)
289
+ throw e;
290
+ throw unknown(`sending ${sent.length === 0 ? "the first" : "the next"} transaction failed without a hash (${safeErrorText(e).slice(0, 200)})`);
291
+ }
292
+ const execution = sent.find((s) => s.role === "EXECUTION");
293
+ if (execution === undefined || sent.length !== checked.transactions.length)
294
+ throw unknown("the signer stopped before the transfer");
295
+ const ok = [];
296
+ try {
297
+ for (const s of sent)
298
+ ok.push(await chain.waitForSuccess(s.chainId, s.hash));
299
+ }
300
+ catch (e) {
301
+ throw unknown(`waiting for a receipt failed (${safeErrorText(e).slice(0, 200)})`);
302
+ }
303
+ if (!ok[sent.indexOf(execution)])
304
+ throw new RectaCheckError("transaction_failed", `EXECUTION transaction ${execution.hash} reverted: nothing was moved by it`);
305
+ // The deposit moved funds even if an approval reverted (an allowance already there): it is reported, the reverted
306
+ // approval is not (Recta then prices the approval at its committed upper bound: the saving can only be understated).
307
+ const approvalsOk = sent.every((s, i) => s.role !== "APPROVAL" || ok[i]);
308
+ const approvalTxHash = approvalsOk ? sent.filter((s) => s.role === "APPROVAL").at(-1)?.hash : undefined;
309
+ return { ...(approvalTxHash === undefined ? {} : { approvalTxHash }), originTxHash: execution.hash };
310
+ }
239
311
  /**
240
312
  * Step 4: reports the executed route; Recta verifies the delivery on chain and records the saving and its 5 %.
241
313
  * `stage`: ACCRUED (verified and recorded), PENDING (not yet verifiable: report again later) or REFUSED (Recta will
@@ -279,7 +351,7 @@ export function createRectaClient(options) {
279
351
  }
280
352
  /**
281
353
  * The four steps in a row. With `dryRun`, it evaluates and checks but signs no permit and sends no transaction: it
282
- * 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).
283
355
  */
284
356
  async function run(request, opts = {}) {
285
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.7";
10
+ export declare const CLIENT_VERSION = "0.1.9";
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.7";
12
+ export declare const USER_AGENT = "recta-client/0.1.9";
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.7";
10
+ export const CLIENT_VERSION = "0.1.9";
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/errors.d.ts CHANGED
@@ -1,9 +1,41 @@
1
- /** A local check refused to sign or send: nothing was signed or sent. `check` names the check. */
1
+ /**
2
+ * A local check refused, or a transaction did not end as expected. `check` names it. Read it before acting:
3
+ * - `transaction_unknown` (a RectaSendUnknownError): a transaction may have been sent. Look `sentTxHashes` (or, with
4
+ * none, the account's latest transactions) up on chain before sending anything again, by Recta or any other route.
5
+ * - `transaction_failed`: the named transaction was mined and reverted.
6
+ * - a wallet's own checks (`wallet_*`, from the MetaMask signer) say in their message what was sent.
7
+ * - every other check: nothing was signed or sent.
8
+ */
2
9
  export declare class RectaCheckError extends Error {
3
10
  readonly check: string;
4
11
  readonly name: string;
5
12
  constructor(check: string, message: string);
6
13
  }
14
+ /** A send whose outcome is not known (owner rule 2026-11-11: UNKNOWN, never FAILED): what was already sent, as data. */
15
+ export declare class RectaSendUnknownError extends RectaCheckError {
16
+ /** The evaluation this send belongs to, when it belongs to one. */
17
+ readonly resultId: string | undefined;
18
+ /** Every transaction hash already sent, in order; empty when none came back. */
19
+ readonly sentTxHashes: readonly {
20
+ readonly role: string;
21
+ readonly chainId: number;
22
+ readonly hash: `0x${string}`;
23
+ }[];
24
+ /** "NO" only when the transfer was certainly never asked for; "UNKNOWN" when it may have left (no hash for it). */
25
+ readonly transferSent: "NO" | "UNKNOWN";
26
+ readonly name: string;
27
+ constructor(message: string,
28
+ /** The evaluation this send belongs to, when it belongs to one. */
29
+ resultId: string | undefined,
30
+ /** Every transaction hash already sent, in order; empty when none came back. */
31
+ sentTxHashes: readonly {
32
+ readonly role: string;
33
+ readonly chainId: number;
34
+ readonly hash: `0x${string}`;
35
+ }[],
36
+ /** "NO" only when the transfer was certainly never asked for; "UNKNOWN" when it may have left (no hash for it). */
37
+ transferSent?: "NO" | "UNKNOWN");
38
+ }
7
39
  /** Recta answered with an error. `body` is Recta's JSON answer when it sent one. */
8
40
  export declare class RectaHttpError extends Error {
9
41
  readonly status: number;
package/dist/errors.js CHANGED
@@ -1,4 +1,11 @@
1
- /** A local check refused to sign or send: nothing was signed or sent. `check` names the check. */
1
+ /**
2
+ * A local check refused, or a transaction did not end as expected. `check` names it. Read it before acting:
3
+ * - `transaction_unknown` (a RectaSendUnknownError): a transaction may have been sent. Look `sentTxHashes` (or, with
4
+ * none, the account's latest transactions) up on chain before sending anything again, by Recta or any other route.
5
+ * - `transaction_failed`: the named transaction was mined and reverted.
6
+ * - a wallet's own checks (`wallet_*`, from the MetaMask signer) say in their message what was sent.
7
+ * - every other check: nothing was signed or sent.
8
+ */
2
9
  export class RectaCheckError extends Error {
3
10
  check;
4
11
  name = "RectaCheckError";
@@ -7,6 +14,25 @@ export class RectaCheckError extends Error {
7
14
  this.check = check;
8
15
  }
9
16
  }
17
+ /** A send whose outcome is not known (owner rule 2026-11-11: UNKNOWN, never FAILED): what was already sent, as data. */
18
+ export class RectaSendUnknownError extends RectaCheckError {
19
+ resultId;
20
+ sentTxHashes;
21
+ transferSent;
22
+ name = "RectaSendUnknownError";
23
+ constructor(message,
24
+ /** The evaluation this send belongs to, when it belongs to one. */
25
+ resultId,
26
+ /** Every transaction hash already sent, in order; empty when none came back. */
27
+ sentTxHashes,
28
+ /** "NO" only when the transfer was certainly never asked for; "UNKNOWN" when it may have left (no hash for it). */
29
+ transferSent = "UNKNOWN") {
30
+ super("transaction_unknown", message);
31
+ this.resultId = resultId;
32
+ this.sentTxHashes = sentTxHashes;
33
+ this.transferSent = transferSent;
34
+ }
35
+ }
10
36
  /** Recta answered with an error. `body` is Recta's JSON answer when it sent one. */
11
37
  export class RectaHttpError extends Error {
12
38
  status;
package/dist/index.d.ts CHANGED
@@ -5,5 +5,5 @@ export { checkExecutionArtifact, pinnedRouteOf, type CheckedArtifact, type Evalu
5
5
  export { PINNED_ROUTES, type PinnedRoute } from "./pinned-routes.js";
6
6
  export { parseWalletPolicy, type WalletPolicy, type WalletPolicyNetwork } from "./policy.js";
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
- export { RectaCheckError, RectaHttpError, RectaDebtError } from "./errors.js";
8
+ export { RectaCheckError, RectaHttpError, RectaDebtError, RectaSendUnknownError } from "./errors.js";
9
9
  export * as pins from "./constants.js";
package/dist/index.js CHANGED
@@ -5,5 +5,5 @@ export { checkExecutionArtifact, pinnedRouteOf } from "./artifact.js";
5
5
  export { PINNED_ROUTES } from "./pinned-routes.js";
6
6
  export { parseWalletPolicy } from "./policy.js";
7
7
  export { viemSigner, viemChainReader, cdpSigner, smartAccountSigner, DEFAULT_USER_OPERATION_OVERHEAD_GAS, CDP_SEND_NETWORKS } from "./signer.js";
8
- export { RectaCheckError, RectaHttpError, RectaDebtError } from "./errors.js";
8
+ export { RectaCheckError, RectaHttpError, RectaDebtError, RectaSendUnknownError } from "./errors.js";
9
9
  export * as pins from "./constants.js";
package/dist/signer.d.ts CHANGED
@@ -46,6 +46,12 @@ export interface RectaSigner {
46
46
  signTypedData(typedData: RectaTypedData): Promise<Hex>;
47
47
  /** Sends one transaction on `tx.chainId` and returns its hash. */
48
48
  sendTransaction(tx: RectaTransaction): Promise<Hex>;
49
+ /**
50
+ * Optional: sends transactions of one chain one after another without waiting for any receipt, on consecutive nonces
51
+ * read once, calling `onSent(i, hash)` the moment each leaves. Only a signer that does not itself wait for receipts
52
+ * and that picks its own nonces implements it (viemSigner with a local key); without it, execute() waits for each.
53
+ */
54
+ sendInSequence?(txs: readonly RectaTransaction[], onSent: (index: number, hash: Hex) => void): Promise<void>;
49
55
  }
50
56
  /** Read access to the chains (the agent's own RPC): receipts, and the payer's USDC on Base before a fee is signed. */
51
57
  export interface RectaChainReader {
package/dist/signer.js CHANGED
@@ -3,6 +3,7 @@ import { formatUserOperationRequest } from "viem/account-abstraction";
3
3
  import { toAccount } from "viem/accounts";
4
4
  import { FEE_CHAIN_ID, PERMIT2, USDC_BASE } from "./constants.js";
5
5
  import { ERC20_READ_ABI, safeErrorText } from "./funds.js";
6
+ import { RectaCheckError } from "./errors.js";
6
7
  /** A RectaSigner from a viem account and one wallet client per chain. */
7
8
  export function viemSigner(args) {
8
9
  const { account } = args;
@@ -21,9 +22,26 @@ export function viemSigner(args) {
21
22
  signMessage: (message) => account.signMessage({ message }),
22
23
  signTypedData: (td) => account.signTypedData(td),
23
24
  sendTransaction: (tx) => sendWith(args.walletClientFor(tx.chainId), account, tx),
25
+ // A local key: the nonce is read once from the node (pending) and the transactions take it and the ones after it,
26
+ // so they never share one. Nothing is remembered between calls.
27
+ sendInSequence: async (txs, onSent) => {
28
+ const chainId = txs[0]?.chainId;
29
+ if (chainId === undefined || txs.some((t) => t.chainId !== chainId))
30
+ throw new Error("sendInSequence sends transactions of one chain");
31
+ const client = args.walletClientFor(chainId);
32
+ let first;
33
+ try {
34
+ first = Number(BigInt((await client.request({ method: "eth_getTransactionCount", params: [account.address, "pending"] }))));
35
+ }
36
+ catch (e) {
37
+ throw new RectaCheckError("wallet_nonce", `could not read the nonce of ${account.address} on chain ${chainId} (${safeErrorText(e).slice(0, 200)}): nothing was sent`);
38
+ }
39
+ for (const [i, tx] of txs.entries())
40
+ onSent(i, await sendWith(client, account, tx, first + i));
41
+ },
24
42
  };
25
43
  }
26
- async function sendWith(client, account, tx) {
44
+ async function sendWith(client, account, tx, nonce) {
27
45
  const chainId = await client.getChainId();
28
46
  if (chainId !== tx.chainId)
29
47
  throw new Error(`walletClientFor(${tx.chainId}) returned a client on chain ${chainId}`);
@@ -37,6 +55,7 @@ async function sendWith(client, account, tx) {
37
55
  maxFeePerGas: tx.maxFeePerGas,
38
56
  maxPriorityFeePerGas: tx.maxPriorityFeePerGas,
39
57
  type: "eip1559",
58
+ ...(nonce === undefined ? {} : { nonce }),
40
59
  });
41
60
  }
42
61
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recta/client",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
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)",