@recta/client 0.1.4 → 0.1.6

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
@@ -50,7 +50,8 @@ const result = await recta.run(request);
50
50
  your signer's address. Each step is also available alone: `evaluate`, `authorizeFee`, `check`, `execute`, `report`,
51
51
  `ledger`, `payDebt`, `feeFunds`, `feeApproval`.
52
52
 
53
- Your account must be an EOA: Recta's signed requests are EIP-191 signatures recovered to the sender's address.
53
+ An EOA signs its requests as EIP-191 signatures recovered to the sender's address. A smart account on Base signs
54
+ through `smartAccountSigner` (see "Smart accounts").
54
55
 
55
56
  ## Referral for integrators
56
57
 
@@ -64,6 +65,49 @@ The referrer travels in the query of the agent's own signed requests, so nobody
64
65
  it. It is ignored when it is the agent's own address. Terms and your balance: `GET /v1/referrals/balance`, signed by
65
66
  your address, once Recta's referral program is on (it starts together with fee collection).
66
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
+
67
111
  ### Coinbase CDP accounts
68
112
 
69
113
  A [Coinbase CDP](https://docs.cdp.coinbase.com) EVM server account (an EOA whose key stays in CDP) works through
@@ -177,8 +221,12 @@ Every request this package sends carries the User-Agent `recta-client/<version>`
177
221
  ## Limits of this version
178
222
 
179
223
  - EVM sources and EVM recipients only. Solana, Tron and Bitcoin routes, Relay and deBridge are refused.
180
- - A corridor or contract Recta adds after this release is refused until a new release pins it.
181
- - Smart accounts (EIP-1271) cannot sign Recta's requests.
224
+ - Smart accounts on Base only, with transfers that start from Base (Recta's own rule: an address proves one account
225
+ on one chain). The route is sent through an ERC-4337 bundler; an account that is only driven by its owner's direct
226
+ calls (no bundler) is not supported by `smartAccountSigner`.
227
+ - Only the corridors and contracts pinned in the release, as a safety measure: the package refuses to sign against a
228
+ contract it does not know. A corridor or contract Recta adds later is served by the API at once, but refused by
229
+ this package until a new release pins it.
182
230
 
183
231
  ## Provenance
184
232
 
package/dist/client.d.ts CHANGED
@@ -34,6 +34,12 @@ export declare function signedRequestMessage(f: {
34
34
  readonly bodyKeccak256: string;
35
35
  readonly issuedAt: number;
36
36
  }): string;
37
+ /** The text a smart account signs for one request (v2: it also names the signer and the chain), exactly as Recta's server
38
+ * rebuilds it. The signer and chain stop a request signed for one account from passing for a sibling of the same owner. */
39
+ export declare function smartAccountSignedRequestMessage(f: Parameters<typeof signedRequestMessage>[0] & {
40
+ readonly signer: string;
41
+ readonly chainId: number;
42
+ }): string;
37
43
  /** The `?referrer=` suffix for a configured referrer: lower-cased, empty when none or when it is the payer itself. */
38
44
  export declare function referrerQuery(referrer: string | undefined, payer: string): string;
39
45
  export type FeeOutcome = {
@@ -52,7 +58,7 @@ export type FeeOutcome = {
52
58
  readonly fundsError?: string;
53
59
  };
54
60
  /**
55
- * Recta's flow for an agent that holds its own EOA: evaluate → authorizeFee → execute → report. Every step can be
61
+ * Recta's flow for an agent that holds its own EOA or smart account (on Base): evaluate → authorizeFee → execute → report. Every step can be
56
62
  * called alone. Nothing is signed or sent before this package's own checks pass (see `checkFeePermit` and
57
63
  * `checkExecutionArtifact`); they cannot be turned off.
58
64
  */
package/dist/client.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { keccak256 } from "viem";
2
2
  import { checkExecutionArtifact } from "./artifact.js";
3
- import { ISSUED_AT_HEADER, PATHS, RECTA_ORIGIN, SIGNATURE_HEADER, SIGNED_REQUEST_PREFIX, SIGNER_HEADER, USER_AGENT } from "./constants.js";
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
4
  import { RectaCheckError, RectaDebtError, RectaHttpError } from "./errors.js";
5
5
  import { checkFeePermit } from "./fee.js";
6
6
  import { assertFeeReady, feeReadiness, permit2ApprovalTransaction, routeReserveOf, safeErrorText } from "./funds.js";
@@ -16,6 +16,28 @@ export function signedRequestMessage(f) {
16
16
  `issued-at: ${f.issuedAt}`,
17
17
  ].join("\n");
18
18
  }
19
+ /** The text a smart account signs for one request (v2: it also names the signer and the chain), exactly as Recta's server
20
+ * rebuilds it. The signer and chain stop a request signed for one account from passing for a sibling of the same owner. */
21
+ export function smartAccountSignedRequestMessage(f) {
22
+ return [
23
+ SMART_ACCOUNT_SIGNED_REQUEST_PREFIX,
24
+ `signer: ${f.signer.toLowerCase()}`,
25
+ `chain-id: ${f.chainId}`,
26
+ `method: ${f.method.toUpperCase()}`,
27
+ `path: ${f.path}`,
28
+ `idempotency-key: ${f.idempotencyKey}`,
29
+ `body-keccak256: ${f.bodyKeccak256.toLowerCase()}`,
30
+ `issued-at: ${f.issuedAt}`,
31
+ ].join("\n");
32
+ }
33
+ /** ERC-6492's magic suffix: a signature from an account that is not deployed yet. */
34
+ const ERC6492_SUFFIX = "6492649264926492649264926492649264926492649264926492649264926492";
35
+ /** A permit signature Recta can collect: never an ERC-6492 wrapper, which Permit2 cannot use (Fable B-4 on recta #15). */
36
+ function permitSignature(signature) {
37
+ if (signature.toLowerCase().endsWith(ERC6492_SUFFIX))
38
+ throw new RectaCheckError("account_not_deployed", "the signer returned an ERC-6492 signature (an account not deployed yet): Permit2 cannot use it, so it was not sent");
39
+ return signature;
40
+ }
19
41
  const RESULT_ID = /^[A-Za-z0-9_-]+$/;
20
42
  const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
21
43
  /** The `?referrer=` suffix for a configured referrer: lower-cased, empty when none or when it is the payer itself. */
@@ -34,7 +56,7 @@ const resultIdOf = (v) => {
34
56
  return v;
35
57
  };
36
58
  /**
37
- * Recta's flow for an agent that holds its own EOA: evaluate → authorizeFee → execute → report. Every step can be
59
+ * Recta's flow for an agent that holds its own EOA or smart account (on Base): evaluate → authorizeFee → execute → report. Every step can be
38
60
  * called alone. Nothing is signed or sent before this package's own checks pass (see `checkFeePermit` and
39
61
  * `checkExecutionArtifact`); they cannot be turned off.
40
62
  */
@@ -45,6 +67,25 @@ export function createRectaClient(options) {
45
67
  const nowUnix = () => BigInt(Math.floor(now() / 1000));
46
68
  const payer = signer.address.toLowerCase();
47
69
  const referral = referrerQuery(options.referrer, payer);
70
+ const smart = signer.smartAccountChainId !== undefined;
71
+ if (smart && (signer.smartAccountChainId !== FEE_CHAIN_ID || typeof signer.isDeployed !== "function")) {
72
+ throw new RectaCheckError("smart_account", `a smart account signer must name Base (${FEE_CHAIN_ID}) and say whether it is deployed (smartAccountSigner does)`);
73
+ }
74
+ /** A fee or debt permit from a smart account: Permit2 asks the deployed account (ERC-1271) and cannot deploy it, so
75
+ * Recta refuses an ERC-6492 permit. Nothing is signed until the account's code is on Base. */
76
+ async function assertPermitSignable() {
77
+ if (!smart)
78
+ return;
79
+ let deployed;
80
+ try {
81
+ deployed = await signer.isDeployed();
82
+ }
83
+ catch (e) {
84
+ throw new RectaCheckError("account_not_deployed", `could not read whether the smart account is deployed on Base: ${safeErrorText(e)}`);
85
+ }
86
+ if (!deployed)
87
+ throw new RectaCheckError("account_not_deployed", "the smart account is not deployed on Base yet, and a fee permit needs it deployed: its first user operation deploys it (e.g. the bounded Permit2 approval, feeApproval)");
88
+ }
48
89
  if (typeof chain.readFeeFunds !== "function") {
49
90
  // Since 0.1.4 (ASTRA T2) a reader must read the fee funds on Base; an older custom reader fails here, clearly.
50
91
  throw new RectaCheckError("chain_reader", "the chain reader has no readFeeFunds(owner): since @recta/client 0.1.4 it must read the payer's USDC balance and Permit2 allowance on Base (viemChainReader does)");
@@ -63,7 +104,10 @@ export function createRectaClient(options) {
63
104
  headers["idempotency-key"] = idempotencyKey;
64
105
  if (signed) {
65
106
  const issuedAt = Math.floor(now() / 1000);
66
- const message = signedRequestMessage({ method, path, idempotencyKey: idempotencyKey ?? "", bodyKeccak256: keccak256(bytes), issuedAt });
107
+ const fields = { method, path, idempotencyKey: idempotencyKey ?? "", bodyKeccak256: keccak256(bytes), issuedAt };
108
+ const message = smart ? smartAccountSignedRequestMessage({ ...fields, signer: signer.address, chainId: FEE_CHAIN_ID }) : signedRequestMessage(fields);
109
+ if (smart)
110
+ headers[SIGNER_CHAIN_HEADER] = String(FEE_CHAIN_ID);
67
111
  headers[SIGNER_HEADER] = signer.address;
68
112
  headers[ISSUED_AT_HEADER] = String(issuedAt);
69
113
  headers[SIGNATURE_HEADER] = await signer.signMessage(message);
@@ -91,6 +135,9 @@ export function createRectaClient(options) {
91
135
  async function evaluate(request, opts = {}) {
92
136
  if (typeof request.sender !== "string" || request.sender.toLowerCase() !== payer)
93
137
  throw new RectaCheckError("sender", "the request's sender must be the signer");
138
+ // Recta accepts a smart account on Base only (its address proves one account on one chain).
139
+ if (smart && request.source_network !== "base")
140
+ throw new RectaCheckError("source_network", "a smart account's transfer must start from Base (source_network: base)");
94
141
  await walletPolicy();
95
142
  const a = await call("POST", `${PATHS.evaluations}${referral}`, request, opts.idempotencyKey ?? crypto.randomUUID());
96
143
  if (a.status === 402)
@@ -151,7 +198,8 @@ export function createRectaClient(options) {
151
198
  }
152
199
  // ASTRA T2: never sign a fee Recta could not collect (no USDC or no Permit2 allowance on Base).
153
200
  assertFeeReady(feeReadiness(await chain.readFeeFunds(signer.address), checked.amount, reserve));
154
- const signature = await signer.signTypedData(checked.typedData);
201
+ await assertPermitSignable();
202
+ const signature = permitSignature(await signer.signTypedData(checked.typedData));
155
203
  const s = await call("POST", `${PATHS.evaluations}/${id}/fee-authorization${referral}`, { signature, amount_usdc_atomic: checked.amount.toString() });
156
204
  if (s.status === 200 || s.status === 201)
157
205
  feeAmounts.set(id, checked.amount);
@@ -191,9 +239,13 @@ export function createRectaClient(options) {
191
239
  /**
192
240
  * Step 4: reports the executed route; Recta verifies the delivery on chain and records the saving and its 5 %.
193
241
  * `stage`: ACCRUED (verified and recorded), PENDING (not yet verifiable: report again later) or REFUSED (Recta will
194
- * not accrue this execution; see `body.reason_code`).
242
+ * not accrue this execution; see `body.reason_code`). A smart account's approval is never reported: it is the
243
+ * account's user operation, not the committed transaction field by field, so Recta prices it at its committed upper
244
+ * bound (the saving can only be understated, never overstated).
195
245
  */
196
246
  async function report(resultId, originTxHash, approvalTxHash) {
247
+ if (smart)
248
+ approvalTxHash = undefined;
197
249
  const a = await call("POST", `${PATHS.evaluations}/${resultIdOf(resultId)}/execution`, { origin_tx_hash: originTxHash, ...(approvalTxHash === undefined ? {} : { approval_tx_hash: approvalTxHash }) });
198
250
  const body = a.body;
199
251
  if (a.status === 200 || a.status === 201)
@@ -218,7 +270,8 @@ export function createRectaClient(options) {
218
270
  if (typeof debtId !== "string")
219
271
  throw new RectaCheckError("debt", "the offer has no debt_id");
220
272
  assertFeeReady(feeReadiness(await chain.readFeeFunds(signer.address), checked.amount));
221
- const signature = await signer.signTypedData(checked.typedData);
273
+ await assertPermitSignable();
274
+ const signature = permitSignature(await signer.signTypedData(checked.typedData));
222
275
  const a = await call("POST", PATHS.feeDebts, { debt_id: debtId, deadline_unix: checked.deadline.toString(), signature });
223
276
  if (a.status !== 200 && a.status !== 201)
224
277
  throw new RectaHttpError(a.status, a.body);
@@ -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.4";
10
+ export declare const CLIENT_VERSION = "0.1.6";
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.4";
12
+ export declare const USER_AGENT = "recta-client/0.1.6";
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";
@@ -56,8 +56,11 @@ export declare const FEE_PERMIT_TYPES: {
56
56
  readonly type: "uint256";
57
57
  }];
58
58
  };
59
- /** Signed requests (EIP-191 `personal_sign` by the sender's EOA). */
59
+ /** Signed requests from this package: an EOA signs v1 (EIP-191 `personal_sign`); a smart account signs v2, which also
60
+ * names the signer and the chain, with the signer-chain header (checked by the account on Base: ERC-1271 / ERC-6492). */
60
61
  export declare const SIGNED_REQUEST_PREFIX = "Recta signed request v1";
62
+ export declare const SMART_ACCOUNT_SIGNED_REQUEST_PREFIX = "Recta signed request v2";
63
+ export declare const SIGNER_CHAIN_HEADER = "x-recta-signer-chain";
61
64
  export declare const SIGNER_HEADER = "x-recta-signer";
62
65
  export declare const ISSUED_AT_HEADER = "x-recta-issued-at";
63
66
  export declare const SIGNATURE_HEADER = "x-recta-signature";
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.4";
10
+ export const CLIENT_VERSION = "0.1.6";
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. */
@@ -39,8 +39,11 @@ export const FEE_PERMIT_TYPES = {
39
39
  { name: "validAfter", type: "uint256" },
40
40
  ],
41
41
  };
42
- /** Signed requests (EIP-191 `personal_sign` by the sender's EOA). */
42
+ /** Signed requests from this package: an EOA signs v1 (EIP-191 `personal_sign`); a smart account signs v2, which also
43
+ * names the signer and the chain, with the signer-chain header (checked by the account on Base: ERC-1271 / ERC-6492). */
43
44
  export const SIGNED_REQUEST_PREFIX = "Recta signed request v1";
45
+ export const SMART_ACCOUNT_SIGNED_REQUEST_PREFIX = "Recta signed request v2";
46
+ export const SIGNER_CHAIN_HEADER = "x-recta-signer-chain";
44
47
  export const SIGNER_HEADER = "x-recta-signer";
45
48
  export const ISSUED_AT_HEADER = "x-recta-issued-at";
46
49
  export const SIGNATURE_HEADER = "x-recta-signature";
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- export { createRectaClient, signedRequestMessage, referrerQuery, type RectaClient, type RectaClientOptions, type FeeOutcome } from "./client.js";
1
+ export { createRectaClient, signedRequestMessage, smartAccountSignedRequestMessage, referrerQuery, type RectaClient, type RectaClientOptions, type FeeOutcome } from "./client.js";
2
2
  export { checkFeePermit, type FeePermitLimits } from "./fee.js";
3
3
  export { feeReadiness, assertFeeReady, permit2ApprovalTransaction, routeReserveOf, safeErrorText, ERC20_READ_ABI, type FeeFunds, type FeeReadiness, type Permit2Approval } from "./funds.js";
4
4
  export { checkExecutionArtifact, pinnedRouteOf, type CheckedArtifact, type EvaluationRequestView, type ArtifactLimits } from "./artifact.js";
5
5
  export { PINNED_ROUTES, type PinnedRoute } from "./pinned-routes.js";
6
6
  export { parseWalletPolicy, type WalletPolicy, type WalletPolicyNetwork } from "./policy.js";
7
- export { viemSigner, viemChainReader, cdpSigner, CDP_SEND_NETWORKS, type CdpEvmAccountLike, type CdpSendNetwork, type RectaSigner, type RectaChainReader, type RectaTransaction, type RectaTypedData } from "./signer.js";
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 } from "./errors.js";
9
9
  export * as pins from "./constants.js";
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- export { createRectaClient, signedRequestMessage, referrerQuery } from "./client.js";
1
+ export { createRectaClient, signedRequestMessage, smartAccountSignedRequestMessage, referrerQuery } from "./client.js";
2
2
  export { checkFeePermit } from "./fee.js";
3
3
  export { feeReadiness, assertFeeReady, permit2ApprovalTransaction, routeReserveOf, safeErrorText, ERC20_READ_ABI } from "./funds.js";
4
4
  export { checkExecutionArtifact, pinnedRouteOf } from "./artifact.js";
5
5
  export { PINNED_ROUTES } from "./pinned-routes.js";
6
6
  export { parseWalletPolicy } from "./policy.js";
7
- export { viemSigner, viemChainReader, cdpSigner, CDP_SEND_NETWORKS } from "./signer.js";
7
+ export { viemSigner, viemChainReader, cdpSigner, smartAccountSigner, DEFAULT_USER_OPERATION_OVERHEAD_GAS, CDP_SEND_NETWORKS } from "./signer.js";
8
8
  export { RectaCheckError, RectaHttpError, RectaDebtError } from "./errors.js";
9
9
  export * as pins from "./constants.js";
package/dist/signer.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import type { Account, Chain, Hex, PublicClient, Transport, TransactionSerializable, WalletClient } from "viem";
2
+ import { type BundlerClient, type SmartAccount } from "viem/account-abstraction";
3
+ import { FEE_CHAIN_ID } from "./constants.js";
2
4
  import { type FeeFunds } from "./funds.js";
3
5
  /** One EIP-1559 transaction of an execution artifact, as this package asks a signer to send it. */
4
6
  export interface RectaTransaction {
@@ -25,11 +27,21 @@ export interface RectaTypedData {
25
27
  readonly message: Record<string, unknown>;
26
28
  }
27
29
  /**
28
- * What this package needs from a wallet, and nothing more. It never receives or stores a key. The account must be an
29
- * EOA: Recta's signed requests are EIP-191 signatures recovered to the sender's address (smart accounts cannot).
30
+ * What this package needs from a wallet, and nothing more. It never receives or stores a key. An EOA signs Recta's v1
31
+ * request text (EIP-191, recovered to the sender's address). A smart account (`smartAccountSigner`) signs the v2 text,
32
+ * which also names the account and Base, and Recta asks the account itself on Base whether the signature holds
33
+ * (ERC-1271, or ERC-6492 before it is deployed).
30
34
  */
31
35
  export interface RectaSigner {
32
36
  readonly address: Hex;
37
+ /**
38
+ * Present only for a smart account: the chain on which Recta checks its signatures. Recta accepts a smart account on
39
+ * Base only (8453), where its fee is collected, so its transfers must start from Base.
40
+ */
41
+ readonly smartAccountChainId?: typeof FEE_CHAIN_ID;
42
+ /** Smart account only: whether its code is on Base. A fee or debt permit is signed only once it is (Permit2 cannot
43
+ * deploy an account, so Recta refuses an ERC-6492 permit). */
44
+ isDeployed?(): Promise<boolean>;
33
45
  signMessage(message: string): Promise<Hex>;
34
46
  signTypedData(typedData: RectaTypedData): Promise<Hex>;
35
47
  /** Sends one transaction on `tx.chainId` and returns its hash. */
@@ -107,5 +119,27 @@ export declare function cdpSigner(args: {
107
119
  readonly account: CdpEvmAccountLike;
108
120
  readonly walletClientFor?: (chainId: number) => WalletClient<Transport, Chain | undefined, Account | undefined>;
109
121
  }): RectaSigner;
122
+ /** The most gas a user operation may spend besides its call (verification, pre-verification and any paymaster's own
123
+ * verification and post-op), unless the operator sets `maxOverheadGas`. Covers deploying a Coinbase Smart Wallet. */
124
+ export declare const DEFAULT_USER_OPERATION_OVERHEAD_GAS = 1500000n;
125
+ /**
126
+ * A RectaSigner from a viem smart account on Base (e.g. `toCoinbaseSmartAccount` from `viem/account-abstraction`) and
127
+ * an ERC-4337 bundler client on Base (give the bundler client a paymaster to sponsor gas, if you have one).
128
+ *
129
+ * Requests and fee permits are signed by the account (viem wraps them in ERC-6492 while it is not deployed; Recta then
130
+ * accepts requests, and this package refuses to sign a fee permit until the account is deployed). Each route
131
+ * transaction, after this package's checks like any other, becomes one user operation, prepared by the bundler client
132
+ * (and its paymaster) and then checked again before the account signs it (Fable A-1/M-1 on recta #15): the sender is the
133
+ * account, the call data is exactly the committed call (`to`, `data`, `value`), the call gas is the committed gas limit,
134
+ * the fees are the committed caps, there is no init code once the account is deployed (and only the account's own
135
+ * factory call before), and verification plus pre-verification plus paymaster gas stays within `maxOverheadGas`. A
136
+ * bundler or paymaster that changes any of it gets nothing signed. The checked operation is signed and sent as is.
137
+ * The returned hash is the bundle's transaction once the operation itself succeeded; a failed operation throws.
138
+ */
139
+ export declare function smartAccountSigner(args: {
140
+ readonly account: SmartAccount;
141
+ readonly bundlerClient: Pick<BundlerClient, "prepareUserOperation" | "request" | "waitForUserOperationReceipt">;
142
+ readonly maxOverheadGas?: bigint;
143
+ }): RectaSigner;
110
144
  /** A RectaChainReader from one viem public client per chain (`publicClientFor(8453)` reads the fee funds on Base). */
111
145
  export declare function viemChainReader(publicClientFor: (chainId: number) => PublicClient): RectaChainReader;
package/dist/signer.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { concat } from "viem";
2
+ import { formatUserOperationRequest } from "viem/account-abstraction";
1
3
  import { toAccount } from "viem/accounts";
2
4
  import { FEE_CHAIN_ID, PERMIT2, USDC_BASE } from "./constants.js";
3
5
  import { ERC20_READ_ABI, safeErrorText } from "./funds.js";
@@ -87,6 +89,111 @@ export function cdpSigner(args) {
87
89
  },
88
90
  };
89
91
  }
92
+ /** The most gas a user operation may spend besides its call (verification, pre-verification and any paymaster's own
93
+ * verification and post-op), unless the operator sets `maxOverheadGas`. Covers deploying a Coinbase Smart Wallet. */
94
+ export const DEFAULT_USER_OPERATION_OVERHEAD_GAS = 1500000n;
95
+ /** How long to wait for a user operation's receipt before giving up (it may still be included later). */
96
+ const USER_OPERATION_RECEIPT_TIMEOUT_MS = 600_000;
97
+ /**
98
+ * A RectaSigner from a viem smart account on Base (e.g. `toCoinbaseSmartAccount` from `viem/account-abstraction`) and
99
+ * an ERC-4337 bundler client on Base (give the bundler client a paymaster to sponsor gas, if you have one).
100
+ *
101
+ * Requests and fee permits are signed by the account (viem wraps them in ERC-6492 while it is not deployed; Recta then
102
+ * accepts requests, and this package refuses to sign a fee permit until the account is deployed). Each route
103
+ * transaction, after this package's checks like any other, becomes one user operation, prepared by the bundler client
104
+ * (and its paymaster) and then checked again before the account signs it (Fable A-1/M-1 on recta #15): the sender is the
105
+ * account, the call data is exactly the committed call (`to`, `data`, `value`), the call gas is the committed gas limit,
106
+ * the fees are the committed caps, there is no init code once the account is deployed (and only the account's own
107
+ * factory call before), and verification plus pre-verification plus paymaster gas stays within `maxOverheadGas`. A
108
+ * bundler or paymaster that changes any of it gets nothing signed. The checked operation is signed and sent as is.
109
+ * The returned hash is the bundle's transaction once the operation itself succeeded; a failed operation throws.
110
+ */
111
+ export function smartAccountSigner(args) {
112
+ const { account, bundlerClient } = args;
113
+ const maxOverheadGas = args.maxOverheadGas ?? DEFAULT_USER_OPERATION_OVERHEAD_GAS;
114
+ const chainId = account.client.chain?.id;
115
+ if (chainId !== FEE_CHAIN_ID)
116
+ throw new Error(`the smart account's client is on chain ${String(chainId)}: Recta accepts smart accounts on Base (${FEE_CHAIN_ID}) only`);
117
+ return {
118
+ address: account.address,
119
+ smartAccountChainId: FEE_CHAIN_ID,
120
+ isDeployed: () => account.isDeployed(),
121
+ signMessage: (message) => account.signMessage({ message }),
122
+ signTypedData: (td) => account.signTypedData(td),
123
+ sendTransaction: async (tx) => {
124
+ if (tx.chainId !== FEE_CHAIN_ID)
125
+ throw new Error(`a smart account sends on Base (${FEE_CHAIN_ID}) only, not on chain ${tx.chainId}`);
126
+ const call = { to: tx.to, data: tx.data, value: tx.value };
127
+ // Fable B-5 on recta #15: the nonce is read here and must come back unchanged.
128
+ const nonce = await account.getNonce();
129
+ const op = (await bundlerClient.prepareUserOperation({
130
+ account,
131
+ calls: [call],
132
+ nonce,
133
+ callGasLimit: tx.gas,
134
+ maxFeePerGas: tx.maxFeePerGas,
135
+ maxPriorityFeePerGas: tx.maxPriorityFeePerGas,
136
+ }));
137
+ await checkPreparedOperation(op, account, call, tx, nonce, maxOverheadGas);
138
+ const signature = await account.signUserOperation(op);
139
+ const hash = (await bundlerClient.request({
140
+ method: "eth_sendUserOperation",
141
+ params: [formatUserOperationRequest({ ...op, signature }), account.entryPoint.address],
142
+ }, { retryCount: 0 }));
143
+ let receipt;
144
+ try {
145
+ receipt = await bundlerClient.waitForUserOperationReceipt({ hash, timeout: USER_OPERATION_RECEIPT_TIMEOUT_MS });
146
+ }
147
+ catch (e) {
148
+ // Fable B-2: the operation may still be included; sending again could move the funds twice.
149
+ throw new Error(`user operation ${hash} was sent but its receipt is not available yet: do not send again, look the operation up first (${safeErrorText(e)})`);
150
+ }
151
+ if (!receipt.success)
152
+ throw new Error(`user operation ${hash} failed${receipt.reason === undefined ? "" : `: ${receipt.reason}`}`);
153
+ return receipt.receipt.transactionHash;
154
+ },
155
+ };
156
+ }
157
+ /** The gas fields counted against `maxOverheadGas`: each must be a bigint when present (Fable M-3 on recta #15: a paymaster
158
+ * answer is spread onto the operation untyped, and a hex string or JSON number would otherwise count as 0 here and still
159
+ * be signed at its real value). The first two must be present. */
160
+ const OVERHEAD_GAS_FIELDS = ["verificationGasLimit", "preVerificationGas", "paymasterVerificationGasLimit", "paymasterPostOpGasLimit"];
161
+ const sameHex = (a, b) => typeof a === "string" && typeof b === "string" && a.toLowerCase() === b.toLowerCase();
162
+ /** The prepared user operation is the committed call and nothing else, within the gas and fee bounds; or it throws. */
163
+ async function checkPreparedOperation(op, account, call, tx, nonce, maxOverheadGas) {
164
+ const refuse = (what) => { throw new Error(`the bundler or paymaster changed the user operation's ${what}: nothing was signed`); };
165
+ if (!sameHex(op["sender"], account.address))
166
+ refuse("sender");
167
+ if (!sameHex(op["callData"], await account.encodeCalls([call])))
168
+ refuse("call data");
169
+ if (op["callGasLimit"] !== tx.gas)
170
+ refuse("call gas limit");
171
+ if (op["maxFeePerGas"] !== tx.maxFeePerGas || op["maxPriorityFeePerGas"] !== tx.maxPriorityFeePerGas)
172
+ refuse("fee caps");
173
+ if (op["nonce"] !== nonce)
174
+ refuse("nonce");
175
+ if (op["authorization"] !== undefined)
176
+ refuse("authorization");
177
+ const factory = await account.getFactoryArgs();
178
+ if (account.entryPoint.version === "0.6") {
179
+ const expected = factory.factory !== undefined && factory.factoryData !== undefined ? concat([factory.factory, factory.factoryData]) : "0x";
180
+ if (!sameHex(op["initCode"] ?? "0x", expected))
181
+ refuse("init code");
182
+ }
183
+ else if (!(sameHex(op["factory"] ?? "0x", factory.factory ?? "0x") && sameHex(op["factoryData"] ?? "0x", factory.factoryData ?? "0x")))
184
+ refuse("factory");
185
+ let overhead = 0n;
186
+ for (const [i, name] of OVERHEAD_GAS_FIELDS.entries()) {
187
+ const v = op[name];
188
+ if (v === undefined && i >= 2)
189
+ continue;
190
+ if (typeof v !== "bigint" || v < 0n)
191
+ refuse(name);
192
+ overhead += v;
193
+ }
194
+ if (overhead > maxOverheadGas)
195
+ throw new Error(`the user operation's verification and pre-verification gas (${overhead}) exceeds the limit ${maxOverheadGas}: nothing was signed`);
196
+ }
90
197
  /** A RectaChainReader from one viem public client per chain (`publicClientFor(8453)` reads the fee funds on Base). */
91
198
  export function viemChainReader(publicClientFor) {
92
199
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recta/client",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
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)",