From d668ca7a24f8d63770ed27967c95b2cb80e57fef Mon Sep 17 00:00:00 2001 From: nikhil kumar Date: Fri, 18 Sep 2026 21:02:08 +0530 Subject: [PATCH 1/8] feat!: support scalar-nonce frame transactions and EOA accounts Align the type 0x06 envelope, RPC parsing, and gas accounting with the current EIP-8141 format. Add FrameAccount, EOA preparation and signing helpers, an ETH transfer example, tests, and updated documentation. BREAKING CHANGE: FrameTransaction now uses a scalar nonce. The EIP-8250 nonceKeys/nonceSeq and EIP-8272 recentRootReferences fields and related APIs have been removed. --- CONTRIBUTING.md | 23 +-- README.md | 51 +---- docs/DESIGN.md | 273 ++++++++------------------- docs/OPEN-ITEMS.md | 2 +- package.json | 6 +- scripts/capture-fixtures.ts | 5 +- scripts/send-eth-eoa.ts | 145 ++++++++++++++ src/accounts/toEoaFrameAccount.ts | 119 ++++++++++++ src/accounts/toFrameAccount.ts | 31 +++ src/accounts/types.ts | 92 +++++++++ src/divergence.ts | 78 +------- src/envelope.ts | 92 ++------- src/gas.ts | 92 ++------- src/index.ts | 38 ++-- src/prepareFrameTransaction.ts | 126 +++++++++++++ src/rpc.ts | 13 +- src/signFrameTransaction.ts | 19 ++ src/signatures.ts | 6 +- src/types.ts | 24 +-- test/accounts.test.ts | 112 +++++++++++ test/divergence.test.ts | 159 +--------------- test/envelope.decode.test.ts | 30 +-- test/envelope.encode.test.ts | 21 +-- test/envelope.validate.test.ts | 129 ++----------- test/fixtures/golden.ts | 20 +- test/gas.test.ts | 52 ++--- test/live/simulate.test.ts | 88 +-------- test/oracles.test.ts | 153 ++------------- test/prepareFrameTransaction.test.ts | 127 +++++++++++++ test/signFrameTransaction.test.ts | 49 +++++ test/viem.test.ts | 4 +- 31 files changed, 1084 insertions(+), 1095 deletions(-) create mode 100644 scripts/send-eth-eoa.ts create mode 100644 src/accounts/toEoaFrameAccount.ts create mode 100644 src/accounts/toFrameAccount.ts create mode 100644 src/accounts/types.ts create mode 100644 src/prepareFrameTransaction.ts create mode 100644 src/signFrameTransaction.ts create mode 100644 test/accounts.test.ts create mode 100644 test/prepareFrameTransaction.test.ts create mode 100644 test/signFrameTransaction.test.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 88bf295..fd0f3a0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -11,8 +11,8 @@ frame transactions as the hegota-testnet chain (chain ID `8141`) accepts them. T envelope is a composition of three draft EIPs that none of them specifies on its own: EIP-8141 frames, EIP-8250 keyed nonces, EIP-8272 recent-root references. -It is a deliberate second implementation. The reference client is -[ethrex, on its `hegota-testnet` branch](https://github.com/lambdaclass/ethrex/tree/hegota-testnet), +It is a deliberate second implementation. The migration is pinned against +[ethrex commit `d587cf9`](https://github.com/lambdaclass/ethrex/tree/d587cf9ff0996315381c4b2784a4d7d499decc0f), and this library exists partly to disagree with it usefully. Every `.rs`, `.py` and `docs/*.md` path cited in this repository's docs and comments — `transaction.rs`, `frame_tx_wire_tests.rs`, `frametx.py` and the rest — is a path in that repository, not in @@ -46,15 +46,14 @@ interchangeable. ```bash bun run test # hermetic, no network -bun run test:live # opt-in, hits rpc1.privacy.ethrex.xyz +bun run test:live # checks rpc1.frames.ethrex.xyz identity bun run typecheck bun run build # tsup -> dist/, dual ESM + CJS with both declaration flavours -bunx tsx scripts/capture-fixtures.ts [from-block] [to-block] ``` CI runs `typecheck`, `test`, `build`, and then `@arethetypeswrong/cli --pack .` against -the built package. All four must pass. The live suite is not expected to pass in every -environment and is not a gate. +the built package. All four must pass. The public frames RPC currently has no +frame-aware simulation method, so there is no live simulation gate. That last check is there because a broken `exports` map or a mismatched `.d.cts` breaks every consumer while leaving the test suite entirely green — the tests import from `src/`, @@ -81,7 +80,7 @@ authority; if the encoder disagrees with them, the encoder is wrong. Fixtures un **`src/gas.ts` must not import `src/envelope.ts`.** The gas model stays independently testable, so it can be independently wrong or independently right. The small duplication -this causes (a `sameAddress` helper, the framing for two calldata blobs) is deliberate. +this causes (for example, a `sameAddress` helper) is deliberate. `src/envelope.ts` must not import `src/signatures.ts`; the reverse direction is fine. **`encodeFrameTx` deliberately does not validate.** `frameTxSigHash` is defined over a @@ -99,8 +98,6 @@ path is `assertValidFrameTx(tx)` then `encodeFrameTx(tx)`. signature makes the transaction invalid at consensus, not merely unrelayable. - **RLP scalars are minimal big-endian**; zero is the empty string `0x`, not `0x00`. Never pass viem's `numberToHex` into `toRlp`; use `rlpUint`. -- **`recentRootCalldata` is empty (`0x`) when no reference is declared**, not `toRlp([])` - (`0xc0`). Getting this wrong adds billed bytes to every transaction on the chain. - **State gas is added on top of the calldata floor**, never absorbed by it. - **`limits` is always a two-element list**, including when `state` is zero. - **The frame's JSON field for the target is `to`, not `target`.** The node's `type` is @@ -170,7 +167,7 @@ That means **your commit messages set the version**. Use Pull request titles are validated by CI against that list, with an optional scope from `envelope`, `sighash`, `signatures`, `gas`, `divergence`, `rlp`, `rpc`, `viem`, `fixtures`, `docs`, `deps`, `ci`, `repo` — for example -`feat(gas): model the head EIP-8272 reference arm`. Subjects start lowercase. +`fix(envelope): encode the scalar frame nonce`. Subjects start lowercase. Do not hand-edit `version` in `package.json` or touch `CHANGELOG.md`; the release commit owns both. A wire-format or gas change is almost always at least a `fix:`, because @@ -184,10 +181,8 @@ someone downstream is encoding bytes with this. published figure, a golden vector, or captured chain data, not to the code's own output. - If you touched anything in **Rules that are not style preferences**, say why in the PR description. Those changes are not refused, but they are argued. -- Fixtures expire. They record the client version and genesis hash they were captured - against and the oracle suite asserts the genesis hash, so a re-genesis fails loudly. - This chain is already on its third genesis; re-capture with the script rather than - hand-editing. +- Files under `test/fixtures/chain` are archived captures from the superseded envelope. + Do not use them as current wire-format oracles. ## Where the rest of the docs are diff --git a/README.md b/README.md index 33d01c9..8648e43 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,8 @@ [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE) [![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/JustaLab-co/frametx-kit/badge)](https://scorecard.dev/viewer/?uri=github.com/JustaLab-co/frametx-kit) -TypeScript for **EIP-8141 frame transactions** as hegota-testnet (chain ID `8141`) -actually accepts them: the composed envelope that also carries EIP-8250 keyed nonces -and EIP-8272 recent-root references. +TypeScript for the current **EIP-8141 frame transaction** envelope implemented by +the Ethrex frames devnet (chain ID `81410`). Decode, build, hash, sign, price, dry-run and broadcast. @@ -27,7 +26,7 @@ import { createPublicClient, http } from 'viem' import { frameActions } from '@jaw.id/frametx-kit/viem' const client = createPublicClient({ - transport: http('https://rpc1.privacy.ethrex.xyz'), + transport: http('https://rpc1.frames.ethrex.xyz'), }).extend(frameActions) const tx = await client.getFrameTransaction({ hash }) @@ -46,7 +45,7 @@ assertValidFrameTx(signed) const raw = encodeFrameTx(signed) ``` -`signFrameTx` also takes an account instead of a key — anything with an `address` and a +`signFrameTx` also takes a `FrameSigner` instead of a key — anything with an `address` and a raw-digest `sign`, which covers viem's `privateKeyToAccount` and `mnemonicToAccount`, a `toAccount` source, and your own wrapper around a hardware wallet, an HSM or a remote signer. It signs every SECP256K1 entry whose `msg` is empty, and refuses if the entry's @@ -98,45 +97,17 @@ the node's decoded JSON, re-encodes it, and refuses to return anything whose re- does not reproduce the transaction hash. What you get back is a transaction this library can put back on the wire byte-for-byte. -## Gas and rule sets +## Gas -Gas is priced under one of three rule sets, because the deployed binary and the pinned -EIP text disagree: - -| Rule set | Meaning | -|---|---| -| `'chain'` | ethrex `31b532266`, what the nodes actually run | -| `'pins'` | the pinned EIP text | -| `'head'` | current drafts, for anticipating the next re-genesis | +`frameTxGas` prices the current EIP-8141 transaction shape. The historical +`'chain'`, `'pins'`, and `'head'` rule-set names remain accepted as compatibility +aliases and currently produce identical results. ```ts import { compareRuleSets, decodeFrameTx } from '@jaw.id/frametx-kit' console.log(compareRuleSets(decodeFrameTx(raw), 'chain', 'pins')) ``` -The head EIP-8272 draft alters the *envelope*, not just the price: the recent-root field -is gone and references travel as a leading VERIFY frame against -`0x0000000000000000000000000000000000008272`, 72 bytes each. `compareRuleSets` prices -whichever side names `'head'` over `toHeadShape(tx)`, which applies exactly that change -as a transformation of the transaction, so a reference-carrying transaction is surveyed -rather than refused. - -```ts -import { toHeadShape } from '@jaw.id/frametx-kit' -compareRuleSets(tx, 'pins', 'head') // prices the head side over toHeadShape(tx) -toHeadShape(tx) // the same transform on its own; identity when no reference is carried -``` - -The synthetic frame claims zero execution and state. Zero state is normative: the draft -pins `limits.state` for the recent root verifier frame, along with its mode, target, flags -and value. `limits.execution` is the one figure it leaves open — that falls out of the -`STATICCALL` and one `SLOAD` per tuple — so every limit-derived term of the head price is -still a floor, fine to compare against and wrong to budget with. That is why -`frameTxGas(tx, 'head')` still throws for a reference-carrying transaction rather than -hand you a floor that reads like a budget. `'head'` otherwise prices identically to -`'pins'`; the EIP-8250 change it models is an execution-time charge against -`limits.state`, published as `HEAD_KEYED_NONCE_STATE_GAS`. - Every gas constant is written as its published figure rather than derived. ethrex's own suite missed its intrinsic dropping from 15000 to 12000 across 1372 tests by deriving the expected value from the constant under test. @@ -145,13 +116,11 @@ expected value from the constant under test. ```bash bun run test # hermetic, no network -bun run test:live # hits rpc1.privacy.ethrex.xyz bun run typecheck ``` -The default suite runs entirely off checked-in fixtures. Those are real transactions -captured with `bunx tsx scripts/capture-fixtures.ts`; each records the client version and -genesis hash it was taken against, so a re-genesis fails loudly rather than silently. +The default suite is hermetic. Its golden RLP and signature hash are pinned to the +current Ethrex `FrameTransaction` encoder. ## Contributing diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 78f98d8..a9f595d 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1,31 +1,22 @@ -# frametx-kit — design +# frametx-kit design -**Date:** 2026-09-06 -**Status:** implemented; binding on the code in this repository. Reviewed against ethrex `hegota-testnet` @ `19c065fa8` and the live node on 2026-09-06; §5, §6 and §9 amended for the RPC surface actually served (no raw transaction bytes). §5, §7 and §8 amended 2026-09-07 to match the module graph, strict-decode surface and entry-point name as built. §7 amended 2026-09-08: the byte-offset promise is delivered by a hand-rolled `walkRlp`, not deferred. §4 amended 2026-09-08: the `'head'` EIP-8272 frame shape and `72`-byte tuple order confirmed against upstream `eip-8272.md` @ `824cbc0b0`. -**Target network:** hegota-testnet, chain ID `8141`, genesis `0x7ca0f735…cd0f2332` -**Reference client:** [`lambdaclass/ethrex`, branch `hegota-testnet`](https://github.com/lambdaclass/ethrex/tree/hegota-testnet). Every `.rs`, `.py` and `docs/*.md` path cited below is a path in that repository, not in this one. +**Status:** implemented against the EIP-8141 frame transaction layout used by +Ethrex `v23.0.0-HEAD-d587cf9ff0996315381c4b2784a4d7d499decc0f`. -A TypeScript library for reading, building, hashing, pricing and simulating EIP-8141 frame -transactions as they exist on hegota-testnet — the composed envelope that also carries -EIP-8250 keyed nonces and EIP-8272 recent-root references. +## Scope -## 1. Why this exists +The package provides pure TypeScript tools to encode, decode, hash, sign, validate, +price, and format EIP-8141 frame transactions. It also provides a small account +abstraction for constructing account-specific validation and signatures. -**No JavaScript can touch this chain.** The only frame-transaction encoders are ethrex's Rust -implementation and ethrex's own `scripts/hegota-testnet/frametx.py` (126 lines). viem PR 4486 is a draft, -last touched 2026-05-06, with zero human review; it implements a pre-composition EIP-8141 -envelope with a flat `nonce`, flat fees, no `limits`, no recent-root references, and — across -its whole 3372-line diff — no `signatures` field and no `sig_hash`. It cannot authenticate a -frame transaction, and its bytes are not the bytes this chain accepts. +Transaction submission remains a normal `eth_sendRawTransaction` call. The optional +Ethrex simulation wrapper is retained, but not every frames-devnet RPC exposes that +method. -**A second implementation with hardcoded published figures catches a class of drift that -derived-constant tests cannot.** From `crates/common/types/transaction.rs:2215-2220`: +## Canonical envelope -> EIP-8141 publishes these in its Constants table; assert the constants reproduce them exactly, -> so a repricing or a re-spelling upstream is a compile error here rather than a silent -> consensus change. […] the reason the intrinsic drop from 15000 to 12000 was invisible to 1372 -> tests: the suite derives its expected intrinsic from this constant, so it can check the -> formula's composition but never the published figure. +A transaction is encoded as `0x06 || rlp(payload)`, where `payload` has exactly seven +fields: The same blindness applies to the wire format. From `test/tests/common/frame_tx_wire_tests.rs:3-8`: @@ -95,176 +86,85 @@ limits = rlp([execution, state]) signature = rlp([scheme, signer, msg, signature_bytes]) ``` -The composition of the three EIPs is this chain's own choice — none of the three specifies it. -EIP-8250 replaces the scalar `nonce` with `nonce_keys, nonce_seq` in place, EIP-8272 appends -`recent_root_references` last, and EIP-8141's `fees` list sits where its three flat fee fields -used to be. +`nonce` is a scalar u64 account nonce. The older experimental `nonce_keys`, +`nonce_seq`, and `recent_root_references` fields are intentionally unsupported. -> **`docs/eip-8141.md:78` in the ethrex branch still documents the pre-composition layout** — -> flat `nonce`, flat fee fields, and a frame as `[mode, flags, target, gas_limit, value, data]` -> with no `limits` nesting. Anyone building from that section produces bytes the node rejects. -> Reporting this is a candidate contribution (§10). +A frame is: -### sig_hash - -``` -sig_hash = keccak256(0x06 || rlp(envelope with empty-msg signatures' bytes elided)) +```text +[mode, flags, target, [execution_gas, state_gas], value, data] ``` -Each signature whose `msg` is empty has its `signature` field replaced with empty bytes, -because a signature over `compute_sig_hash` cannot commit to its own bytes. Signatures with an -explicit 32-byte `msg` keep their bytes — they sign that digest, not this hash. All frame data -is committed verbatim. - -The consequence for the API: **the encoder is a dependency of the decoder's verification -path**, because `sig_hash` is defined over a re-encoding. Read-only work still exercises the -full round trip. - -### Signature schemes and canonical rules - -`scheme`: 0 ARBITRARY, 1 SECP256K1, 2 P256. - -- ARBITRARY — `signer` MUST be empty; `signature` is arbitrary bytes, EVM-readable via - `SIGPARAM` param `0x04`. No ECDSA rules apply. -- SECP256K1 — `signature = v||r||s`, 65 bytes; `v` is a **bare recovery id (`v <= 1`, not the - EVM's 27/28)**; `0 < r < SECP256K1N`; `s` low (`0 < s <= SECP256K1N/2`). -- P256 — `signature = r||s||qx||qy`, 128 bytes; `0 < r < SECP256R1N`; `0 < s <= SECP256R1N/2`. - `P256VERIFY` itself accepts high-`s`, so the signer must normalize `s` to `n - s` before use. - -These are **consensus rules**, checked in `validate_frame_signatures` before any frame executes. -A high-`s` or 27/28-encoded signature makes the whole transaction invalid, not merely -unrelayable — which makes them a correctness requirement of this library, not a lint. - -An empty `signer` resolves to `tx.sender` for SECP256K1 and P256, including for EVM -introspection. - -### Signing - -`signFrameTx(tx, signer)` takes either a raw private key or a `FrameAccount` — -`{ address, sign }`, satisfied by viem's `privateKeyToAccount` and `mnemonicToAccount`, by a -`toAccount` source, and by any wrapper around a hardware wallet, an HSM or a remote signer. -It signs exactly the entries that are SECP256K1 with an empty `msg`, over `sig_hash`, and -refuses when an entry's resolved signer is not the account's address — otherwise the result -would recover to the wrong address and be rejected at consensus with no local error. - -**Raw-digest signing is required.** `signMessage` prefixes its argument per EIP-191, so it -cannot produce a signature over `sig_hash`, and a `JsonRpcAccount` cannot sign a raw digest -at all. Both are refused with an error rather than silently producing an unrecoverable -signature. `sign` is typed optional because it is optional on viem's own `LocalAccount`; -the check is at runtime. - -**A returned `v` is normalized, not assumed.** viem returns 27/28; HSMs and hand-rolled -wrappers commonly return a bare 0/1. Both are accepted. An EIP-155 `v` is refused: it -encodes a chain id this layout has no room for, and guessing at its parity would forge a -recovery id. Subtracting 27 unconditionally — the obvious implementation — writes `0x-1a…` -into the signature, malformed hex that surfaces only as a byte-alignment error naming the -wrong problem. - -This does not widen §2's out-of-scope line on key management. The account form holds no key -material; it delegates key management to the caller instead of doing any. - -### Structural limits - -| Constant | Value | Source | -|---|---|---| -| `FRAME_TX_MAX_FRAMES` | 64 | `transaction.rs:2209` | -| `FRAME_TX_MAX_NONCE_KEYS` | 16 | `transaction.rs:2211` | -| `FRAME_TX_MAX_RECENT_ROOT_REFERENCES` | 16 | `transaction.rs:2213` | -| `FRAME_TX_EXPIRY_DATA_LENGTH` | 8 | `transaction.rs:2273` | - -`nonce_keys` rules (`transaction.rs:2679-2694`): between 1 and 16 entries; strictly increasing; -if more than one entry, the first may not be zero. Frame `value` must be zero unless the frame -is SENDER. Frame `flags` bits 0-1 are the APPROVE scope restriction, bit 2 the atomic-batch -flag, bits 3-7 reserved and must be zero. - -EIP-8272 window: `RECENT_ROOT_LENGTH = 8192`, and a declared reference is valid iff -`1 <= current_slot - slot <= 8191`. Domain separators are `keccak256("RECENT_ROOT_ENTRY")` and -`keccak256("RECENT_ROOT_STORAGE")`. - -## 4. The gas model - -Transcribed from `crates/common/types/transaction.rs`, which is the branch's current -(post-`77e502ef4`) behaviour. Every constant is written as its published figure. +A signature is: +```text +[scheme, signer, msg, signature] ``` -value_transfer_cost = Σ 6000 over frames where value != 0 - AND target is present - AND target != sender -signature_verification_cost = Σ per signature: ARBITRARY 100, SECP256K1 2800, P256 6700 +All integer fields use canonical minimal big-endian RLP. Zero is the empty RLP string, +not the byte `0x00`. -mandatory_gas = 12000 - + 475 * len(frames) - + signature_verification_cost - + value_transfer_cost +## Signature hash -billed_bytes = concat( frame.data for each frame, - sig.signer, sig.msg, sig.signature for each signature, - nonce_calldata, - recent_root_calldata ) +The canonical signature hash is `keccak256(0x06 || rlp(payload))` after replacing the +raw `signature` bytes of every signature whose `msg` is empty with `0x`. Frames and all +other fields remain unchanged. Because the signature commits to the envelope, any wire +format change must update encoding, decoding, hashing, signing, and fixtures together. -nonce_calldata = rlp(nonce_keys) || rlp(nonce_seq) -recent_root_calldata = rlp(recent_root_references), or empty when no reference is declared +SECP256K1 signatures use `v || r || s`, with `v` normalized to a bare recovery id `0` +or `1`. P256 and ARBITRARY entries are validated structurally but are not generated by +`signFrameTx`. -data_cost = Σ over billed_bytes: 4 if byte == 0 else 16 +## Frame accounts -recent_root_reference_intrinsic_gas = 0 when no references - = 2400 + 2002 * len(references) otherwise +`FrameAccountImplementation` follows viem's implementation/resolved-account split. +It supplies: -frame_tx_intrinsic_gas = mandatory_gas + data_cost + recent_root_reference_intrinsic_gas +- `getAddress()` +- `getNonce({ blockTag? })` +- `getValidationData({ calls, chainId, nonce })` +- `signFrameTransaction(transaction)` +- an execution strategy -state_gas_limit = Σ frame.limits.state -standard_gas_limit = frame_tx_intrinsic_gas - + Σ frame.limits.execution - + state_gas_limit +`toEoaFrameAccount` implements protocol default-code validation for a code-less EOA. +It reads the scalar nonce with `eth_getTransactionCount`, returns empty validation +calldata, and installs one empty-message SECP256K1 signature entry. -calldata_tokens = len(billed_bytes) * 4 -calldata_floor_gas = calldata_tokens * 16 # 64 gas per byte -calldata_floor_total = mandatory_gas - + recent_root_reference_intrinsic_gas - + calldata_floor_gas +## Gas -max_gas = max(standard_gas_limit, calldata_floor_total + state_gas_limit) -max_cost = max_gas * max_fee_per_gas - + len(blob_versioned_hashes) * 131072 * blob_base_fee -``` - -Four traps worth naming, because each is a place a reimplementation goes quietly wrong: - -1. **The RLP framing and the scalar fields are not billed** — only the byte fields listed in - `billed_bytes`. But `nonce_calldata` and `recent_root_calldata` *are* RLP encodings, and - their framing bytes are billed, because the EIP prices the bytes those EIPs add to the - payload. -2. **`recent_root_calldata` is empty, not `rlp([])`, when no reference is declared** - (`transaction.rs:2538-2540`), so a reference-free transaction's gas is exactly the EIP-8141 - figure. Encoding `rlp([])` here would add billed bytes to every transaction on the chain. -3. **State gas sits outside the floor and is added on top of it** — `max_gas` takes - `calldata_floor_total + state_gas_limit`, not `calldata_floor_total`. Both bound an - execution-dimension resource, so the floor branch cannot absorb the state sum. -4. **`frame_tx_intrinsic_gas` must be computed directly, never as - `total_gas_limit − frame budgets`**, because `total_gas_limit` may be the floor branch. +The mandatory gas terms are: -The EIP-7825 per-transaction cap applies to a *different* quantity — -`frame_tx_intrinsic_gas + Σ frame.limits.execution`, state excluded — and is checked separately. +```text +12000 ++ 475 * len(frames) ++ signature verification cost ++ 6000 for each value transfer to an explicit non-sender target +``` -The published intrinsic is **12000**, down from an earlier 15000 (`transaction.rs:2189-2195`). -`docs/eip-8141.md:362` in the ethrex branch still says 15000, and its formulas omit both -`state_gas_limit` and `recent_root_reference_intrinsic_gas`. Second candidate contribution (§10). +Signature verification costs are ARBITRARY `100`, SECP256K1 `2800`, and P256 `6700`. +Calldata cost and the calldata floor cover frame `data` and each signature's `signer`, +`msg`, and `signature` bytes. Envelope RLP, nonce, and other scalar fields are not +billed data. State gas is added on top of the calldata-floor branch. -### Rule sets +The historical `'chain'`, `'pins'`, and `'head'` parameters remain accepted by gas +helpers as compatibility aliases; they currently use the same rules. -The gas module takes a rule-set parameter. This is load-bearing, not generality for its own -sake: the deployed nodes run ethrex `31b532266`, which carries two divergences from the pinned -EIP text, so a single hardcoded model cannot be simultaneously correct and green against live -data. +## Module boundaries -| Rule set | Meaning | +| Module | Responsibility | |---|---| -| `'chain'` | What `31b532266` does — the two live divergences included | -| `'pins'` | The pinned EIP text: EIP-8141 `7d1c8bfb94`, EIP-8250 `e5cf246ff1`, EIP-8272 `0231fb05f5` | -| `'head'` | Current drafts, for anticipating the next re-genesis | - -The two divergences that separate `'chain'` from `'pins'`: +| `types` | Public frame transaction and account-independent types | +| `rlp` | Canonical scalar and offset-aware RLP helpers | +| `envelope` | Encode, decode, and structural validation | +| `sighash` | Canonical signature hash | +| `signatures` | Signature validation, recovery, and signing | +| `accounts` | Generic frame accounts and the direct EOA adapter | +| `gas` | Pure gas and maximum-cost accounting | +| `rpc` | Frame transaction/receipt JSON parsing and optional simulation wrapper | +| `viem` | viem client extension | + +`gas` deliberately does not depend on `envelope`; this keeps accounting independently +testable. `envelope` does not depend on `signatures`; the reverse direction is allowed. - **`value_cost`** — the chain charges `TX_VALUE_COST` for every frame with `value > 0`; the pins charge it only when the frame has a target that is not `tx.sender`. A targetless or @@ -276,30 +176,15 @@ The two divergences that separate `'chain'` from `'pins'`: divergence and affects validation-prefix replay rather than the gas model, so it is recorded but not modelled. -What `'head'` changes, per the branch spec's "Changed upstream since the pins": - -- **EIP-8250** moves the first use of a keyed nonce from 20,000 execution gas, deducted from the - frame's remaining gas, to **97,920 state gas** charged during the payment `APPROVE`. A frame - consuming two fresh nullifier keys needs 195,840 of `limits.state` under `'head'` and none - here. -- **EIP-8272** drops the envelope field, `TXPARAM 0x11` and `RECENTROOTREFLOAD` entirely, - carrying references instead as a leading VERIFY frame targeting - `0x0000000000000000000000000000000000008272`. Confirmed against upstream - `ethereum/EIPs` `eip-8272.md` @ `824cbc0b0` (2026-09-07): the "recent root verifier frame" - is `mode == VERIFY`, `target == RECENT_ROOT_ADDRESS`, `flags == 0`, `value == 0`, - `limits.state == 0`, and its data is `n` tuples of `source_id: bytes32 || slot: uint64_be - || root: bytes32` — `RECENT_ROOT_TUPLE_BYTES = 72` — with no selector or length prefix. - The spec adds **no** special intrinsic gas, warming rule, or block-gas exemption: the - frame is priced as ordinary EIP-8141 frame data plus one more `FRAME_TX_PER_FRAME_COST`. - This changes the *envelope*, not only the gas, so `'head'` cannot share the `'chain'` - encoder. `divergence.toHeadShape` applies the change as a transformation of the - transaction: the field is emptied and its contents prepended as one VERIFY frame with zero - limits, which the existing pricer then prices. `compareRuleSets` routes whichever side names `'head'` - through it. `gas` fabricates nothing and `frameTxGas(tx, 'head')` still refuses a - reference-carrying transaction, so the floor that zero `limits.execution` produces — the - one figure the spec does not pin, since it falls out of the `STATICCALL` and the per-tuple - `SLOAD`s — cannot be mistaken for a budget. No second serializer: the transform yields a - `FrameTransaction`, never bytes. +The hermetic suite pins: + +- Ethrex v23's golden frame transaction bytes +- Ethrex v23's canonical signature hash +- strict canonical-RLP rejection and byte offsets +- signature normalization and recovery +- scalar nonce retrieval for EOAs +- gas-accounting terms +- RPC transaction and receipt formatting ## 5. Modules diff --git a/docs/OPEN-ITEMS.md b/docs/OPEN-ITEMS.md index 459f9b3..4a97fdf 100644 --- a/docs/OPEN-ITEMS.md +++ b/docs/OPEN-ITEMS.md @@ -1,4 +1,4 @@ -# frametx-kit — open items +# frametx-kit open items Known gaps and unfinished work, current as of ethrex `hegota-testnet` @ `19c065fa8`. The invariants and wire-format traps are in `../CONTRIBUTING.md`; `DESIGN.md` is the diff --git a/package.json b/package.json index f28636f..a09a2cc 100644 --- a/package.json +++ b/package.json @@ -59,10 +59,8 @@ "keywords": [ "ethereum", "eip-8141", - "eip-8250", - "eip-8272", "frame-transaction", - "hegota-testnet", + "frames-devnet", "ethrex", "viem", "rlp" @@ -70,8 +68,8 @@ "scripts": { "build": "tsup", "test": "vitest run", - "test:watch": "vitest", "test:live": "FRAMES_LIVE=1 vitest run test/live", + "test:watch": "vitest", "typecheck": "tsc --noEmit" }, "peerDependencies": { diff --git a/scripts/capture-fixtures.ts b/scripts/capture-fixtures.ts index e20aa32..b403060 100644 --- a/scripts/capture-fixtures.ts +++ b/scripts/capture-fixtures.ts @@ -1,5 +1,8 @@ /** - * Capture live type-0x06 transactions as test fixtures. + * Legacy fixture capture script for the retired chain-8141 envelope. + * + * Do not use this to produce current wire-format fixtures. The frames-devnet RPC + * does not expose the simulation method this historical capture flow requires. * * The public endpoint serves no raw transaction bytes — ethrex has no * `eth_getRawTransactionByHash`, and `debug_getRawTransaction` is refused by diff --git a/scripts/send-eth-eoa.ts b/scripts/send-eth-eoa.ts new file mode 100644 index 0000000..7504919 --- /dev/null +++ b/scripts/send-eth-eoa.ts @@ -0,0 +1,145 @@ +/** + * Send native ETH from a code-less EOA using an EIP-8141 frame transaction. + * + * Required: + * PRIVATE_KEY=0x... RECIPIENT=0x... bun run scripts/send-eth-eoa.ts + * + * Optional: + * AMOUNT_ETH=0.001 + * RPC_URL=https://rpc1.frames.ethrex.xyz + * DRY_RUN=1 + */ +import { + createPublicClient, + defineChain, + formatEther, + getAddress, + http, + keccak256, + parseEther, + type Address, + type Hex, +} from 'viem' +import { privateKeyToAccount } from 'viem/accounts' +import { + assertValidFrameTx, + encodeFrameTx, + frameTxGas, + frameTxMaxCost, + parseRpcFrameReceipt, + prepareFrameTransaction, + signFrameTransaction, + toEoaFrameAccount, + type FrameRpcClient, + type RpcFrameReceiptJson, +} from '../src/index.js' + +const CHAIN_ID = 81410n +const DEFAULT_RPC_URL = 'https://rpc1.frames.ethrex.xyz' +const RECEIPT_TIMEOUT_MS = 120_000 +const framesDevnet = defineChain({ + id: Number(CHAIN_ID), + name: 'Ethrex Frames Devnet', + nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, + rpcUrls: { default: { http: [DEFAULT_RPC_URL] } }, +}) + +function requiredEnv(name: string): string { + const value = process.env[name] + if (!value) throw new Error(`${name} is required`) + return value +} + +function privateKeyFromEnv(): Hex { + const value = requiredEnv('PRIVATE_KEY') + if (!/^0x[0-9a-fA-F]{64}$/.test(value)) + throw new Error('PRIVATE_KEY must be a 32-byte 0x-prefixed hex value') + return value as Hex +} + +async function waitForFrameReceipt( + client: FrameRpcClient, + hash: Hex, +): Promise { + const deadline = Date.now() + RECEIPT_TIMEOUT_MS + + while (Date.now() < deadline) { + const receipt = (await client.request({ + method: 'eth_getTransactionReceipt', + params: [hash], + })) as RpcFrameReceiptJson | null + + if (receipt !== null) return receipt + await new Promise((resolve) => setTimeout(resolve, 1_000)) + } + + throw new Error( + `transaction ${hash} was not mined within ${RECEIPT_TIMEOUT_MS / 1_000}s`, + ) +} + +async function main(): Promise { + const rpcUrl = process.env.RPC_URL ?? DEFAULT_RPC_URL + const owner = privateKeyToAccount(privateKeyFromEnv()) + const recipient: Address = getAddress(requiredEnv('RECIPIENT')) + const amount = parseEther(process.env.AMOUNT_ETH ?? '0.001') + const dryRun = process.env.DRY_RUN === '1' + + const client = createPublicClient({ + chain: framesDevnet, + transport: http(rpcUrl), + }) + const account = await toEoaFrameAccount({ client, owner }) + + const unsigned = await prepareFrameTransaction( + account, + [{ to: recipient, value: amount, data: '0x' }], + { + validation: { execution: 80_000n, state: 0n }, + calls: [{ execution: 30_000n, state: 200_000n }], + }, + ) + + const signed = await signFrameTransaction(account, unsigned) + assertValidFrameTx(signed) + + const raw = encodeFrameTx(signed) + const transactionHash = keccak256(raw) + const gas = frameTxGas(signed, 'chain') + const maxGasCost = frameTxMaxCost(signed, 0n, 'chain') + + console.log(`raw tx: ${raw}`) + console.log(`sender: ${account.address}`) + console.log(`recipient: ${recipient}`) + console.log(`amount: ${formatEther(amount)} ETH`) + console.log(`nonce: ${signed.nonce}`) + console.log(`max gas: ${gas.maxGas}`) + console.log(`max gas cost: ${formatEther(maxGasCost)} ETH`) + console.log(`local hash: ${transactionHash}`) + + if (dryRun) { + console.log('DRY_RUN=1, so the valid transaction was not broadcast') + return + } + + const submittedHash = (await client.request({ + method: 'eth_sendRawTransaction', + params: [raw], + })) as Hex + + if (submittedHash.toLowerCase() !== transactionHash.toLowerCase()) + throw new Error( + `node returned hash ${submittedHash}, expected ${transactionHash}`, + ) + + console.log(`submitted: ${submittedHash}`) + const rpcReceipt = await waitForFrameReceipt(client, submittedHash) + const receipt = parseRpcFrameReceipt(rpcReceipt) + console.log('payer:', receipt.payer) + console.log('frames:', receipt.frameReceipts) +} + +main().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : error) + process.exitCode = 1 +}) diff --git a/src/accounts/toEoaFrameAccount.ts b/src/accounts/toEoaFrameAccount.ts new file mode 100644 index 0000000..4499a3e --- /dev/null +++ b/src/accounts/toEoaFrameAccount.ts @@ -0,0 +1,119 @@ +import { + type Account, + type Address, + type Chain, + type Client, + type Hash, + type Hex, + type JsonRpcAccount, + type LocalAccount, + type Transport, + isAddressEqual, +} from 'viem' +import { signFrameTx } from '../signatures.js' +import { FrameEncodeError } from '../errors.js' +import type { FrameTransaction } from '../types.js' +import { toFrameAccount } from './toFrameAccount.js' +import type { + FrameAccount, + FrameAccountImplementation, + GetFrameNonceParameters, +} from './types.js' + +export type EoaFrameOwner = Account & { + address: Address + sign: (parameters: { hash: Hash }) => Promise +} + +export type EoaFrameAccountImplementation< + chain extends Chain | undefined = Chain | undefined, + owner extends EoaFrameOwner = EoaFrameOwner, + extend extends object = object, +> = FrameAccountImplementation + +export type ToEoaFrameAccountParameters< + chain extends Chain | undefined = Chain | undefined, + owner extends EoaFrameOwner = EoaFrameOwner, + extend extends object = object, +> = { + client: Client< + Transport, + chain, + JsonRpcAccount | LocalAccount | undefined + > + owner: owner + extend?: extend | undefined +} + +export type ToEoaFrameAccountReturnType< + chain extends Chain | undefined = Chain | undefined, + owner extends EoaFrameOwner = EoaFrameOwner, + extend extends object = object, +> = FrameAccount> + +async function getEoaFrameNonce< + chain extends Chain | undefined, + owner extends EoaFrameOwner, +>( + client: Client< + Transport, + chain, + JsonRpcAccount | LocalAccount | undefined + >, + sender: Address, + parameters: GetFrameNonceParameters, +): Promise { + const nonce = await client.request({ + method: 'eth_getTransactionCount', + params: [sender, parameters.blockTag ?? 'pending'], + }) + return BigInt(nonce) +} + +/** Create a direct-execution frame account backed by an ordinary EOA. */ +export async function toEoaFrameAccount< + chain extends Chain | undefined, + owner extends EoaFrameOwner, + extend extends object = object, +>( + parameters: ToEoaFrameAccountParameters, +): Promise> { + const { client, owner } = parameters + + return toFrameAccount({ + client, + owner, + execution: { type: 'direct' }, + ...(parameters.extend === undefined ? {} : { extend: parameters.extend }), + async getAddress() { + return owner.address + }, + async getNonce(nonceParameters = {}) { + return getEoaFrameNonce(client, owner.address, nonceParameters) + }, + async getValidationData() { + return '0x' + }, + async signFrameTransaction(transaction: FrameTransaction) { + if (!isAddressEqual(transaction.sender, owner.address)) + throw new FrameEncodeError( + `transaction sender ${transaction.sender} does not match EOA ${owner.address}`, + ) + + return signFrameTx( + { + ...transaction, + signatures: [ + { + scheme: 1, + signer: null, + msg: '0x', + signature: '0x', + }, + ], + }, + owner, + ) + }, + }) +} diff --git a/src/accounts/toFrameAccount.ts b/src/accounts/toFrameAccount.ts new file mode 100644 index 0000000..db8dc58 --- /dev/null +++ b/src/accounts/toFrameAccount.ts @@ -0,0 +1,31 @@ +import type { + FrameAccount, + FrameAccountImplementation, +} from './types.js' + +export type ToFrameAccountParameters< + implementation extends + FrameAccountImplementation = FrameAccountImplementation, +> = implementation + +export type ToFrameAccountReturnType< + implementation extends + FrameAccountImplementation = FrameAccountImplementation, +> = FrameAccount + +/** Resolve an account implementation into the object consumed by frame actions. */ +export async function toFrameAccount< + const implementation extends FrameAccountImplementation, +>( + implementation: ToFrameAccountParameters, +): Promise> { + const { extend, ...rest } = implementation + const address = await implementation.getAddress() + + return { + ...extend, + ...rest, + address, + type: 'frame', + } as ToFrameAccountReturnType +} diff --git a/src/accounts/types.ts b/src/accounts/types.ts new file mode 100644 index 0000000..33be036 --- /dev/null +++ b/src/accounts/types.ts @@ -0,0 +1,92 @@ +import type { + Account, + Address, + BlockTag, + Chain, + Client, + Hex, + JsonRpcAccount, + LocalAccount, + Transport, +} from 'viem' +import type { FrameTransaction } from '../types.js' + +export type FrameCall = { + to: Address + value: bigint + data: Hex +} + +export type GetFrameNonceParameters = { + blockTag?: BlockTag | undefined +} + +export type GetValidationDataParameters = { + calls: readonly FrameCall[] + chainId: bigint + nonce: bigint +} + +export type DirectFrameExecution = { + type: 'direct' +} + +/** Account-specific behavior required to construct and sign frame transactions. */ +export type FrameAccountImplementation< + chain extends Chain | undefined = Chain | undefined, + owner extends Account | undefined = Account | undefined, + extend extends object = object, +> = { + /** Client used to read account and nonce state. */ + client: Client< + Transport, + chain, + JsonRpcAccount | LocalAccount | undefined + > + /** Account or signer that controls the frame account. */ + owner: owner + /** How calls are represented by execution frames. */ + execution: DirectFrameExecution + /** Add implementation-specific properties to the resolved account. */ + extend?: extend | undefined + /** Resolve the sender address represented by this account. */ + getAddress: () => Promise
+ /** Resolve the sender's scalar account nonce. */ + getNonce: (parameters?: GetFrameNonceParameters) => Promise + /** Produce calldata for the account's EIP-8141 validation frame. */ + getValidationData: (parameters: GetValidationDataParameters) => Promise + /** Apply the account's signature scheme and ordering to a frame transaction. */ + signFrameTransaction: ( + transaction: FrameTransaction, + ) => Promise +} + +type Assign = Omit< + base, + keyof overrides +> & + overrides + +type Simplify = { [key in keyof type]: type[key] } & {} + +type AccountExtension = + NonNullable + +/** A resolved frame account, analogous to viem's resolved SmartAccount type. */ +export type FrameAccount< + implementation extends + FrameAccountImplementation = FrameAccountImplementation, +> = Simplify< + Assign< + AccountExtension, + Assign< + Omit, + { + /** Resolved sender address. */ + address: Address + /** Discriminator for frame-account-aware APIs. */ + type: 'frame' + } + > + > +> diff --git a/src/divergence.ts b/src/divergence.ts index a991663..68d3612 100644 --- a/src/divergence.ts +++ b/src/divergence.ts @@ -1,71 +1,5 @@ -import { type Address, type Hex, concatHex, numberToHex } from 'viem' import { type FrameGas, frameTxGas } from './gas.js' -import type { Frame, FrameTransaction, RecentRootReference, RuleSet } from './types.js' - -/** - * EIP-8250 at head: the first use of a keyed nonce moved from 20,000 execution - * gas, deducted from the frame's remaining gas, to 97,920 STATE gas charged - * during the payment APPROVE and attributed to the frame that calls it. - * - * A frame consuming two fresh nullifier keys needs 195,840 of limits.state under - * the head draft, and none on this chain. Adopting it is a re-genesis. - */ -export const HEAD_KEYED_NONCE_STATE_GAS = 97_920n - -/** - * EIP-8272 at head: the envelope field, `TXPARAM 0x11` and `RECENTROOTREFLOAD` are - * gone. References travel instead as a "recent root verifier frame" against this - * address (upstream `eip-8272.md` @ `824cbc0b0`, §Recent root verifier frame). - */ -export const HEAD_RECENT_ROOT_VERIFIER: Address = - '0x0000000000000000000000000000000000008272' - -/** - * `RECENT_ROOT_TUPLE_BYTES` from upstream `eip-8272.md`: one packed reference is - * `source_id: bytes32 || slot: uint64_be || root: bytes32`, 32 + 8 + 32. - */ -export const HEAD_REFERENCE_BYTES = 72 - -// Field order and widths per upstream `eip-8272.md` @ `824cbc0b0` -// (§"Validation operation"): the tuples are concatenated with no selector or -// length prefix. `slot` is a big-endian u64 — the same width `validateFrameTx` -// already holds it to (`assertUint(ref.slot, 64, …)`). -function packReference(ref: RecentRootReference): Hex { - return concatHex([ref.sourceId, numberToHex(ref.slot, { size: 8 }), ref.root]) -} - -/** - * The head-shaped equivalent of a reference-carrying transaction: the envelope - * field emptied, its contents prepended as one VERIFY frame. - * - * The frame's `mode`, `target`, `flags`, `value` and `limits.state` are the ones - * upstream `eip-8272.md` (§Recent root verifier frame) makes normative for the - * shape. Its `limits.execution` is set to zero because that is the one figure the - * spec does not pin — it falls out of executing the `STATICCALL` and one `SLOAD` - * per tuple — so every limit-derived gas term of the result is a floor. That is - * why this is the divergence survey's entry point and `frameTxGas(tx, 'head')` - * still refuses a reference-carrying transaction: a floor is fine to compare - * against and wrong to budget with. - * - * The frame is prepended at index 0. The spec places it after an optional - * `expiry_verify` frame, but frame order does not affect the gas terms priced - * here, so the survey does not model the offset. - * - * Identity for a transaction that carries no reference. - */ -export function toHeadShape(tx: FrameTransaction): FrameTransaction { - if (tx.recentRootReferences.length === 0) return tx - - const verify: Frame = { - mode: 1, - flags: 0, - target: HEAD_RECENT_ROOT_VERIFIER, - limits: { execution: 0n, state: 0n }, - value: 0n, - data: concatHex(tx.recentRootReferences.map(packReference)), - } - return { ...tx, frames: [verify, ...tx.frames], recentRootReferences: [] } -} +import type { FrameTransaction, RuleSet } from './types.js' export type GasDivergence = { term: keyof FrameGas @@ -83,18 +17,16 @@ export type GasDivergence = { * on live chain data that the divergence ledger does not already explain is a * finding worth reporting. * - * Whichever side names `'head'` is priced over `toHeadShape(tx)`, so a - * reference-carrying transaction compares against the head envelope rather than - * being refused. Both sides are transformed independently, so argument order - * never changes the outcome. + * The rule-set names are compatibility aliases now that the current envelope + * has removed the keyed-nonce and recent-root extensions. */ export function compareRuleSets( tx: FrameTransaction, a: RuleSet, b: RuleSet, ): GasDivergence[] { - const gasA = frameTxGas(a === 'head' ? toHeadShape(tx) : tx, a) - const gasB = frameTxGas(b === 'head' ? toHeadShape(tx) : tx, b) + const gasA = frameTxGas(tx, a) + const gasB = frameTxGas(tx, b) const divergences: GasDivergence[] = [] for (const term of Object.keys(gasA) as (keyof FrameGas)[]) { diff --git a/src/envelope.ts b/src/envelope.ts index 111cdad..0fd4886 100644 --- a/src/envelope.ts +++ b/src/envelope.ts @@ -3,7 +3,6 @@ import type { Frame, FrameSignature, FrameTransaction, - RecentRootReference, FrameLimits, FrameMode, SigScheme, @@ -31,17 +30,12 @@ function encodeSignature(sig: FrameSignature): RlpTree { return [rlpUint(BigInt(sig.scheme)), sig.signer ?? '0x', sig.msg, sig.signature] } -function encodeRecentRootReference(ref: RecentRootReference): RlpTree { - return [ref.sourceId, rlpUint(ref.slot), ref.root] -} - /** The RLP body, without the `0x06` type prefix. */ export function encodeFrameTxBody(tx: FrameTransaction): Hex { return toRlp( [ rlpUint(tx.chainId), - tx.nonceKeys.map(rlpUint), - rlpUint(tx.nonceSeq), + rlpUint(tx.nonce), tx.sender, tx.frames.map(encodeFrame), tx.signatures.map(encodeSignature), @@ -51,7 +45,6 @@ export function encodeFrameTxBody(tx: FrameTransaction): Hex { rlpUint(tx.maxFeePerBlobGas), ], tx.blobVersionedHashes, - tx.recentRootReferences.map(encodeRecentRootReference), ] satisfies RlpTree, 'hex', ) @@ -143,20 +136,6 @@ function decodeSignature(node: RlpNode): FrameSignature { } } -function decodeRecentRootReference(node: RlpNode): RecentRootReference { - const r = asList(node, 'recentRootReference') - if (r.length !== 3) - throw new FrameDecodeError( - `recentRootReference must have 3 fields, got ${r.length}`, - node.start, - ) - return { - sourceId: asHex(r[0]!, 'recentRootReference.sourceId'), - slot: asUint(r[1]!, 'recentRootReference.slot'), - root: asHex(r[2]!, 'recentRootReference.root'), - } -} - function decodeFields( fields: readonly RlpNode[], fees: readonly RlpNode[], @@ -164,20 +143,16 @@ function decodeFields( ): FrameTransaction { return { chainId: asUint(fields[0]!, 'chainId'), - nonceKeys: asList(fields[1]!, 'nonceKeys').map((k) => asUint(k, 'nonceKeys[]')), - nonceSeq: asUint(fields[2]!, 'nonceSeq'), + nonce: asUint(fields[1]!, 'nonce'), sender, - frames: asList(fields[4]!, 'frames').map(decodeFrame), - signatures: asList(fields[5]!, 'signatures').map(decodeSignature), + frames: asList(fields[3]!, 'frames').map(decodeFrame), + signatures: asList(fields[4]!, 'signatures').map(decodeSignature), maxPriorityFeePerGas: asUint(fees[0]!, 'maxPriorityFeePerGas'), maxFeePerGas: asUint(fees[1]!, 'maxFeePerGas'), maxFeePerBlobGas: asUint(fees[2]!, 'maxFeePerBlobGas'), - blobVersionedHashes: asList(fields[7]!, 'blobVersionedHashes').map((h) => + blobVersionedHashes: asList(fields[6]!, 'blobVersionedHashes').map((h) => asHex(h, 'blobVersionedHashes[]'), ), - recentRootReferences: asList(fields[8]!, 'recentRootReferences').map( - decodeRecentRootReference, - ), } } @@ -218,22 +193,22 @@ export function decodeFrameTx(raw: Hex): FrameTransaction { } const fields = asList(tree, 'envelope') - if (fields.length !== 9) + if (fields.length !== 7) throw new FrameDecodeError( - `envelope must have 9 fields, got ${fields.length}`, + `envelope must have 7 fields, got ${fields.length}`, tree.start, ) - const fees = asList(fields[6]!, 'fees') + const fees = asList(fields[5]!, 'fees') if (fees.length !== 3) throw new FrameDecodeError( `fees must have 3 fields, got ${fees.length}`, - fields[6]!.start, + fields[5]!.start, ) - const sender = asAddressOrNull(fields[3]!, 'sender') + const sender = asAddressOrNull(fields[2]!, 'sender') if (sender === null) - throw new FrameDecodeError('sender may not be empty', fields[3]!.start) + throw new FrameDecodeError('sender may not be empty', fields[2]!.start) const tx = decodeFields(fields, fees, sender) @@ -251,8 +226,6 @@ export function decodeFrameTx(raw: Hex): FrameTransaction { } export const MAX_FRAMES = 64 -export const MAX_NONCE_KEYS = 16 -export const MAX_RECENT_ROOT_REFERENCES = 16 /** EIP-7594 per-transaction blob limit; frame transactions inherit it unchanged. */ export const MAX_BLOBS_PER_TX = 6 /** EIP-8141 expiry-verifier predeploy. A VERIFY frame targeting it is an expiry frame. */ @@ -328,13 +301,11 @@ function isExpiryVerifier(frame: Frame): boolean { } function assertFieldWidths(tx: FrameTransaction): void { - // These are the widths ethrex's decoder reads the fields at (`chain_id`, - // `nonce_seq`, both non-blob fees and `RecentRootReference::slot` are u64; - // `max_fee_per_blob_gas`, the nonce keys and `Frame::value` are U256). + // These are the widths ethrex's decoder reads the fields at. assertUint(tx.chainId, 64, 'chainId') - assertUint(tx.nonceSeq, 64, 'nonceSeq') - assertUint(tx.maxPriorityFeePerGas, 64, 'maxPriorityFeePerGas') - assertUint(tx.maxFeePerGas, 64, 'maxFeePerGas') + assertUint(tx.nonce, 64, 'nonce') + assertUint(tx.maxPriorityFeePerGas, 256, 'maxPriorityFeePerGas') + assertUint(tx.maxFeePerGas, 256, 'maxFeePerGas') assertUint(tx.maxFeePerBlobGas, 256, 'maxFeePerBlobGas') } @@ -353,36 +324,8 @@ function assertFrameCount(tx: FrameTransaction): void { } function assertNonce(tx: FrameTransaction): void { - if (tx.nonceKeys.length < 1 || tx.nonceKeys.length > MAX_NONCE_KEYS) - throw new FrameEncodeError( - `nonceKeys must hold between 1 and ${MAX_NONCE_KEYS} entries, got ${tx.nonceKeys.length}`, - ) - for (const [i, key] of tx.nonceKeys.entries()) assertUint(key, 256, `nonceKeys[${i}]`) - for (let i = 1; i < tx.nonceKeys.length; i++) - if (tx.nonceKeys[i - 1]! >= tx.nonceKeys[i]!) - throw new FrameEncodeError('nonceKeys must be strictly increasing') - if (tx.nonceKeys.length > 1 && tx.nonceKeys[0] === 0n) - throw new FrameEncodeError( - 'the first nonce key may only be zero when it is the only key', - ) - if (tx.nonceSeq >= U64_MAX) - throw new FrameEncodeError('nonceSeq must be below 2**64 - 1') -} - -function assertRecentRootReferences(tx: FrameTransaction): void { - if (tx.recentRootReferences.length > MAX_RECENT_ROOT_REFERENCES) - throw new FrameEncodeError( - `at most ${MAX_RECENT_ROOT_REFERENCES} recent-root references, got ${tx.recentRootReferences.length}`, - ) - // `source_id` and `root` are H256 in ethrex, decoded through the fixed - // `[u8; 32]` impl: any other length fails RLP decode with InvalidLength. - for (const [i, ref] of tx.recentRootReferences.entries()) { - if (checkedByteLength(ref.sourceId, `recentRootReference ${i}: sourceId`) !== 32) - throw new FrameEncodeError(`recentRootReference ${i}: sourceId must be 32 bytes`) - if (checkedByteLength(ref.root, `recentRootReference ${i}: root`) !== 32) - throw new FrameEncodeError(`recentRootReference ${i}: root must be 32 bytes`) - assertUint(ref.slot, 64, `recentRootReference ${i}: slot`) - } + if (tx.nonce >= U64_MAX) + throw new FrameEncodeError('nonce must be below 2**64 - 1') } function assertBlobs(tx: FrameTransaction): void { @@ -510,7 +453,6 @@ export function validateFrameTx(tx: FrameTransaction): void { assertSender(tx) assertFrameCount(tx) assertNonce(tx) - assertRecentRootReferences(tx) assertBlobs(tx) assertSignatures(tx) assertFrames(tx) diff --git a/src/gas.ts b/src/gas.ts index 68878b5..998ccd2 100644 --- a/src/gas.ts +++ b/src/gas.ts @@ -1,6 +1,5 @@ -import { type Address, type Hex, concatHex, toRlp } from 'viem' -import { FrameEncodeError } from './errors.js' -import { byteLength, rlpUint } from './rlp.js' +import { type Address, type Hex } from 'viem' +import { byteLength } from './rlp.js' import type { FrameTransaction, RuleSet, SigScheme } from './types.js' // EIP-8141 Constants table. Written as published figures, never derived: ethrex's @@ -13,11 +12,6 @@ export const STANDARD_TOKEN_COST = 4n export const TOTAL_COST_FLOOR_PER_TOKEN = 16n export const GAS_PER_BLOB = 131_072n -/** EIP-8272: ACCESS_LIST_ADDRESS_COST, and - * ACCESS_LIST_STORAGE_KEY_COST + 2*KECCAK256_BASE_GAS + 7*KECCAK256_WORD_GAS. */ -export const RECENT_ROOT_REFERENCE_ADDRESS_GAS = 2_400n -export const RECENT_ROOT_REFERENCE_GAS = 2_002n - export const SIG_VERIFY_COST: Record = { 0: 100n, 1: 2_800n, @@ -31,7 +25,6 @@ export type FrameGas = { /** Total length in bytes of every billed field. */ billedBytes: bigint dataCost: bigint - recentRootReferenceGas: bigint intrinsicGas: bigint stateGasLimit: bigint standardGasLimit: bigint @@ -42,37 +35,15 @@ export type FrameGas = { maxGas: bigint } -/** EIP-8250 `nonce_calldata`: rlp(nonce_keys) || rlp(nonce_seq). */ -export function nonceCalldata(tx: FrameTransaction): Hex { - return concatHex([toRlp(tx.nonceKeys.map(rlpUint), 'hex'), toRlp(rlpUint(tx.nonceSeq), 'hex')]) -} - -/** - * EIP-8272 `recent_root_calldata`: rlp(recent_root_references), or EMPTY when no - * reference is declared — not `toRlp([])`, which would add a billed byte to every - * transaction on the chain. - */ -export function recentRootCalldata(tx: FrameTransaction): Hex { - if (tx.recentRootReferences.length === 0) return '0x' - return toRlp( - tx.recentRootReferences.map((r) => [r.sourceId, rlpUint(r.slot), r.root]), - 'hex', - ) -} - /** * The fields the calldata cost is charged over: each frame's `data`, each - * signature's `signer`, `msg` and `signature`, the nonce calldata and the - * recent-root calldata. The envelope's RLP framing and its scalar fields are - * NOT billed — but the two calldata blobs above are themselves RLP, and their - * framing bytes are billed. + * signature's `signer`, `msg` and `signature`. The envelope's RLP framing and + * its scalar fields are not billed. */ function billedFields(tx: FrameTransaction): Hex[] { return [ ...tx.frames.map((f) => f.data), ...tx.signatures.flatMap((s) => [s.signer ?? '0x', s.msg, s.signature] as Hex[]), - nonceCalldata(tx), - recentRootCalldata(tx), ] } @@ -94,23 +65,13 @@ function sameAddress(a: Address, b: Address): boolean { /** * EIP-8141 `value_transfer_cost`. * - * The rule sets differ here, and this is the divergence you can observe on the - * live chain: ethrex 31b532266 charges every value-carrying frame, while the - * pinned text charges only a frame whose target is present and is not tx.sender. - * A targetless or self-targeted value frame is therefore overcharged 6000 on the - * deployed chain. Divergence-ledger row 3.8. + * Charged only when a frame moves value to an explicit target other than the + * transaction sender. */ -function valueTransferCost(tx: FrameTransaction, rules: RuleSet): bigint { +function valueTransferCost(tx: FrameTransaction): bigint { let total = 0n for (const frame of tx.frames) { if (frame.value === 0n) continue - if (rules === 'chain') { - total += FRAME_TX_VALUE_COST - continue - } - // Compare case-insensitively: `getAddress` returns EIP-55 mixed case while a - // hand-written fixture is lowercase, and a `!==` between the two would charge - // TX_VALUE_COST on a self-targeted frame that the pinned rule exempts. if (frame.target !== null && !sameAddress(frame.target, tx.sender)) total += FRAME_TX_VALUE_COST } @@ -118,31 +79,11 @@ function valueTransferCost(tx: FrameTransaction, rules: RuleSet): bigint { } /** - * Price a frame transaction under a rule set. - * - * Only `valueTransferCost` depends on the rule set, and only between `'chain'` - * and `'pins'`. `'head'` prices identically to `'pins'` here: the head EIP-8250 - * change (97,920 state gas on the first use of a keyed nonce) is an - * execution-time charge against `limits.state`, not an intrinsic term, so it - * moves what a builder must budget, not what this function computes. The figure - * lives in `divergence.ts` as `HEAD_KEYED_NONCE_STATE_GAS`. - * - * `'head'` is refused, not modeled, for a transaction that carries any - * recent-root reference: the head EIP-8272 draft removes the envelope's - * recent-root field entirely (references become a leading VERIFY frame - * carrying 72 bytes of data each), so the `2400 + 2002·n` intrinsic term and - * the billed RLP reference bytes computed here have no head-shaped equivalent - * to compare against — this function does not model the head envelope shape. + * Price a frame transaction. The rule-set argument remains as a compatibility + * alias; all names use the current EIP-8141 accounting rules. */ -export function frameTxGas(tx: FrameTransaction, rules: RuleSet = 'chain'): FrameGas { - if (rules === 'head' && tx.recentRootReferences.length > 0) - throw new FrameEncodeError( - 'the head EIP-8272 draft removes the recent-root envelope field entirely ' + - '(references become a leading VERIFY frame carrying 72 bytes of data each), ' + - 'so this transaction has no head-shaped equivalent and frameTxGas does not model it', - ) - - const valueCost = valueTransferCost(tx, rules) +export function frameTxGas(tx: FrameTransaction, _rules: RuleSet = 'chain'): FrameGas { + const valueCost = valueTransferCost(tx) const sigCost = tx.signatures.reduce( (acc, s) => acc + SIG_VERIFY_COST[s.scheme], 0n, @@ -157,13 +98,7 @@ export function frameTxGas(tx: FrameTransaction, rules: RuleSet = 'chain'): Fram const billedBytes = fields.reduce((acc, f) => acc + BigInt(byteLength(f)), 0n) const dataCost = calldataCost(fields) - const recentRootReferenceGas = - tx.recentRootReferences.length === 0 - ? 0n - : RECENT_ROOT_REFERENCE_ADDRESS_GAS + - BigInt(tx.recentRootReferences.length) * RECENT_ROOT_REFERENCE_GAS - - const intrinsicGas = mandatoryGas + dataCost + recentRootReferenceGas + const intrinsicGas = mandatoryGas + dataCost const stateGasLimit = tx.frames.reduce((acc, f) => acc + f.limits.state, 0n) const executionGasLimit = tx.frames.reduce((acc, f) => acc + f.limits.execution, 0n) @@ -171,7 +106,7 @@ export function frameTxGas(tx: FrameTransaction, rules: RuleSet = 'chain'): Fram const calldataTokens = billedBytes * STANDARD_TOKEN_COST const calldataFloorGas = calldataTokens * TOTAL_COST_FLOOR_PER_TOKEN - const calldataFloorTotal = mandatoryGas + recentRootReferenceGas + calldataFloorGas + const calldataFloorTotal = mandatoryGas + calldataFloorGas // State gas is added ON TOP of the floor: both bound an execution-dimension // resource, so the floor branch cannot absorb the state sum. @@ -186,7 +121,6 @@ export function frameTxGas(tx: FrameTransaction, rules: RuleSet = 'chain'): Fram mandatoryGas, billedBytes, dataCost, - recentRootReferenceGas, intrinsicGas, stateGasLimit, standardGasLimit, diff --git a/src/index.ts b/src/index.ts index 8c389d4..aa013af 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,31 @@ export * from './errors.js' export * from './types.js' +export { + type DirectFrameExecution, + type FrameAccount, + type FrameAccountImplementation, + type FrameCall, + type GetFrameNonceParameters, + type GetValidationDataParameters, +} from './accounts/types.js' +export { + type ToFrameAccountParameters, + type ToFrameAccountReturnType, + toFrameAccount, +} from './accounts/toFrameAccount.js' +export { + type EoaFrameAccountImplementation, + type EoaFrameOwner, + type ToEoaFrameAccountParameters, + type ToEoaFrameAccountReturnType, + toEoaFrameAccount, +} from './accounts/toEoaFrameAccount.js' +export { + type PrepareFrameLimits, + type PrepareFrameTransactionOptions, + prepareFrameTransaction, +} from './prepareFrameTransaction.js' +export { signFrameTransaction } from './signFrameTransaction.js' export { rlpUint, parseRlpUint, byteLength } from './rlp.js' export { encodeFrameTx, @@ -7,8 +33,6 @@ export { decodeFrameTx, validateFrameTx, MAX_FRAMES, - MAX_NONCE_KEYS, - MAX_RECENT_ROOT_REFERENCES, MAX_BLOBS_PER_TX, EXPIRY_VERIFIER, } from './envelope.js' @@ -16,7 +40,7 @@ export { frameTxSigHash } from './sighash.js' export { SECP256K1_N, SECP256R1_N, - type FrameAccount, + type FrameSigner, assertCanonicalSignature, assertValidFrameTx, recoverFrameSigner, @@ -28,24 +52,16 @@ export { FRAME_TX_PER_FRAME_COST, FRAME_TX_VALUE_COST, GAS_PER_BLOB, - RECENT_ROOT_REFERENCE_ADDRESS_GAS, - RECENT_ROOT_REFERENCE_GAS, SIG_VERIFY_COST, STANDARD_TOKEN_COST, TOTAL_COST_FLOOR_PER_TOKEN, type FrameGas, frameTxGas, frameTxMaxCost, - nonceCalldata, - recentRootCalldata, } from './gas.js' export { - HEAD_KEYED_NONCE_STATE_GAS, - HEAD_RECENT_ROOT_VERIFIER, - HEAD_REFERENCE_BYTES, type GasDivergence, compareRuleSets, - toHeadShape, } from './divergence.js' export { type FrameReceipt, diff --git a/src/prepareFrameTransaction.ts b/src/prepareFrameTransaction.ts new file mode 100644 index 0000000..4cbe3f9 --- /dev/null +++ b/src/prepareFrameTransaction.ts @@ -0,0 +1,126 @@ +import type { BlockTag, Chain, Hex } from 'viem' +import { MAX_FRAMES } from './envelope.js' +import { FrameEncodeError } from './errors.js' +import type { FrameAccount, FrameAccountImplementation, FrameCall } from './accounts/types.js' +import type { FrameLimits, FrameTransaction } from './types.js' + +export type PrepareFrameLimits = { + /** Limits for the leading VERIFY frame. */ + validation: FrameLimits + /** One limit entry for each call, in the same order as `calls`. */ + calls: readonly FrameLimits[] +} + +export type PrepareFrameTransactionOptions = { + /** State used for nonce and fee reads. */ + blockTag?: BlockTag | undefined +} + +type RpcBlock = { + baseFeePerGas?: Hex | null | undefined +} + +function assertLimits(limits: FrameLimits, label: string): void { + if (limits.execution < 0n) + throw new FrameEncodeError(`${label}.execution must not be negative`) + if (limits.state < 0n) + throw new FrameEncodeError(`${label}.state must not be negative`) +} + +async function getFees( + account: FrameAccount, + blockTag: BlockTag, +): Promise<{ maxPriorityFeePerGas: bigint; maxFeePerGas: bigint }> { + const [priorityHex, block, gasPriceHex] = await Promise.all([ + account.client.request({ method: 'eth_maxPriorityFeePerGas' }), + account.client.request({ + method: 'eth_getBlockByNumber', + params: [blockTag, false], + }) as Promise, + account.client.request({ method: 'eth_gasPrice' }), + ]) + + const suggestedPriorityFee = BigInt(priorityHex) + const gasPrice = BigInt(gasPriceHex) + const baseFeePerGas = block?.baseFeePerGas + + if (baseFeePerGas === undefined || baseFeePerGas === null) { + return { + maxPriorityFeePerGas: + suggestedPriorityFee < gasPrice ? suggestedPriorityFee : gasPrice, + maxFeePerGas: gasPrice, + } + } + + return { + maxPriorityFeePerGas: suggestedPriorityFee, + maxFeePerGas: BigInt(baseFeePerGas) * 2n + suggestedPriorityFee, + } +} + +/** + * Build an unsigned direct-execution frame transaction. + * + * The returned transaction contains one leading VERIFY frame followed by one + * SENDER frame per call. Pass it to `account.signFrameTransaction` to produce + * the transaction that can be validated and encoded. + */ +export async function prepareFrameTransaction< + implementation extends FrameAccountImplementation, +>( + account: FrameAccount, + calls: readonly FrameCall[], + frameLimits: PrepareFrameLimits, + options: PrepareFrameTransactionOptions = {}, +): Promise { + if (calls.length === 0) + throw new FrameEncodeError('prepareFrameTransaction requires at least one call') + if (calls.length + 1 > MAX_FRAMES) + throw new FrameEncodeError( + `prepareFrameTransaction supports at most ${MAX_FRAMES - 1} calls because the validation frame also counts toward the ${MAX_FRAMES}-frame limit`, + ) + if (frameLimits.calls.length !== calls.length) + throw new FrameEncodeError( + `frameLimits.calls must contain one entry per call: expected ${calls.length}, got ${frameLimits.calls.length}`, + ) + + assertLimits(frameLimits.validation, 'frameLimits.validation') + for (const [index, limits] of frameLimits.calls.entries()) + assertLimits(limits, `frameLimits.calls[${index}]`) + + const blockTag = options.blockTag ?? 'pending' + const [nonce, fees] = await Promise.all([ + account.getNonce({ blockTag }), + getFees(account, blockTag), + ]) + const chainId = BigInt(account.client.chain.id) + const validationData = await account.getValidationData({ calls, chainId, nonce }) + + return { + chainId, + nonce, + sender: account.address, + frames: [ + { + mode: 1, + flags: 0x3, + target: null, + limits: frameLimits.validation, + value: 0n, + data: validationData, + }, + ...calls.map((call, index) => ({ + mode: 2 as const, + flags: 0, + target: call.to, + limits: frameLimits.calls[index]!, + value: call.value, + data: call.data, + })), + ], + signatures: [], + ...fees, + maxFeePerBlobGas: 0n, + blobVersionedHashes: [], + } +} diff --git a/src/rpc.ts b/src/rpc.ts index 8644ab5..86a0d82 100644 --- a/src/rpc.ts +++ b/src/rpc.ts @@ -5,7 +5,6 @@ import type { FrameMode, FrameSignature, FrameTransaction, - RecentRootReference, SigScheme, } from './types.js' @@ -15,8 +14,7 @@ export type RpcFrameTransaction = { /** Present on `eth_getTransactionByHash` and hydrated blocks; absent on hand-written fixtures. */ hash?: Hex chainId: Hex - nonceKeys: readonly Hex[] - nonceSeq: Hex + nonce: Hex sender: Address frames: readonly { mode: Hex @@ -38,7 +36,6 @@ export type RpcFrameTransaction = { maxFeePerGas: Hex maxFeePerBlobGas: Hex blobVersionedHashes: readonly Hex[] - recentRootReferences: readonly { sourceId: Hex; slot: Hex; root: Hex }[] } /** EIP-8141 frame receipt status: 0 failure, 1 success, 2 skipped (atomic-batch failure). */ @@ -127,14 +124,9 @@ export function parseRpcFrameTransaction(json: RpcFrameTransaction): FrameTransa signature: s.signature, })) - const recentRootReferences: RecentRootReference[] = json.recentRootReferences.map( - (r) => ({ sourceId: r.sourceId, slot: BigInt(r.slot), root: r.root }), - ) - return { chainId: BigInt(json.chainId), - nonceKeys: json.nonceKeys.map((k) => BigInt(k)), - nonceSeq: BigInt(json.nonceSeq), + nonce: BigInt(json.nonce), sender: getAddress(json.sender), frames, signatures, @@ -142,7 +134,6 @@ export function parseRpcFrameTransaction(json: RpcFrameTransaction): FrameTransa maxFeePerGas: BigInt(json.maxFeePerGas), maxFeePerBlobGas: BigInt(json.maxFeePerBlobGas), blobVersionedHashes: [...json.blobVersionedHashes], - recentRootReferences, } } diff --git a/src/signFrameTransaction.ts b/src/signFrameTransaction.ts new file mode 100644 index 0000000..c8df940 --- /dev/null +++ b/src/signFrameTransaction.ts @@ -0,0 +1,19 @@ +import { isAddressEqual } from 'viem' +import type { FrameAccount, FrameAccountImplementation } from './accounts/types.js' +import { FrameEncodeError } from './errors.js' +import type { FrameTransaction } from './types.js' + +/** Sign a prepared transaction using its frame account's signing strategy. */ +export async function signFrameTransaction< + implementation extends FrameAccountImplementation, +>( + account: FrameAccount, + transaction: FrameTransaction, +): Promise { + if (!isAddressEqual(transaction.sender, account.address)) + throw new FrameEncodeError( + `transaction sender ${transaction.sender} does not match frame account ${account.address}`, + ) + + return account.signFrameTransaction(transaction) +} diff --git a/src/signatures.ts b/src/signatures.ts index 6171bb2..4c77d90 100644 --- a/src/signatures.ts +++ b/src/signatures.ts @@ -142,7 +142,7 @@ function bareRecoveryId(v: bigint, index: number): bigint { * `signMessage` is deliberately not an accepted substitute: it prefixes its * argument per EIP-191, so it cannot produce a signature over a sig-hash. */ -export type FrameAccount = { +export type FrameSigner = { address: Address sign?: ((parameters: { hash: Hex }) => Promise) | undefined } @@ -150,7 +150,7 @@ export type FrameAccount = { /** * Sign every empty-`msg` SECP256K1 entry over the transaction's sig-hash. * - * Takes either a raw private key or a `FrameAccount` — a hardware wallet, a + * Takes either a raw private key or a `FrameSigner` — a hardware wallet, a * KMS, an HD account, anything that signs a digest for a known address. * * Idempotent: the sig-hash elides empty-`msg` signature bytes, so re-signing an @@ -158,7 +158,7 @@ export type FrameAccount = { */ export async function signFrameTx( tx: FrameTransaction, - signer: Hex | FrameAccount, + signer: Hex | FrameSigner, ): Promise { const account = typeof signer === 'string' ? privateKeyToAccount(signer) : signer if (typeof account.sign !== 'function') diff --git a/src/types.ts b/src/types.ts index a2073d9..c9626cd 100644 --- a/src/types.ts +++ b/src/types.ts @@ -35,19 +35,10 @@ export type FrameSignature = { signature: Hex } -export type RecentRootReference = { - /** 32 bytes. */ - sourceId: Hex - slot: bigint - /** 32 bytes. */ - root: Hex -} - export type FrameTransaction = { chainId: bigint - /** 1..16 entries, strictly increasing; if more than one, the first is non-zero. */ - nonceKeys: bigint[] - nonceSeq: bigint + /** Sender account nonce, encoded as a scalar uint64. */ + nonce: bigint sender: Address frames: Frame[] signatures: FrameSignature[] @@ -55,18 +46,11 @@ export type FrameTransaction = { maxFeePerGas: bigint maxFeePerBlobGas: bigint blobVersionedHashes: Hex[] - recentRootReferences: RecentRootReference[] } /** * Which rule set to price under. - * - 'chain' — ethrex 31b532266, the deployed binary, with its two live divergences. - * - 'pins' — the pinned EIP text: 8141 7d1c8bfb94, 8250 e5cf246ff1, 8272 0231fb05f5. - * - 'head' — current drafts, for anticipating the next re-genesis. Models only - * the EIP-8250 gas change; the EIP-8272 head draft changes the *envelope* - * (recent-root references become a leading VERIFY frame), not just the - * price, so `frameTxGas` refuses rather than guess at a reference-carrying - * transaction under `'head'`. Price one through `compareRuleSets`, which - * routes it via `toHeadShape`, or call that transform directly. + * Kept for API compatibility with the kit's gas helpers. The current frame + * transaction envelope has no keyed-nonce or recent-root extensions. */ export type RuleSet = 'chain' | 'pins' | 'head' diff --git a/test/accounts.test.ts b/test/accounts.test.ts new file mode 100644 index 0000000..cec6557 --- /dev/null +++ b/test/accounts.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, test } from 'vitest' +import { createClient, custom, getAddress } from 'viem' +import { privateKeyToAccount } from 'viem/accounts' +import { mainnet } from 'viem/chains' +import { toFrameAccount } from '../src/accounts/toFrameAccount.js' +import { toEoaFrameAccount } from '../src/accounts/toEoaFrameAccount.js' +import { recoverFrameSigner } from '../src/signatures.js' +import type { FrameTransaction } from '../src/types.js' +import { GOLDEN_TX } from './fixtures/golden.js' + +const OWNER_KEY = `0x${'11'.repeat(32)}` as const + +describe('toFrameAccount', () => { + test('resolves methods and extensions', async () => { + const owner = privateKeyToAccount(OWNER_KEY) + const client = createClient({ + account: owner, + chain: mainnet, + transport: custom({ async request() { throw new Error('unexpected RPC request') } }), + }) + const address = getAddress('0x0000000000000000000000000000000000001234') + const account = await toFrameAccount({ + client, + owner, + execution: { type: 'direct' }, + extend: { implementationName: 'test-account' as const }, + async getAddress() { return address }, + async getNonce() { return 1n }, + async getValidationData({ nonce }) { return nonce === 1n ? '0xabcd' : '0x' }, + async signFrameTransaction(transaction) { return transaction }, + }) + + expect(account.address).toBe(address) + expect(account.type).toBe('frame') + expect(account.implementationName).toBe('test-account') + expect(await account.getNonce()).toBe(1n) + expect(await account.getValidationData({ calls: [], chainId: 1n, nonce: 1n })).toBe('0xabcd') + expect(await account.signFrameTransaction(GOLDEN_TX as FrameTransaction)).toBe(GOLDEN_TX) + }) + + test('resolved fields override extension properties', async () => { + const owner = privateKeyToAccount(OWNER_KEY) + const client = createClient({ + account: owner, + chain: mainnet, + transport: custom({ async request() {} }), + }) + const account = await toFrameAccount({ + client, + owner, + execution: { type: 'direct' }, + extend: { address: 'extension-value', type: 'extension-value' }, + getAddress: async () => owner.address, + getNonce: async () => 0n, + getValidationData: async () => '0x', + signFrameTransaction: async (transaction) => transaction, + }) + + expect(account.address).toBe(owner.address) + expect(account.type).toBe('frame') + }) +}) + +describe('toEoaFrameAccount', () => { + test('uses default-code validation and signs as the EOA', async () => { + const owner = privateKeyToAccount(OWNER_KEY) + const client = createClient({ + account: owner, + chain: mainnet, + transport: custom({ async request() {} }), + }) + const account = await toEoaFrameAccount({ client, owner }) + const unsigned = { ...GOLDEN_TX, sender: owner.address, signatures: [] } + + expect(await account.getValidationData({ calls: [], chainId: 1n, nonce: 0n })).toBe('0x') + const signed = await account.signFrameTransaction(unsigned) + expect(signed.signatures[0]).toMatchObject({ scheme: 1, signer: null, msg: '0x' }) + expect(await recoverFrameSigner(signed, 0)).toBe(owner.address) + }) + + test('reads the pending scalar account nonce', async () => { + const owner = privateKeyToAccount(OWNER_KEY) + const requests: { method: string; params?: unknown }[] = [] + const client = createClient({ + account: owner, + chain: mainnet, + transport: custom({ + async request(request) { + requests.push(request) + return '0x7' + }, + }), + }) + const account = await toEoaFrameAccount({ client, owner }) + + expect(await account.getNonce()).toBe(7n) + expect(requests).toEqual([ + { method: 'eth_getTransactionCount', params: [owner.address, 'pending'] }, + ]) + }) + + test('rejects a transaction whose sender is not the EOA', async () => { + const owner = privateKeyToAccount(OWNER_KEY) + const client = createClient({ + account: owner, + chain: mainnet, + transport: custom({ async request() {} }), + }) + const account = await toEoaFrameAccount({ client, owner }) + await expect(account.signFrameTransaction(GOLDEN_TX)).rejects.toThrow(/does not match EOA/) + }) +}) diff --git a/test/divergence.test.ts b/test/divergence.test.ts index dfcbd51..bebb913 100644 --- a/test/divergence.test.ts +++ b/test/divergence.test.ts @@ -1,164 +1,25 @@ import { describe, expect, test } from 'vitest' -import { size, sliceHex } from 'viem' -import { - HEAD_KEYED_NONCE_STATE_GAS, - HEAD_RECENT_ROOT_VERIFIER, - HEAD_REFERENCE_BYTES, - compareRuleSets, - toHeadShape, -} from '../src/divergence.js' +import { compareRuleSets } from '../src/divergence.js' import { frameTxGas } from '../src/gas.js' import { GOLDEN_TX } from './fixtures/golden.js' -const REF_A = { - sourceId: `0x${'11'.repeat(32)}`, - slot: 0xaf1n, - root: `0x${'22'.repeat(32)}`, -} as const - -const REF_B = { - sourceId: `0x${'33'.repeat(32)}`, - slot: 0xaf6n, - root: `0x${'44'.repeat(32)}`, -} as const - -const TWO_REFERENCE_TX = { ...GOLDEN_TX, recentRootReferences: [REF_A, REF_B] } - -/** A SENDER frame carrying value with no target — the shape the chain overcharges. */ -const TARGETLESS_VALUE_TX = { - ...GOLDEN_TX, - frames: [ - { - mode: 2 as const, - flags: 0, - target: null, - limits: { execution: 21_000n, state: 0n }, - value: 1n, - data: '0x' as const, - }, - ], -} - -describe('compareRuleSets', () => { - test('the golden vector prices identically under chain and pins', () => { +describe('compatibility rule-set aliases', () => { + test('all rule-set names use the current accounting rules', () => { expect(compareRuleSets(GOLDEN_TX, 'chain', 'pins')).toEqual([]) + expect(compareRuleSets(GOLDEN_TX, 'pins', 'head')).toEqual([]) }) - test('a targetless value frame diverges by exactly TX_VALUE_COST', () => { - const divergences = compareRuleSets(TARGETLESS_VALUE_TX, 'chain', 'pins') - const valueCost = divergences.find((d) => d.term === 'valueTransferCost') - expect(valueCost).toBeDefined() - expect(valueCost!.delta).toBe(6_000n) - }) - - test('a self-targeted value frame diverges by exactly TX_VALUE_COST', () => { - const tx = { - ...TARGETLESS_VALUE_TX, - frames: [{ ...TARGETLESS_VALUE_TX.frames[0]!, target: GOLDEN_TX.sender }], - } - const valueCost = compareRuleSets(tx, 'chain', 'pins').find( - (d) => d.term === 'valueTransferCost', - ) - expect(valueCost!.delta).toBe(6_000n) - }) - - test('a self-targeted frame is exempt regardless of address casing', () => { - // Regression guard: getAddress returns EIP-55 mixed case, the fixture is - // lowercase. A case-sensitive comparison charges 6000 here and is wrong. + test('a targetless self-transfer has no value-transfer charge', () => { const tx = { - ...TARGETLESS_VALUE_TX, - sender: '0x000000000000000000000000000000000000ABCD' as const, + ...GOLDEN_TX, frames: [ { - ...TARGETLESS_VALUE_TX.frames[0]!, - target: '0x000000000000000000000000000000000000abcd' as const, + ...GOLDEN_TX.frames[1]!, + target: null, + value: 1n, }, ], } - expect(compareRuleSets(tx, 'chain', 'pins')[0]!.delta).toBe(6_000n) - expect(frameTxGas(tx, 'pins').valueTransferCost).toBe(0n) - }) - - test('a value frame with a third-party target does not diverge', () => { - const tx = { - ...TARGETLESS_VALUE_TX, - frames: [ - { - ...TARGETLESS_VALUE_TX.frames[0]!, - target: '0x0000000000000000000000000000000000009999' as const, - }, - ], - } - expect(compareRuleSets(tx, 'chain', 'pins')).toEqual([]) - }) - - test('the chain overcharges relative to the pins, never the reverse', () => { - expect(frameTxGas(TARGETLESS_VALUE_TX, 'chain').maxGas).toBeGreaterThan( - frameTxGas(TARGETLESS_VALUE_TX, 'pins').maxGas, - ) - }) - - test("'pins' and 'head' never diverge on intrinsic gas", () => { - expect(compareRuleSets(TARGETLESS_VALUE_TX, 'pins', 'head')).toEqual([]) - }) -}) - -describe('toHeadShape', () => { - test('leaves a transaction that carries no reference untouched', () => { - expect(toHeadShape(GOLDEN_TX)).toBe(GOLDEN_TX) - }) - - test('empties the envelope field and prepends one VERIFY frame', () => { - const head = toHeadShape(TWO_REFERENCE_TX) - expect(head.recentRootReferences).toEqual([]) - expect(head.frames.length).toBe(GOLDEN_TX.frames.length + 1) - expect(head.frames.slice(1)).toEqual(GOLDEN_TX.frames) - }) - - // upstream eip-8272.md @ 824cbc0b0, §"Recent root verifier frame": the shape - // is normative — mode VERIFY, target RECENT_ROOT_ADDRESS, flags 0, value 0, - // limits.state 0 — and the data is n tuples with no selector or length prefix. - test('the synthetic frame matches the EIP-8272 recent-root-verifier-frame shape', () => { - const verify = toHeadShape(TWO_REFERENCE_TX).frames[0]! - expect(verify.mode).toBe(1) // VERIFY - expect(verify.target).toBe(HEAD_RECENT_ROOT_VERIFIER) - expect(verify.flags).toBe(0) - expect(verify.value).toBe(0n) - expect(verify.limits.state).toBe(0n) - // RECENT_ROOT_TUPLE_BYTES <= len(data), len(data) % RECENT_ROOT_TUPLE_BYTES == 0 - expect(size(verify.data)).toBeGreaterThanOrEqual(HEAD_REFERENCE_BYTES) - expect(size(verify.data) % HEAD_REFERENCE_BYTES).toBe(0) - }) - - // limits.execution is the one field the spec does NOT pin — it falls out of - // the STATICCALL and one SLOAD per tuple — so zero is a deliberate floor. - test('the synthetic frame claims no execution budget: a floor, not a figure', () => { - expect(toHeadShape(TWO_REFERENCE_TX).frames[0]!.limits.execution).toBe(0n) - }) - - test('both references pack into one frame, 72 bytes each', () => { - const data = toHeadShape(TWO_REFERENCE_TX).frames[0]!.data - expect(size(data)).toBe(2 * HEAD_REFERENCE_BYTES) - }) - - // eip-8272.md §"Validation operation": source_id: bytes32, slot: uint64_be, - // root: bytes32 — concatenated, big-endian slot, in that order. - test('each reference packs as source_id || slot || root', () => { - const data = toHeadShape(TWO_REFERENCE_TX).frames[0]!.data - for (const [i, ref] of [REF_A, REF_B].entries()) { - const at = i * HEAD_REFERENCE_BYTES - expect(sliceHex(data, at, at + 32)).toBe(ref.sourceId) - expect(BigInt(sliceHex(data, at + 32, at + 40))).toBe(ref.slot) - expect(sliceHex(data, at + 40, at + 72)).toBe(ref.root) - } - }) -}) - -describe('the head draft', () => { - test('publishes the keyed-nonce state-gas figure', () => { - // EIP-8250 moved the first use of a keyed nonce from 20,000 execution gas to - // 97,920 state gas. Two fresh keys therefore need 195,840 of limits.state. - expect(HEAD_KEYED_NONCE_STATE_GAS).toBe(97_920n) - expect(HEAD_KEYED_NONCE_STATE_GAS * 2n).toBe(195_840n) + expect(frameTxGas(tx).valueTransferCost).toBe(0n) }) }) diff --git a/test/envelope.decode.test.ts b/test/envelope.decode.test.ts index 53b7160..f12d83a 100644 --- a/test/envelope.decode.test.ts +++ b/test/envelope.decode.test.ts @@ -55,22 +55,22 @@ describe('decodeFrameTx: FrameDecodeError.offset', () => { }) test('a non-canonical scalar points at the offending byte', () => { - // nonceSeq 7 written long-form as `81 07`: chainId `01` at 3, nonceKeys - // `c1 80` at 4-5, so the bad `81` byte sits at offset 6. - const longFormNonceSeq = GOLDEN_RLP.replace('c18007', 'c1808107').replace( + // nonce 7 written long-form as `81 07`: chainId is at byte 3, so the bad + // `81` byte sits at offset 4. + const longFormNonce = GOLDEN_RLP.replace('0107', '018107').replace( '0x06f8b3', '0x06f8b4', ) as `0x${string}` - expect(offsetOf(longFormNonceSeq)).toBe(6) + expect(offsetOf(longFormNonce)).toBe(4) }) test('a non-minimal scalar field points at the field', () => { - // nonceSeq 7 written as the two-byte string `82 00 07`. - const leadingZero = GOLDEN_RLP.replace('c18007', 'c180820007').replace( + // nonce 7 written as the two-byte string `82 00 07`. + const leadingZero = GOLDEN_RLP.replace('0107', '01820007').replace( '0x06f8b3', '0x06f8b5', ) as `0x${string}` - expect(offsetOf(leadingZero)).toBe(6) + expect(offsetOf(leadingZero)).toBe(4) }) }) @@ -95,38 +95,38 @@ describe('decodeFrameTx: malformed bodies stay typed', () => { }) describe('decodeFrameTx: non-canonical RLP', () => { - // `nonceSeq` is 7, canonically the single byte 0x07. Written long-form as + // `nonce` is 7, canonically the single byte 0x07. Written long-form as // 0x81 0x07 it is one byte longer, so the outer list header grows from // 0xf8 0xb3 to 0xf8 0xb4. viem's `fromRlp` would accept the long form and // return 7; ethrex's decoder rejects it ("the 0x81 0x01 form is now // rejected"), and so does `walkRlp` — decoding it here would otherwise hand // back a transaction whose bytes the chain will not take. - const LONG_FORM_NONCE_SEQ = GOLDEN_RLP.replace('c18007', 'c1808107').replace( + const LONG_FORM_NONCE = GOLDEN_RLP.replace('0107', '018107').replace( '0x06f8b3', '0x06f8b4', ) test('the mutation is a real one', () => { - expect(LONG_FORM_NONCE_SEQ).not.toBe(GOLDEN_RLP) - expect(LONG_FORM_NONCE_SEQ.length).toBe(GOLDEN_RLP.length + 2) + expect(LONG_FORM_NONCE).not.toBe(GOLDEN_RLP) + expect(LONG_FORM_NONCE.length).toBe(GOLDEN_RLP.length + 2) }) test('rejects a long-form encoding of a single-byte scalar', () => { - expect(() => decodeFrameTx(LONG_FORM_NONCE_SEQ as `0x${string}`)).toThrow( + expect(() => decodeFrameTx(LONG_FORM_NONCE as `0x${string}`)).toThrow( FrameDecodeError, ) - expect(() => decodeFrameTx(LONG_FORM_NONCE_SEQ as `0x${string}`)).toThrow( + expect(() => decodeFrameTx(LONG_FORM_NONCE as `0x${string}`)).toThrow( /non-canonical/, ) }) test('rejects a non-minimal scalar (leading zero byte) as a decode error', () => { - // nonceSeq 7 written as the two-byte string 0x00 0x07: `82 00 07` replaces + // nonce 7 written as the two-byte string 0x00 0x07: `82 00 07` replaces // `07`, and the outer list grows by two. `walkRlp` returns the bytes // verbatim (a 2-byte string is well-formed RLP), `parseRlpUint` rejects the // leading zero, and the caller must see that as a FrameDecodeError like // every other malformed-body case, not the internal FrameRlpError. - const leadingZero = GOLDEN_RLP.replace('c18007', 'c180820007').replace( + const leadingZero = GOLDEN_RLP.replace('0107', '01820007').replace( '0x06f8b3', '0x06f8b5', ) as `0x${string}` diff --git a/test/envelope.encode.test.ts b/test/envelope.encode.test.ts index bee2957..a85b90b 100644 --- a/test/envelope.encode.test.ts +++ b/test/envelope.encode.test.ts @@ -7,28 +7,23 @@ describe('encodeFrameTx', () => { expect(encodeFrameTx(GOLDEN_TX)).toBe(GOLDEN_RLP) }) - test('encodes nonceSeq zero as empty string, not 0x00', () => { - const encoded = encodeFrameTx({ ...GOLDEN_TX, nonceSeq: 0n }) + test('encodes nonce zero as an empty RLP string, not 0x00', () => { + const encoded = encodeFrameTx({ ...GOLDEN_TX, nonce: 0n }) expect(encoded).not.toBe(GOLDEN_RLP) - // nonceSeq: 7 encodes as 07, nonceSeq: 0 encodes as 80 (empty string in RLP) - // Sequence c180 (nonceKeys) should be followed by 80 (nonceSeq zero) - // then 94 (sender), instead of 07 - expect(encoded).toContain('c1808094') + expect(encoded).toContain('018094') }) test('a targetless frame encodes an empty target, not 20 zero bytes', () => { const encoded = encodeFrameTx(GOLDEN_TX) - // frame 1 is `cc 01 03 80 c4825208 80 80 821122`: mode, flags, empty target - expect(encoded).toContain('cc010380c4825208') + expect(encoded).toContain('cf010380c7825208831e8480') }) test('encodeFrameTxBody is the wire encoding minus the 0x06 type byte', () => { expect(encodeFrameTx(GOLDEN_TX)).toBe(`0x06${encodeFrameTxBody(GOLDEN_TX).slice(2)}`) }) - test('limits always encode as a two-element list, even when state is zero', () => { - // frame 1 limits are { execution: 0x5208, state: 0 } -> c4 (825208)(80) - expect(encodeFrameTx(GOLDEN_TX)).toContain('c482520880') + test('limits always encode as a two-element list', () => { + expect(encodeFrameTx(GOLDEN_TX)).toContain('c7825208831e8480') }) test('the fees list always has three entries, even when maxFeePerBlobGas is zero', () => { @@ -36,8 +31,8 @@ describe('encodeFrameTx', () => { expect(encodeFrameTx(GOLDEN_TX)).toContain('cc843b9aca008506fc23ac0080') }) - test('an empty blob list and an empty reference list each encode as 0xc0', () => { - expect(encodeFrameTx(GOLDEN_TX).endsWith('c0c0')).toBe(true) + test('an empty blob list is the final 0xc0 field', () => { + expect(encodeFrameTx(GOLDEN_TX).endsWith('c0')).toBe(true) }) }) diff --git a/test/envelope.validate.test.ts b/test/envelope.validate.test.ts index 2adc8ce..cdf7ea9 100644 --- a/test/envelope.validate.test.ts +++ b/test/envelope.validate.test.ts @@ -60,28 +60,8 @@ describe('validateFrameTx', () => { expect(() => validateFrameTx(tx)).toThrow(/reserved/) }) - test('rejects an empty nonceKeys list', () => { - expect(() => validateFrameTx({ ...GOLDEN_TX, nonceKeys: [] })).toThrow(/between 1 and 16/) - }) - - test('rejects non-increasing nonce keys', () => { - expect(() => validateFrameTx({ ...GOLDEN_TX, nonceKeys: [2n, 2n] })).toThrow( - /strictly increasing/, - ) - }) - - test('rejects a leading zero key when there is more than one', () => { - expect(() => validateFrameTx({ ...GOLDEN_TX, nonceKeys: [0n, 1n] })).toThrow( - /first nonce key/, - ) - }) - - test('accepts a lone zero key', () => { - expect(() => validateFrameTx({ ...GOLDEN_TX, nonceKeys: [0n] })).not.toThrow() - }) - - test('rejects nonceSeq at 2**64 - 1', () => { - expect(() => validateFrameTx({ ...GOLDEN_TX, nonceSeq: 2n ** 64n - 1n })).toThrow(/nonceSeq/) + test('rejects nonce at 2**64 - 1', () => { + expect(() => validateFrameTx({ ...GOLDEN_TX, nonce: 2n ** 64n - 1n })).toThrow(/nonce/) }) test('rejects more than 64 frames', () => { @@ -173,55 +153,18 @@ describe('validateFrameTx: single-byte and 32-byte wire fields', () => { expect(() => validateFrameTx(tx)).toThrow(/flags.*one byte/) }) - // `source_id` and `root` are H256 in ethrex, decoded through the fixed - // `[u8; 32]` impl, which fails with InvalidLength for any other size. - test('rejects a recent-root sourceId that is not 32 bytes', () => { - const tx = { - ...GOLDEN_TX, - recentRootReferences: [ - { sourceId: `0x${'11'.repeat(31)}` as const, slot: 1n, root: `0x${'22'.repeat(32)}` as const }, - ], - } - expect(() => validateFrameTx(tx)).toThrow(/sourceId must be 32 bytes/) - }) - - test('rejects a recent-root root that is not 32 bytes', () => { - const tx = { - ...GOLDEN_TX, - recentRootReferences: [ - { sourceId: `0x${'11'.repeat(32)}` as const, slot: 1n, root: `0x${'22'.repeat(33)}` as const }, - ], - } - expect(() => validateFrameTx(tx)).toThrow(/root must be 32 bytes/) - }) - - test('accepts a well-formed recent-root reference', () => { - const tx = { - ...GOLDEN_TX, - recentRootReferences: [ - { sourceId: `0x${'11'.repeat(32)}` as const, slot: 1n, root: `0x${'22'.repeat(32)}` as const }, - ], - } - expect(() => validateFrameTx(tx)).not.toThrow() - }) }) /** * ethrex's `FrameTransaction` decodes each numeric field at a fixed width — - * `chain_id`, `nonce_seq`, `max_priority_fee_per_gas`, `max_fee_per_gas` and - * `RecentRootReference::slot` as u64; `max_fee_per_blob_gas`, `nonce_keys[]` - * and `Frame::value` as U256 — and `static_left_pad` returns `InvalidLength` + * `chain_id` and `nonce` as u64; all three fees and `Frame::value` as U256. + * `static_left_pad` returns `InvalidLength` * for anything wider. A wider value encodes to well-formed RLP here and then * cannot be decoded by the node at all, so it has to be caught on this side. */ describe('validateFrameTx: numeric field widths', () => { const U64_MAX = 2n ** 64n - 1n const U256_MAX = 2n ** 256n - 1n - const REF = { - sourceId: `0x${'11'.repeat(32)}`, - root: `0x${'22'.repeat(32)}`, - } as const - test('accepts chainId at 2**64 - 1', () => { expect(() => validateFrameTx({ ...GOLDEN_TX, chainId: U64_MAX })).not.toThrow() }) @@ -232,47 +175,25 @@ describe('validateFrameTx: numeric field widths', () => { ) }) - test('accepts maxPriorityFeePerGas at 2**64 - 1', () => { + test('accepts maxPriorityFeePerGas at 2**256 - 1', () => { expect(() => - validateFrameTx({ ...GOLDEN_TX, maxPriorityFeePerGas: U64_MAX }), + validateFrameTx({ ...GOLDEN_TX, maxPriorityFeePerGas: U256_MAX }), ).not.toThrow() }) - test('rejects maxPriorityFeePerGas at 2**64', () => { + test('rejects maxPriorityFeePerGas at 2**256', () => { expect(() => - validateFrameTx({ ...GOLDEN_TX, maxPriorityFeePerGas: 2n ** 64n }), - ).toThrow(/maxPriorityFeePerGas must fit in 64 bits/) - }) - - test('accepts maxFeePerGas at 2**64 - 1', () => { - expect(() => validateFrameTx({ ...GOLDEN_TX, maxFeePerGas: U64_MAX })).not.toThrow() - }) - - test('rejects maxFeePerGas at 2**64', () => { - expect(() => validateFrameTx({ ...GOLDEN_TX, maxFeePerGas: 2n ** 64n })).toThrow( - /maxFeePerGas must fit in 64 bits/, - ) - }) - - test('accepts a recent-root slot at 2**64 - 1', () => { - const tx = { ...GOLDEN_TX, recentRootReferences: [{ ...REF, slot: U64_MAX }] } - expect(() => validateFrameTx(tx)).not.toThrow() + validateFrameTx({ ...GOLDEN_TX, maxPriorityFeePerGas: 2n ** 256n }), + ).toThrow(/maxPriorityFeePerGas must fit in 256 bits/) }) - test('rejects a recent-root slot at 2**64', () => { - const tx = { ...GOLDEN_TX, recentRootReferences: [{ ...REF, slot: 2n ** 64n }] } - expect(() => validateFrameTx(tx)).toThrow( - /recentRootReference 0: slot must fit in 64 bits/, - ) + test('accepts maxFeePerGas at 2**256 - 1', () => { + expect(() => validateFrameTx({ ...GOLDEN_TX, maxFeePerGas: U256_MAX })).not.toThrow() }) - test('accepts a nonce key at 2**256 - 1', () => { - expect(() => validateFrameTx({ ...GOLDEN_TX, nonceKeys: [U256_MAX] })).not.toThrow() - }) - - test('rejects a nonce key at 2**256', () => { - expect(() => validateFrameTx({ ...GOLDEN_TX, nonceKeys: [2n ** 256n] })).toThrow( - /nonceKeys\[0\] must fit in 256 bits/, + test('rejects maxFeePerGas at 2**256', () => { + expect(() => validateFrameTx({ ...GOLDEN_TX, maxFeePerGas: 2n ** 256n })).toThrow( + /maxFeePerGas must fit in 256 bits/, ) }) @@ -327,28 +248,6 @@ describe('validateFrameTx: malformed hex fields throw FrameEncodeError', () => { expect(() => validateFrameTx(tx)).toThrow(/signature 0: msg/) }) - test('an odd-length recent-root sourceId', () => { - const tx = { - ...GOLDEN_TX, - recentRootReferences: [ - { sourceId: `0x${'11'.repeat(31)}1` as const, slot: 1n, root: `0x${'22'.repeat(32)}` as const }, - ], - } - expect(() => validateFrameTx(tx)).toThrow(FrameEncodeError) - expect(() => validateFrameTx(tx)).toThrow(/recentRootReference 0: sourceId/) - }) - - test('a non-hex recent-root root', () => { - const tx = { - ...GOLDEN_TX, - recentRootReferences: [ - { sourceId: `0x${'11'.repeat(32)}` as const, slot: 1n, root: `0x${'zz'.repeat(32)}` as const }, - ], - } - expect(() => validateFrameTx(tx)).toThrow(FrameEncodeError) - expect(() => validateFrameTx(tx)).toThrow(/recentRootReference 0: root/) - }) - test('an odd-length frame data field', () => { const tx = { ...GOLDEN_TX, diff --git a/test/fixtures/golden.ts b/test/fixtures/golden.ts index 71c0192..5c6492b 100644 --- a/test/fixtures/golden.ts +++ b/test/fixtures/golden.ts @@ -1,8 +1,8 @@ import type { FrameTransaction } from '../../src/types.js' /** Two frames — a targetless VERIFY carrying data, then a SENDER frame with a - * target — one SECP256K1 signature with an empty msg, no state budget on - * either frame. The shape ethrex's `scripts/hegota-testnet/frametx.py` __main__ builds. */ + * target — one SECP256K1 signature with an empty msg and a non-zero state + * budget on the VERIFY frame. This is Ethrex v23's wire-format golden vector. */ /** EIP-55 form of `0x…abcd`. viem's `getAddress` — and therefore `decodeFrameTx` * and `parseRpcFrameTransaction` — returns checksummed addresses, so the fixture * is written checksummed and `toEqual` against decoder output holds without case @@ -12,15 +12,14 @@ const ABCD = '0x000000000000000000000000000000000000ABcD' as const export const GOLDEN_TX: FrameTransaction = { chainId: 1n, - nonceKeys: [0n], - nonceSeq: 7n, + nonce: 7n, sender: ABCD, frames: [ { mode: 1, flags: 3, target: null, - limits: { execution: 0x5208n, state: 0n }, + limits: { execution: 0x5208n, state: 0x1e8480n }, value: 0n, data: '0x1122', }, @@ -45,18 +44,17 @@ export const GOLDEN_TX: FrameTransaction = { maxFeePerGas: 0x6fc23ac00n, maxFeePerBlobGas: 0n, blobVersionedHashes: [], - recentRootReferences: [], } /** Copy VERBATIM from frame_tx_wire_tests.rs:67. Do not reflow or re-wrap: * a hand-wrapped transcription of this string was already caught being * 10 characters short. */ export const GOLDEN_RLP = - '0x06f8b301c1800794000000000000000000000000000000000000abcdeccc010380c48252088080821122de0280940000000000000000000000000000000000001234c4829c40808080f85cf85a0194000000000000000000000000000000000000abcd80b8410101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101cc843b9aca008506fc23ac0080c0c0' as const + '0x06f8b3010794000000000000000000000000000000000000abcdefcf010380c7825208831e848080821122de0280940000000000000000000000000000000000001234c4829c40808080f85cf85a0194000000000000000000000000000000000000abcd80b8410101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101cc843b9aca008506fc23ac0080c0' as const /** From frame_tx_wire_tests.rs:69. */ export const GOLDEN_SIG_HASH = - '0xd4df51143828c0338882dbd10c3308f3569972fe1928a7b5040ee18057920510' as const + '0x2518df13bab80fe6bcc7a7e462dea6d617ad6992d53411ddbaff26a8cbc22341' as const /** The golden transaction as the node would serve it from * `eth_getTransactionByHash`, minus the block fields. Field names and formats @@ -66,11 +64,10 @@ export const GOLDEN_SIG_HASH = export const GOLDEN_RPC_JSON = { type: '0x6', chainId: '0x1', - nonceKeys: ['0x0'], - nonceSeq: '0x7', + nonce: '0x7', sender: '0x000000000000000000000000000000000000abcd', frames: [ - { mode: '0x1', flags: '0x3', to: null, gasLimit: '0x5208', stateLimit: '0x0', + { mode: '0x1', flags: '0x3', to: null, gasLimit: '0x5208', stateLimit: '0x1e8480', value: '0x0', data: '0x1122' }, { mode: '0x2', flags: '0x0', to: '0x0000000000000000000000000000000000001234', gasLimit: '0x9c40', stateLimit: '0x0', value: '0x0', data: '0x' }, @@ -83,5 +80,4 @@ export const GOLDEN_RPC_JSON = { maxFeePerGas: '0x6fc23ac00', maxFeePerBlobGas: '0x0', blobVersionedHashes: [], - recentRootReferences: [], } as const diff --git a/test/gas.test.ts b/test/gas.test.ts index adbe991..9ee91ac 100644 --- a/test/gas.test.ts +++ b/test/gas.test.ts @@ -6,21 +6,19 @@ describe('frameTxGas on the golden vector', () => { const gas = frameTxGas(GOLDEN_TX, 'chain') test('mandatory gas', () => expect(gas.mandatoryGas).toBe(15_750n)) - test('billed byte count', () => expect(gas.billedBytes).toBe(90n)) - test('data cost', () => expect(gas.dataCost).toBe(1_224n)) - test('recent-root reference gas is zero with no references', () => - expect(gas.recentRootReferenceGas).toBe(0n)) - test('intrinsic gas', () => expect(gas.intrinsicGas).toBe(16_974n)) - test('state gas limit', () => expect(gas.stateGasLimit).toBe(0n)) - test('standard gas limit', () => expect(gas.standardGasLimit).toBe(77_974n)) - test('calldata tokens', () => expect(gas.calldataTokens).toBe(360n)) - test('calldata floor total', () => expect(gas.calldataFloorTotal).toBe(21_510n)) - test('max gas takes the standard branch', () => expect(gas.maxGas).toBe(77_974n)) + test('billed byte count', () => expect(gas.billedBytes).toBe(87n)) + test('data cost', () => expect(gas.dataCost).toBe(1_176n)) + test('intrinsic gas', () => expect(gas.intrinsicGas).toBe(16_926n)) + test('state gas limit', () => expect(gas.stateGasLimit).toBe(2_000_000n)) + test('standard gas limit', () => expect(gas.standardGasLimit).toBe(2_077_926n)) + test('calldata tokens', () => expect(gas.calldataTokens).toBe(348n)) + test('calldata floor total', () => expect(gas.calldataFloorTotal).toBe(21_318n)) + test('max gas takes the standard branch', () => expect(gas.maxGas).toBe(2_077_926n)) }) describe('frameTxMaxCost', () => { test('is maxGas * maxFeePerGas with no blobs', () => { - expect(frameTxMaxCost(GOLDEN_TX, 0n, 'chain')).toBe(2_339_220_000_000_000n) + expect(frameTxMaxCost(GOLDEN_TX, 0n, 'chain')).toBe(62_337_780_000_000_000n) }) test('adds the blob term at the base rate', () => { @@ -66,25 +64,6 @@ describe('the calldata floor branch', () => { }) }) -describe('recent-root references', () => { - test('charge 2400 + 2002 per reference and bill their RLP bytes', () => { - const tx = { - ...GOLDEN_TX, - recentRootReferences: [ - { sourceId: `0x${'11'.repeat(32)}` as const, slot: 100n, root: `0x${'22'.repeat(32)}` as const }, - ], - } - const gas = frameTxGas(tx, 'chain') - expect(gas.recentRootReferenceGas).toBe(2_400n + 2_002n) - expect(gas.billedBytes).toBeGreaterThan(90n) - }) - - test('an empty reference list bills no bytes at all', () => { - // recentRootCalldata must be '0x', NOT toRlp([]) === '0xc0' - expect(frameTxGas(GOLDEN_TX, 'chain').billedBytes).toBe(90n) - }) -}) - describe('signature verification cost by scheme', () => { // EIP-8141 Constants table (DESIGN.md §4): ARBITRARY 100, SECP256K1 2800, // P256 6700. Hand-written figures, not read back from SIG_VERIFY_COST. No @@ -131,17 +110,8 @@ describe('signature verification cost by scheme', () => { }) describe('rule sets', () => { - test("'head' prices identically to 'pins' — the head change is execution-time state gas", () => { + test('compatibility rule-set names price identically', () => { + expect(frameTxGas(GOLDEN_TX, 'chain')).toEqual(frameTxGas(GOLDEN_TX, 'pins')) expect(frameTxGas(GOLDEN_TX, 'head')).toEqual(frameTxGas(GOLDEN_TX, 'pins')) }) - - test("'head' throws for a transaction carrying a recent-root reference", () => { - const tx = { - ...GOLDEN_TX, - recentRootReferences: [ - { sourceId: `0x${'11'.repeat(32)}` as const, slot: 100n, root: `0x${'22'.repeat(32)}` as const }, - ], - } - expect(() => frameTxGas(tx, 'head')).toThrow(/no head-shaped equivalent/) - }) }) diff --git a/test/live/simulate.test.ts b/test/live/simulate.test.ts index 23e432a..ed392ab 100644 --- a/test/live/simulate.test.ts +++ b/test/live/simulate.test.ts @@ -1,88 +1,16 @@ +import { createPublicClient, http } from 'viem' import { describe, expect, test } from 'vitest' -import { http, createPublicClient } from 'viem' -import { privateKeyToAccount } from 'viem/accounts' -import { encodeFrameTx } from '../../src/envelope.js' -import { frameTxMaxCost } from '../../src/gas.js' -import { parseRpcFrameTransaction, simulateFrameTransaction } from '../../src/rpc.js' -import { signFrameTx } from '../../src/signatures.js' -import type { FrameTransaction } from '../../src/types.js' -import { loadChainFixtures } from '../helpers/fixtures.js' - -const RPC_URL = 'https://rpc1.privacy.ethrex.xyz' -const CHAIN_ID = 8141n -const GENESIS_HASH = '0x7ca0f7358d127dc4a68983050eb88837a5f384225254d1b009fa87fbcd0f2332' - -// A throwaway key. It holds no funds and never will; simulation does not spend. -const THROWAWAY_KEY = `0x${'42'.repeat(32)}` as const +const RPC_URL = 'https://rpc1.frames.ethrex.xyz' +const CHAIN_ID = 81410 const live = process.env.FRAMES_LIVE === '1' -describe.skipIf(!live)('ethrex_simulateFrameTransaction', () => { +describe.skipIf(!live)('Ethrex frames devnet', () => { const client = createPublicClient({ transport: http(RPC_URL) }) - const account = privateKeyToAccount(THROWAWAY_KEY) - - test('the node reports our chain id and the third genesis', async () => { - expect(BigInt(await client.getChainId())).toBe(CHAIN_ID) - const genesis = await client.getBlock({ blockNumber: 0n }) - expect(genesis.hash).toBe(GENESIS_HASH) - }) - - test('a throwaway-signed SelfVerify transaction is decoded, authenticated and priced', async () => { - const tx: FrameTransaction = { - chainId: CHAIN_ID, - nonceKeys: [0n], - nonceSeq: 0n, - sender: account.address, - frames: [ - { - mode: 1, // VERIFY: the only mode that can open a recognized prefix - flags: 0x3, // APPROVE_EXECUTION | APPROVE_PAYMENT → SelfVerify - target: null, - limits: { execution: 21_000n, state: 0n }, - value: 0n, - data: '0x', - }, - ], - signatures: [{ scheme: 1, signer: null, msg: '0x', signature: '0x' }], - maxPriorityFeePerGas: 1_000_000_000n, - maxFeePerGas: 30_000_000_000n, - maxFeePerBlobGas: 0n, - blobVersionedHashes: [], - recentRootReferences: [], - } - - const signed = await signFrameTx(tx, THROWAWAY_KEY) - const result = await simulateFrameTransaction(client, encodeFrameTx(signed)) - - // maxCost is a pure function of the fields and is present on every path. - // Proves the node computed the same max_gas from our bytes as we did. - expect(result.maxCost).toBe(frameTxMaxCost(signed, 0n, 'chain')) - - // The prefix shape is derived AFTER signature authentication, so a non-null - // shape proves the node decoded our envelope AND accepted our signature. - expect(result.prefixShape).toBe('SelfVerify') - - // A throwaway EOA has no code to call APPROVE, so the prefix cannot pass. - // Observed 2026-09-06: `valid: false`, `violation: "validation prefix frame reverted"`. - expect(result.valid).toBe(false) - expect(result.violation).toMatch(/prefix/) - }) - - test('a captured transaction re-encoded from its JSON is authenticated by the node', async () => { - const fixture = loadChainFixtures()[0] - if (fixture === undefined) return - const tx = parseRpcFrameTransaction(fixture.tx) - const result = await simulateFrameTransaction(client, encodeFrameTx(tx)) - // It cannot be valid any more (its nonce is spent or its root expired), but it - // must get past signature authentication, and the node's maxCost is stable. - expect(result.violation ?? '').not.toMatch(/does not authenticate/) - expect(result.maxCost).toBe(BigInt(fixture.simulate.maxCost)) - }) - test('a malformed envelope is rejected by the node, not silently accepted', async () => { - // Observed: JSON-RPC error -32000 "Invalid params: Error decoding field 'chain_id'". - await expect(simulateFrameTransaction(client, '0x06c0')).rejects.toThrow( - /decoding|Invalid params/, - ) + test('reports the expected chain and an Ethrex client', async () => { + expect(await client.getChainId()).toBe(CHAIN_ID) + const version = await client.request({ method: 'web3_clientVersion' }) + expect(version).toMatch(/^ethrex\//) }) }) diff --git a/test/oracles.test.ts b/test/oracles.test.ts index f634597..acfb2a6 100644 --- a/test/oracles.test.ts +++ b/test/oracles.test.ts @@ -1,151 +1,22 @@ import { describe, expect, test } from 'vitest' -import { keccak256 } from 'viem' import { decodeFrameTx, encodeFrameTx } from '../src/envelope.js' +import { frameTxSigHash } from '../src/sighash.js' import { - FRAME_TX_PER_FRAME_COST, - RECENT_ROOT_REFERENCE_ADDRESS_GAS, - RECENT_ROOT_REFERENCE_GAS, - frameTxGas, - frameTxMaxCost, -} from '../src/gas.js' -import { type GasDivergence, compareRuleSets } from '../src/divergence.js' -import { parseRpcFrameReceipt, parseRpcFrameTransaction } from '../src/rpc.js' -import { recoverFrameSigner, resolveSigner } from '../src/signatures.js' -import { loadChainFixtures } from './helpers/fixtures.js' + GOLDEN_RLP, + GOLDEN_SIG_HASH, + GOLDEN_TX, +} from './fixtures/golden.js' -const fixtures = loadChainFixtures() - -/** - * Every term the head envelope change can move: the dropped reference charge, the - * extra frame, the calldata that moves from `rlp(refs)` into frame data, and the - * totals derived from those. A term outside this set is a finding. - */ -const HEAD_SHAPE_TERMS = new Set([ - 'mandatoryGas', - 'recentRootReferenceGas', - 'billedBytes', - 'dataCost', - 'intrinsicGas', - 'calldataTokens', - 'calldataFloorGas', - 'calldataFloorTotal', - 'standardGasLimit', - 'maxGas', -]) - -describe('captured fixtures', () => { - test('at least one fixture is present', () => { - expect(fixtures.length).toBeGreaterThan(0) - }) - - test('every fixture was captured against the third genesis', () => { - for (const f of fixtures) - expect(f.meta.genesisHash).toBe( - '0x7ca0f7358d127dc4a68983050eb88837a5f384225254d1b009fa87fbcd0f2332', - ) - }) -}) - -describe.each(fixtures)('$name', (fixture) => { - const tx = parseRpcFrameTransaction(fixture.tx) - const raw = encodeFrameTx(tx) - - // Oracle 2: absolute layout. The transaction hash is keccak256 of the canonical - // bytes, so reproducing it from the node's decoded JSON pins every byte of the - // envelope — nesting included. A field-by-field diff of two decoders could not - // see a mis-nesting they both made; the hash can. - test('re-encoding the node JSON reproduces the transaction hash', () => { - expect(keccak256(raw)).toBe(fixture.tx.hash) - }) - - // Oracle 2, decoder side: our decoder over those bytes agrees with the node's - // decoder over the same bytes. - test('decodes to the same transaction the node reports', () => { - expect(decodeFrameTx(raw)).toEqual(tx) - }) - - // The node ran signature authentication over our bytes and got past it, i.e. - // our sig_hash over a REAL signature equals the node's. Recorded at capture. - test('the node authenticated our re-encoding', () => { - expect(fixture.simulate.violation ?? '').not.toMatch(/does not authenticate/) +describe('Ethrex v23 wire oracle', () => { + test('encodes the seven-field transaction byte-for-byte', () => { + expect(encodeFrameTx(GOLDEN_TX)).toBe(GOLDEN_RLP) }) - // Oracle 3: recovery. The signer is often NOT the sender on this chain — the - // shielded pool's spends have the pool as sender and an EOA as signer — so the - // comparison is against the resolved signer, not `sender`. - test('every empty-msg secp256k1 signature recovers to its resolved signer', async () => { - for (const [i, sig] of tx.signatures.entries()) { - if (sig.scheme !== 1 || sig.msg !== '0x') continue - expect(await recoverFrameSigner(tx, i)).toBe(resolveSigner(tx, i)) - } - }) - - // Oracle 3: the receipt parses, one entry per frame, three-valued status intact. - test('the receipt parses with one entry per frame', () => { - const receipt = parseRpcFrameReceipt(fixture.receipt) - expect(receipt.frameReceipts.length).toBe(tx.frames.length) - }) - - // Oracle 3: max gas. The node computed `maxCost` from OUR bytes; 'chain' must - // reproduce it exactly. The blob term needs the block's blob base fee, which - // the fixture does not carry, so blob-carrying transactions are skipped here. - test("'chain' reproduces the node's maxCost", () => { - if (tx.blobVersionedHashes.length > 0) return - expect(frameTxMaxCost(tx, 0n, 'chain')).toBe(BigInt(fixture.simulate.maxCost)) - }) - - // Oracle 3: the receipt reconciles. Observed with a zero delta on every live - // transaction checked: gasUsed = intrinsic + Σ execution + Σ state. Four of - // the five captured fixtures (block 2782, 2787, 2792, 42241) take the - // standard branch; the fifth, 0xe936e39d…25fb1 at block 42086, takes the - // EIP-7623 calldata-floor branch — standard 26246, floored 27382, actual - // receipt gasUsed 27382 — so both arms are exercised on live data. - test('receipt.gasUsed = intrinsic + Σ frame gasUsed + Σ frame stateGasUsed', () => { - const receipt = parseRpcFrameReceipt(fixture.receipt) - const gas = frameTxGas(tx, 'chain') - const execution = receipt.frameReceipts.reduce((acc, f) => acc + f.gasUsed, 0n) - const state = receipt.frameReceipts.reduce((acc, f) => acc + f.stateGasUsed, 0n) - const standard = gas.intrinsicGas + execution + state - const floored = gas.calldataFloorTotal + state - expect(BigInt(fixture.receipt.gasUsed)).toBe(standard > floored ? standard : floored) - }) - - // The divergence survey. Any divergence must be one the ledger explains. - test('chain-vs-pins divergences are only ever valueTransferCost-rooted', () => { - const divergences = compareRuleSets(tx, 'chain', 'pins') - if (divergences.length === 0) return - const root = divergences.find((d) => d.term === 'valueTransferCost') - expect(root, `unexplained divergence in ${fixture.name}: ${JSON.stringify( - divergences.map((d) => d.term), - )}`).toBeDefined() - expect(root!.delta % 6_000n).toBe(0n) - }) - - // The same survey against the head draft. Two of the captured fixtures carry - // recent-root references, the shape `frameTxGas(tx, 'head')` refuses, so this - // runs over `toHeadShape` and is the only place head pricing meets live data. - const refs = tx.recentRootReferences.length - - test('pins-vs-head divergences are rooted in the dropped envelope field', () => { - const divergences = compareRuleSets(tx, 'pins', 'head') - if (refs === 0) { - expect(divergences).toEqual([]) - return - } - - const byTerm = new Map(divergences.map((d) => [d.term, d.delta])) - // The envelope field is gone: 2400 for the address, 2002 per reference. - expect(byTerm.get('recentRootReferenceGas')).toBe( - RECENT_ROOT_REFERENCE_ADDRESS_GAS + BigInt(refs) * RECENT_ROOT_REFERENCE_GAS, - ) - // One frame more than the envelope shape, and no other mandatory term moves. - expect(byTerm.get('mandatoryGas')).toBe(FRAME_TX_PER_FRAME_COST) + test('decodes the exact bytes without a dialect transform', () => { + expect(decodeFrameTx(GOLDEN_RLP)).toEqual(GOLDEN_TX) }) - test('pins-vs-head moves no term outside the two roots', () => { - const unexpected = compareRuleSets(tx, 'pins', 'head') - .map((d) => d.term) - .filter((term) => !HEAD_SHAPE_TERMS.has(term)) - expect(unexpected, `${fixture.name} diverges on an unaccounted term`).toEqual([]) + test('reproduces the canonical signature hash', () => { + expect(frameTxSigHash(GOLDEN_TX)).toBe(GOLDEN_SIG_HASH) }) }) diff --git a/test/prepareFrameTransaction.test.ts b/test/prepareFrameTransaction.test.ts new file mode 100644 index 0000000..5843147 --- /dev/null +++ b/test/prepareFrameTransaction.test.ts @@ -0,0 +1,127 @@ +import { describe, expect, test } from 'vitest' +import { createClient, custom, getAddress } from 'viem' +import { privateKeyToAccount } from 'viem/accounts' +import { mainnet } from 'viem/chains' +import { toEoaFrameAccount } from '../src/accounts/toEoaFrameAccount.js' +import { prepareFrameTransaction } from '../src/prepareFrameTransaction.js' +import { assertValidFrameTx } from '../src/signatures.js' + +const OWNER_KEY = `0x${'11'.repeat(32)}` as const + +function testClient() { + const requests: { method: string; params?: unknown }[] = [] + const owner = privateKeyToAccount(OWNER_KEY) + const client = createClient({ + account: owner, + chain: { ...mainnet, id: 81_410 }, + transport: custom({ + async request(request) { + requests.push(request) + switch (request.method) { + case 'eth_getTransactionCount': return '0x7' + case 'eth_maxPriorityFeePerGas': return '0x3b9aca00' + case 'eth_gasPrice': return '0x77359400' + case 'eth_getBlockByNumber': return { baseFeePerGas: '0x77359400' } + default: throw new Error(`unexpected RPC method ${request.method}`) + } + }, + }), + }) + return { client, owner, requests } +} + +describe('prepareFrameTransaction', () => { + test('builds a VERIFY frame and one SENDER frame per call', async () => { + const { client, owner, requests } = testClient() + const account = await toEoaFrameAccount({ client, owner }) + const first = getAddress('0x0000000000000000000000000000000000001234') + const second = getAddress('0x0000000000000000000000000000000000005678') + + const transaction = await prepareFrameTransaction( + account, + [ + { to: first, value: 1n, data: '0x' }, + { to: second, value: 2n, data: '0x1234' }, + ], + { + validation: { execution: 80_000n, state: 0n }, + calls: [ + { execution: 30_000n, state: 100_000n }, + { execution: 40_000n, state: 200_000n }, + ], + }, + ) + + expect(transaction).toMatchObject({ + chainId: 81_410n, + nonce: 7n, + sender: owner.address, + signatures: [], + maxPriorityFeePerGas: 1_000_000_000n, + maxFeePerGas: 5_000_000_000n, + maxFeePerBlobGas: 0n, + blobVersionedHashes: [], + }) + expect(transaction.frames).toEqual([ + { + mode: 1, + flags: 3, + target: null, + limits: { execution: 80_000n, state: 0n }, + value: 0n, + data: '0x', + }, + { + mode: 2, + flags: 0, + target: first, + limits: { execution: 30_000n, state: 100_000n }, + value: 1n, + data: '0x', + }, + { + mode: 2, + flags: 0, + target: second, + limits: { execution: 40_000n, state: 200_000n }, + value: 2n, + data: '0x1234', + }, + ]) + + const signed = await account.signFrameTransaction(transaction) + expect(() => assertValidFrameTx(signed)).not.toThrow() + expect(requests.some(({ method }) => method === 'eth_chainId')).toBe(false) + }) + + test('requires one call-limit entry per call', async () => { + const { client, owner, requests } = testClient() + const account = await toEoaFrameAccount({ client, owner }) + + await expect( + prepareFrameTransaction( + account, + [{ to: owner.address, value: 0n, data: '0x' }], + { validation: { execution: 1n, state: 0n }, calls: [] }, + ), + ).rejects.toThrow(/one entry per call/) + expect(requests).toEqual([]) + }) + + test('rejects negative frame limits before making RPC requests', async () => { + const { client, owner, requests } = testClient() + const account = await toEoaFrameAccount({ client, owner }) + + await expect( + prepareFrameTransaction( + account, + [{ to: owner.address, value: 0n, data: '0x' }], + { + validation: { execution: 1n, state: 0n }, + calls: [{ execution: -1n, state: 0n }], + }, + ), + ).rejects.toThrow(/execution must not be negative/) + expect(requests).toEqual([]) + }) +}) diff --git a/test/signFrameTransaction.test.ts b/test/signFrameTransaction.test.ts new file mode 100644 index 0000000..8489ace --- /dev/null +++ b/test/signFrameTransaction.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, test, vi } from 'vitest' +import { createClient, custom, getAddress } from 'viem' +import { privateKeyToAccount } from 'viem/accounts' +import { mainnet } from 'viem/chains' +import { toEoaFrameAccount } from '../src/accounts/toEoaFrameAccount.js' +import { signFrameTransaction } from '../src/signFrameTransaction.js' +import { recoverFrameSigner } from '../src/signatures.js' +import { GOLDEN_TX } from './fixtures/golden.js' + +const OWNER_KEY = `0x${'11'.repeat(32)}` as const + +describe('signFrameTransaction', () => { + test('delegates signing to the frame account and returns the signed transaction', async () => { + const owner = privateKeyToAccount(OWNER_KEY) + const client = createClient({ + account: owner, + chain: mainnet, + transport: custom({ async request() {} }), + }) + const account = await toEoaFrameAccount({ client, owner }) + const unsigned = { ...GOLDEN_TX, sender: owner.address, signatures: [] } + const spy = vi.spyOn(account, 'signFrameTransaction') + + const signed = await signFrameTransaction(account, unsigned) + + expect(spy).toHaveBeenCalledOnce() + expect(spy).toHaveBeenCalledWith(unsigned) + expect(await recoverFrameSigner(signed, 0)).toBe(owner.address) + }) + + test('rejects a transaction for a different sender before signing', async () => { + const owner = privateKeyToAccount(OWNER_KEY) + const client = createClient({ + account: owner, + chain: mainnet, + transport: custom({ async request() {} }), + }) + const account = await toEoaFrameAccount({ client, owner }) + const spy = vi.spyOn(account, 'signFrameTransaction') + + await expect( + signFrameTransaction(account, { + ...GOLDEN_TX, + sender: getAddress('0x0000000000000000000000000000000000001234'), + }), + ).rejects.toThrow(/does not match frame account/) + expect(spy).not.toHaveBeenCalled() + }) +}) diff --git a/test/viem.test.ts b/test/viem.test.ts index 3008b54..b0ec1bc 100644 --- a/test/viem.test.ts +++ b/test/viem.test.ts @@ -76,7 +76,7 @@ describe('frameActions', () => { test('estimateFrameGas prices under the requested rule set', () => { const actions = frameActions(stubClient({})) - expect(actions.estimateFrameGas({ transaction: GOLDEN_TX }).maxGas).toBe(77_974n) + expect(actions.estimateFrameGas({ transaction: GOLDEN_TX }).maxGas).toBe(2_077_926n) }) test('composes with client.extend on a real viem client', () => { @@ -87,7 +87,7 @@ describe('frameActions', () => { frameActions, ) expect(typeof client.getFrameTransaction).toBe('function') - expect(client.estimateFrameGas({ transaction: GOLDEN_TX }).maxGas).toBe(77_974n) + expect(client.estimateFrameGas({ transaction: GOLDEN_TX }).maxGas).toBe(2_077_926n) }) test('waitForFrameTransactionReceipt polls until the receipt is present', async () => { From c2268f8094c5f843b7482f865e22eb4406cd137a Mon Sep 17 00:00:00 2001 From: nikhil kumar Date: Mon, 21 Sep 2026 20:50:15 +0530 Subject: [PATCH 2/8] fix(rpc): read stateGasLimit from frame responses --- src/rpc.ts | 4 ++-- test/fixtures/golden.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/rpc.ts b/src/rpc.ts index 86a0d82..7674a68 100644 --- a/src/rpc.ts +++ b/src/rpc.ts @@ -22,7 +22,7 @@ export type RpcFrameTransaction = { /** The node calls this `to`, not `target`. */ to: Address | null gasLimit: Hex - stateLimit: Hex + stateGasLimit: Hex value: Hex data: Hex }[] @@ -112,7 +112,7 @@ export function parseRpcFrameTransaction(json: RpcFrameTransaction): FrameTransa mode: toMode(f.mode), flags: Number(BigInt(f.flags)), target: f.to === null ? null : getAddress(f.to), - limits: { execution: BigInt(f.gasLimit), state: BigInt(f.stateLimit) }, + limits: { execution: BigInt(f.gasLimit), state: BigInt(f.stateGasLimit) }, value: BigInt(f.value), data: f.data, })) diff --git a/test/fixtures/golden.ts b/test/fixtures/golden.ts index 5c6492b..a07376e 100644 --- a/test/fixtures/golden.ts +++ b/test/fixtures/golden.ts @@ -67,10 +67,10 @@ export const GOLDEN_RPC_JSON = { nonce: '0x7', sender: '0x000000000000000000000000000000000000abcd', frames: [ - { mode: '0x1', flags: '0x3', to: null, gasLimit: '0x5208', stateLimit: '0x1e8480', + { mode: '0x1', flags: '0x3', to: null, gasLimit: '0x5208', stateGasLimit: '0x1e8480', value: '0x0', data: '0x1122' }, { mode: '0x2', flags: '0x0', to: '0x0000000000000000000000000000000000001234', - gasLimit: '0x9c40', stateLimit: '0x0', value: '0x0', data: '0x' }, + gasLimit: '0x9c40', stateGasLimit: '0x0', value: '0x0', data: '0x' }, ], signatures: [ { scheme: '0x1', signer: '0x000000000000000000000000000000000000abcd', msg: '0x', From 9a3b0f34410f5a0c27617ecdcc50ce57e86196e7 Mon Sep 17 00:00:00 2001 From: nikhil kumar Date: Mon, 28 Sep 2026 02:26:56 +0530 Subject: [PATCH 3/8] feat: add frame payer accounts and high-level transaction sending --- README.md | 62 +++++- docs/DESIGN.md | 46 +++-- scripts/send-eth-paymaster.ts | 252 +++++++++++++++++++++++++ scripts/send-frame-transaction.ts | 89 +++++++++ src/accounts/toEoaFrameAccount.ts | 42 +++-- src/accounts/toEoaFramePayerAccount.ts | 101 ++++++++++ src/accounts/toFramePayerAccount.ts | 31 +++ src/accounts/types.ts | 65 ++++++- src/index.ts | 27 ++- src/prepareFrameTransaction.ts | 58 +++++- src/sendFrameTransaction.ts | 81 ++++++++ src/signFrameTransaction.ts | 26 ++- src/signatures.ts | 48 ++++- test/accounts.test.ts | 93 +++++++++ test/prepareFrameTransaction.test.ts | 155 ++++++++++++++- test/sendFrameTransaction.test.ts | 116 ++++++++++++ test/signFrameTransaction.test.ts | 40 ++++ 17 files changed, 1288 insertions(+), 44 deletions(-) create mode 100644 scripts/send-eth-paymaster.ts create mode 100644 scripts/send-frame-transaction.ts create mode 100644 src/accounts/toEoaFramePayerAccount.ts create mode 100644 src/accounts/toFramePayerAccount.ts create mode 100644 src/sendFrameTransaction.ts create mode 100644 test/sendFrameTransaction.test.ts diff --git a/README.md b/README.md index 68a679a..45bcea5 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,39 @@ const tx = await client.getFrameTransaction({ hash }) const receipt = await client.getFrameTransactionReceipt({ hash }) ``` +For the common build-sign-send path, use the standalone high-level action. `value`, `data`, +nonce selection, and fee reads have defaults. Frame limits are mandatory because the RPC +cannot currently estimate execution and state gas separately: + +```ts +import { sendFrameTransaction } from '@jaw.id/frametx-kit' + +const hash = await sendFrameTransaction(account, [ + { to: recipient, value: 1n }, +], { + limits: { + validation: { execution: 30_000n, state: 0n }, + calls: [{ execution: 40_000n, state: 200_000n }], + }, +}) +``` + +There must be one call-limit entry per call. A payer account is prepared and signed +automatically when supplied, and its limits are also mandatory: + +```ts +const hash = await sendFrameTransaction(account, calls, { + limits: { + validation: { execution: 25_000n, state: 0n }, + calls: [{ execution: 150_000n, state: 250_000n }], + }, + paymaster: { + account: payer, + limits: { execution: 25_000n, state: 200_000n }, + }, +}) +``` + Building a transaction? Call `assertValidFrameTx(tx)` before `encodeFrameTx(tx)`. The encoder itself does not validate, because `sig_hash` is defined over a re-encoding and a validating encoder would reject the live chain data this library is meant to survey. @@ -71,8 +104,8 @@ cannot sign a raw digest at all — both are refused with an error rather than p transaction the chain silently rejects. P256 and ARBITRARY entries are left untouched; build those signatures yourself and let -`assertValidFrameTx` check them. `signFrameTx` also handles one signer at a time, so a -transaction with entries for two different signers needs the bytes assembled by hand. +`assertValidFrameTx` check them. The low-level `signFrameTx` handles one signer at a time; +`signFrameTransaction` coordinates a sender and an optional `FramePayerAccount`. Sending walks the strict path for you — `assertValidFrameTx`, `encodeFrameTx`, `eth_sendRawTransaction` — and checks that the hash the node returns is `keccak256` of the @@ -90,6 +123,31 @@ code-less EOA gets that from the protocol's default code, which `toEoaFrameAccou anything else needs its own validating contract. Dry-run with `client.simulateFrameTransaction({ raw })` before spending. +To use a separate codeless EOA payer, resolve it from a raw-digest-capable account and pass +it through preparation and signing: + +```ts +const payer = await toEoaFramePayerAccount({ + owner: privateKeyToAccount(payerPrivateKey), +}) + +const transaction = await prepareFrameTransaction(account, calls, limits, { + paymaster: { + account: payer, + limits: { execution: 60_000n, state: 200_000n }, + }, +}) + +const signed = await signFrameTransaction(account, transaction, { payer }) +``` + +This changes the validation prefix from `self_verify` to `only_verify -> pay`. The +sender signs outer signature index `0`; the EOA payer signs the protocol-reserved payment +signature at index `1`. Both entries are installed during preparation, before either +signature is produced, so both signatures commit to the same transaction hash. Custom +contract payers can be defined with `toFramePayerAccount` to provide their PAY calldata, +signature entries, and signing behavior. + ## Nonces are keyed A transaction carries `nonceKeys` and one `nonceSeq` (EIP-8250), not a scalar `nonce`. diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 9f36d7e..c913158 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -13,8 +13,9 @@ commit of [`lambdaclass/ethrex`](https://github.com/lambdaclass/ethrex/tree/bdfc A TypeScript client for frame transactions: build, validate, encode, decode, hash, sign, price, simulate, broadcast, and read them back with their frame receipts. It ships a small -account abstraction (`toFrameAccount`, `toEoaFrameAccount`), `prepareFrameTransaction`, -and a viem extension (`client.extend(frameActions)`). It is not a fork of viem core. +account abstraction (`toFrameAccount`, `toEoaFrameAccount`, `toFramePayerAccount`, +`toEoaFramePayerAccount`), `prepareFrameTransaction`, and a viem extension +(`client.extend(frameActions)`). It is not a fork of viem core. Not supported: @@ -138,19 +139,40 @@ from a sender that does not exist yet. These are budgeting figures for choosing A `FrameAccountImplementation` supplies `getAddress()`, `getNonce({ key?, blockTag? })` (the current sequence of one nonce key), `getValidationData({ calls, chainId, nonceKeys, -nonceSeq })`, `signFrameTransaction(tx)` and an execution strategy; `toFrameAccount` -resolves it into a `FrameAccount`. +nonceSeq })`, `getSignatureEntries(tx)`, `signFrameTransaction(tx)` and an execution +strategy; `toFrameAccount` resolves it into a `FrameAccount`. `toEoaFrameAccount` targets a code-less EOA through the protocol's default code: key `0` from `eth_getTransactionCount`, other keys from `NONCE_MANAGER` via `eth_getStorageAt`, empty validation data, and one empty-`msg`, empty-`signer` SECP256K1 entry. -`prepareFrameTransaction(account, calls, limits, { nonceKeys?, blockTag? })` builds one -VERIFY frame with scope `0x3` followed by one SENDER frame per call, reads fees from the node -(`2 * baseFee + priorityFee`, or `eth_gasPrice` without a base fee), and defaults to -`nonceKeys: [0n]` at `blockTag: 'pending'`. Selected keys must currently sit at the same -sequence, since one `nonceSeq` is matched against all of them. The caller supplies every -frame's limits. +A `FramePayerAccountImplementation` supplies `getAddress()`, `getPayData(tx)`, +`getSignatureEntries(tx)` and `signFrameTransaction(tx)`; `toFramePayerAccount` resolves +it into a `FramePayerAccount`. `toEoaFramePayerAccount` implements the protocol's codeless +EOA payer path: empty PAY calldata and an empty-`msg` SECP256K1 entry at index `1` whose +explicit signer is the payer. The explicit address is required because an empty signer +resolves to `tx.sender`. + +`prepareFrameTransaction(account, calls, limits, { nonceKeys?, blockTag?, paymaster? })` +builds one SENDER frame per call and reads fees from the node (`2 * baseFee + priorityFee`, +or `eth_gasPrice` without a base fee). Without `paymaster`, the validation prefix is one +`self_verify` frame with scope `0x3`. With `{ account: payer, limits }`, the prefix becomes +`only_verify` with scope `0x2`, followed by a `pay` frame targeting `payer.address` with +scope `0x1`; the payer supplies its calldata and signature metadata. Preparation installs +all sender and payer signature entries before signing because those entries are part of the +transaction signature hash. `signFrameTransaction(account, tx, { payer })` then lets each +account populate only its own entries and performs final strict validation. Preparation +defaults to `nonceKeys: [0n]` at `blockTag: 'pending'`. Selected keys must currently sit at +the same sequence, since one `nonceSeq` is matched against all of them. The caller supplies +every frame's limits. + +`sendFrameTransaction(account, calls, options)` is the high-level composition of +preparation, sender/payer signing, strict encoding and `eth_sendRawTransaction`. A call's +`value` and `data` default to `0n` and `0x`; nonce keys, block tag and fees inherit the +preparation defaults. `options.limits` is mandatory and contains the validation limits plus +one entry per call. When a payer is present, `options.paymaster.limits` is mandatory too. +The library does not invent these budgets because the RPC cannot currently estimate the +execution and state dimensions separately. ## 6. RPC surface @@ -207,11 +229,11 @@ as a backstop. Strict decode is `decodeFrameTx(raw)` followed by `assertValidFra | `rlp` | Minimal scalars, `walkRlp` | `errors` | | `envelope` | `encodeFrameTx`, `decodeFrameTx`, `validateFrameTx` | `rlp`, `errors`, `types` | | `sighash` | `frameTxSigHash` | `envelope` | -| `signatures` | Canonicality, recovery, signer resolution, `signFrameTx`, `assertValidFrameTx` | `sighash`, `envelope` | +| `signatures` | Canonicality, recovery, signer resolution, slot and transaction signing, strict validation | `sighash`, `envelope` | | `gas` | `frameTxGas`, `frameTxMaxCost`, `nonceCalldata` | `rlp`, `types` | | `nonce` | `NONCE_MANAGER`, `keyedNonceSlot`, `getFrameNonceSeq` | `errors` | | `rpc` | Transaction and receipt parsing, simulate, broadcast | `errors`, `types` | -| `accounts`, `prepareFrameTransaction`, `signFrameTransaction` | Frame accounts and transaction preparation | `envelope`, `signatures`, `nonce` | +| `accounts`, `prepareFrameTransaction`, `signFrameTransaction`, `sendFrameTransaction` | Frame accounts and transaction construction | `envelope`, `signatures`, `nonce`, `rpc` | | `viem` | `frameActions`, no wire logic of its own | `envelope`, `signatures`, `rpc`, `gas` | Nothing imports upward. `gas` does not import `envelope`, so the gas model stays diff --git a/scripts/send-eth-paymaster.ts b/scripts/send-eth-paymaster.ts new file mode 100644 index 0000000..c33438a --- /dev/null +++ b/scripts/send-eth-paymaster.ts @@ -0,0 +1,252 @@ +/** + * Send native ETH from a code-less EOA while a second code-less EOA pays gas. + * + * Required: + * PRIVATE_KEY=0x... PAYMASTER_PRIVATE_KEY=0x... RECIPIENT=0x... \ + * bun run scripts/send-eth-paymaster.ts + * + * Optional: + * AMOUNT_ETH=0.1 + * RPC_URL=https://rpc1.privacy.ethrex.xyz + * DRY_RUN=1 simulate only; do not broadcast + * + * The transaction is always simulated with `ethrex_simulateFrameTransaction` + * first, and is not broadcast unless the node reports it valid. + */ +import { + createPublicClient, + formatEther, + getAddress, + http, + isAddressEqual, + keccak256, + parseEther, + type Address, + type Hex, +} from 'viem' +import { privateKeyToAccount } from 'viem/accounts' +import { + assertValidFrameTx, + encodeFrameTx, + frameTxGas, + frameTxMaxCost, + hegotaTestnet, + parseRpcFrameReceipt, + prepareFrameTransaction, + simulateFrameTransaction, + signFrameTransaction, + toEoaFrameAccount, + toEoaFramePayerAccount, + type FrameRpcClient, + type RpcFrameReceiptJson, +} from '../src/index.js' + +const RECEIPT_TIMEOUT_MS = 120_000 + +type BalanceSnapshot = { + sender: bigint + payer: bigint + recipient: bigint +} + +function requiredEnv(name: string): string { + const value = process.env[name] + if (!value) throw new Error(`${name} is required`) + return value +} + +function privateKeyFromEnv(name: string): Hex { + const value = requiredEnv(name) + if (!/^0x[0-9a-fA-F]{64}$/.test(value)) + throw new Error(`${name} must be a 32-byte 0x-prefixed hex value`) + return value as Hex +} + +function formatSignedEther(value: bigint): string { + const sign = value > 0n ? '+' : '' + return `${sign}${formatEther(value)} ETH` +} + +function printBalanceChanges( + before: BalanceSnapshot, + after: BalanceSnapshot, + amount: bigint, +): void { + const senderDelta = after.sender - before.sender + const payerDelta = after.payer - before.payer + const recipientDelta = after.recipient - before.recipient + + console.log('\nbalance changes:') + console.log( + ` sender: ${formatEther(before.sender)} -> ${formatEther(after.sender)} ETH (${formatSignedEther(senderDelta)})`, + ) + console.log( + ` recipient: ${formatEther(before.recipient)} -> ${formatEther(after.recipient)} ETH (${formatSignedEther(recipientDelta)})`, + ) + console.log( + ` payer: ${formatEther(before.payer)} -> ${formatEther(after.payer)} ETH (${formatSignedEther(payerDelta)})`, + ) + + console.log('\ninterpretation:') + console.log(` requested transfer: ${formatEther(amount)} ETH`) + console.log(` sender transfer variance: ${formatSignedEther(senderDelta + amount)}`) + console.log(` recipient variance: ${formatSignedEther(recipientDelta - amount)}`) + console.log(` payer net gas cost: ${formatEther(-payerDelta)} ETH`) + console.log( + ` tracked net change: ${formatSignedEther(senderDelta + recipientDelta + payerDelta)}`, + ) +} + +async function waitForFrameReceipt( + client: FrameRpcClient, + hash: Hex, +): Promise { + const deadline = Date.now() + RECEIPT_TIMEOUT_MS + + while (Date.now() < deadline) { + const receipt = (await client.request({ + method: 'eth_getTransactionReceipt', + params: [hash], + })) as RpcFrameReceiptJson | null + + if (receipt !== null) return receipt + await new Promise((resolve) => setTimeout(resolve, 1_000)) + } + + throw new Error( + `transaction ${hash} was not mined within ${RECEIPT_TIMEOUT_MS / 1_000}s`, + ) +} + +async function main(): Promise { + const rpcUrl = process.env.RPC_URL ?? hegotaTestnet.rpcUrls.default.http[0] + const owner = privateKeyToAccount(privateKeyFromEnv('PRIVATE_KEY')) + const payerOwner = privateKeyToAccount( + privateKeyFromEnv('PAYMASTER_PRIVATE_KEY'), + ) + const recipient: Address = getAddress(requiredEnv('RECIPIENT')) + const amount = parseEther(process.env.AMOUNT_ETH ?? '0.1') + const dryRun = process.env.DRY_RUN === '1' + + const client = createPublicClient({ + chain: hegotaTestnet, + transport: http(rpcUrl), + }) + const account = await toEoaFrameAccount({ client, owner }) + const payer = await toEoaFramePayerAccount({ owner: payerOwner }) + + const unsigned = await prepareFrameTransaction( + account, + [{ to: recipient, value: amount, data: '0x' }], + { + validation: { execution: 30_000n, state: 0n }, + calls: [{ execution: 30_000n, state: 200_000n }], + }, + { + paymaster: { + account: payer, + limits: { execution: 30_000n, state: 200_000n }, + }, + }, + ) + + const signed = await signFrameTransaction(account, unsigned, { payer }) + assertValidFrameTx(signed) + + const raw = encodeFrameTx(signed) + const transactionHash = keccak256(raw) + const gas = frameTxGas(signed) + const maxGasCost = frameTxMaxCost(signed, 0n) + + console.log(`raw tx: ${raw}`) + console.log(`sender: ${account.address}`) + console.log(`payer: ${payer.address}`) + console.log(`recipient: ${recipient}`) + console.log(`amount: ${formatEther(amount)} ETH`) + console.log(`nonce keys: [${signed.nonceKeys.join(', ')}] at seq ${signed.nonceSeq}`) + console.log(`max gas: ${gas.maxGas}`) + console.log(`max gas cost: ${formatEther(maxGasCost)} ETH`) + console.log(`local hash: ${transactionHash}`) + + const simulation = await simulateFrameTransaction(client, raw) + console.log(`simulated: valid=${simulation.valid} prefix=${simulation.prefixShape}`) + console.log(` payer: ${simulation.payer}`) + console.log(` gas used: ${simulation.gasUsed}`) + console.log(` max cost: ${simulation.maxCost} (local ${maxGasCost})`) + if (!simulation.valid) + throw new Error( + `simulation rejected the transaction: ${simulation.violation}`, + ) + + const [senderBalanceBefore, payerBalanceBefore, recipientBalanceBefore] = + await Promise.all([ + client.getBalance({ address: account.address }), + client.getBalance({ address: payer.address }), + client.getBalance({ address: recipient }), + ]) + const balancesBefore: BalanceSnapshot = { + sender: senderBalanceBefore, + payer: payerBalanceBefore, + recipient: recipientBalanceBefore, + } + + if (dryRun) { + console.log('DRY_RUN=1, so the valid transaction was not broadcast') + console.log('\ncurrent balances:') + console.log(` sender: ${formatEther(balancesBefore.sender)} ETH`) + console.log(` recipient: ${formatEther(balancesBefore.recipient)} ETH`) + console.log(` payer: ${formatEther(balancesBefore.payer)} ETH`) + console.log('\nprojected changes if broadcast:') + console.log(` sender: -${formatEther(amount)} ETH`) + console.log(` recipient: +${formatEther(amount)} ETH`) + console.log(` payer: gas used, capped at ${formatEther(maxGasCost)} ETH`) + return + } + + const submittedHash = (await client.request({ + method: 'eth_sendRawTransaction', + params: [raw], + })) as Hex + + if (submittedHash.toLowerCase() !== transactionHash.toLowerCase()) + throw new Error( + `node returned hash ${submittedHash}, expected ${transactionHash}`, + ) + + console.log(`submitted: ${submittedHash}`) + const rpcReceipt = await waitForFrameReceipt(client, submittedHash) + const receipt = parseRpcFrameReceipt(rpcReceipt) + console.log('payer:', receipt.payer) + console.log('frames:', receipt.frameReceipts) + + const [senderBalanceAfter, payerBalanceAfter, recipientBalanceAfter] = + await Promise.all([ + client.getBalance({ address: account.address }), + client.getBalance({ address: payer.address }), + client.getBalance({ address: recipient }), + ]) + + const addressesAreDistinct = + !isAddressEqual(account.address, payer.address) && + !isAddressEqual(account.address, recipient) && + !isAddressEqual(payer.address, recipient) + if (!addressesAreDistinct) + console.log( + '\nnote: sender, recipient, and payer are not distinct; role deltas overlap.', + ) + + printBalanceChanges( + balancesBefore, + { + sender: senderBalanceAfter, + payer: payerBalanceAfter, + recipient: recipientBalanceAfter, + }, + amount, + ) +} + +main().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : error) + process.exitCode = 1 +}) diff --git a/scripts/send-frame-transaction.ts b/scripts/send-frame-transaction.ts new file mode 100644 index 0000000..edbcc99 --- /dev/null +++ b/scripts/send-frame-transaction.ts @@ -0,0 +1,89 @@ +/** + * Send native ETH with the high-level `sendFrameTransaction` function. + * + * Required: + * PRIVATE_KEY=0x... RECIPIENT=0x... \ + * bun run scripts/send-frame-transaction.ts + * + * Optional: + * AMOUNT_ETH=0.001 + * RPC_URL=https://rpc1.privacy.ethrex.xyz + * + * This script broadcasts immediately. The sender pays both the transfer value + * and gas because no separate payer is supplied. + */ +import { + createPublicClient, + formatEther, + getAddress, + http, + parseEther, + type Address, + type Hex, +} from 'viem' +import { privateKeyToAccount } from 'viem/accounts' +import { + hegotaTestnet, + sendFrameTransaction, + toEoaFrameAccount, + toEoaFramePayerAccount, +} from '../src/index.js' +import { frameActions } from '../src/viem.js' + +function requiredEnv(name: string): string { + const value = process.env[name] + if (!value) throw new Error(`${name} is required`) + return value +} + +function privateKeyFromEnv(name: string): Hex { + const value = requiredEnv(name) + if (!/^0x[0-9a-fA-F]{64}$/.test(value)) + throw new Error(`${name} must be a 32-byte 0x-prefixed hex value`) + return value as Hex +} + +async function main(): Promise { + const rpcUrl = process.env.RPC_URL ?? hegotaTestnet.rpcUrls.default.http[0] + const owner = privateKeyToAccount(privateKeyFromEnv('PRIVATE_KEY')) + const payer = privateKeyToAccount(privateKeyFromEnv('PAYMASTER_PRIVATE_KEY')) + const recipient: Address = getAddress(requiredEnv('RECIPIENT')) + const amount = parseEther(process.env.AMOUNT_ETH ?? '0.001') + const client = createPublicClient({ + chain: hegotaTestnet, + transport: http(rpcUrl), + }).extend(frameActions) + const account = await toEoaFrameAccount({ client, owner }) + + console.log(`sender: ${account.address}`) + console.log(`recipient: ${recipient}`) + console.log(`amount: ${formatEther(amount)} ETH`) + + const hash = await sendFrameTransaction( + account, + [{ to: recipient, value: amount }], + { + limits: { + validation: { execution: 30_000n, state: 0n }, + calls: [{ execution: 30_000n, state: 200_000n }], + }, + paymaster: { + account: await toEoaFramePayerAccount({ owner: payer }), + limits: { execution: 30_000n, state: 200_000n }, + }, + }, + ) + + console.log(`submitted: ${hash}`) + const receipt = await client.waitForFrameTransactionReceipt({ + hash, + timeout: 120_000, + }) + console.log('payer:', receipt.payer) + console.log('frames:', receipt.frameReceipts) +} + +main().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : error) + process.exitCode = 1 +}) diff --git a/src/accounts/toEoaFrameAccount.ts b/src/accounts/toEoaFrameAccount.ts index 98b7a19..352c0c3 100644 --- a/src/accounts/toEoaFrameAccount.ts +++ b/src/accounts/toEoaFrameAccount.ts @@ -10,7 +10,7 @@ import { type Transport, isAddressEqual, } from 'viem' -import { signFrameTx } from '../signatures.js' +import { signFrameSignature } from '../signatures.js' import { FrameEncodeError } from '../errors.js' import { getFrameNonceSeq } from '../nonce.js' import type { FrameTransaction } from '../types.js' @@ -72,26 +72,38 @@ export async function toEoaFrameAccount< async getValidationData() { return '0x' }, + async getSignatureEntries() { + return [ + { + scheme: 1, + signer: null, + msg: '0x', + signature: '0x', + }, + ] + }, async signFrameTransaction(transaction: FrameTransaction) { if (!isAddressEqual(transaction.sender, owner.address)) throw new FrameEncodeError( `transaction sender ${transaction.sender} does not match EOA ${owner.address}`, ) - return signFrameTx( - { - ...transaction, - signatures: [ - { - scheme: 1, - signer: null, - msg: '0x', - signature: '0x', - }, - ], - }, - owner, - ) + const prepared = + transaction.signatures.length === 0 + ? { + ...transaction, + signatures: [ + { + scheme: 1 as const, + signer: null, + msg: '0x' as const, + signature: '0x' as const, + }, + ], + } + : transaction + + return signFrameSignature(prepared, 0, owner) }, }) } diff --git a/src/accounts/toEoaFramePayerAccount.ts b/src/accounts/toEoaFramePayerAccount.ts new file mode 100644 index 0000000..c54f323 --- /dev/null +++ b/src/accounts/toEoaFramePayerAccount.ts @@ -0,0 +1,101 @@ +import { + type Account, + type Address, + type Hash, + type Hex, + isAddressEqual, +} from 'viem' +import { FrameEncodeError } from '../errors.js' +import { signFrameSignature } from '../signatures.js' +import type { FrameTransaction } from '../types.js' +import { toFramePayerAccount } from './toFramePayerAccount.js' +import type { + FramePayerAccount, + FramePayerAccountImplementation, +} from './types.js' + +export type EoaFramePayerOwner = Account & { + address: Address + sign: (parameters: { hash: Hash }) => Promise +} + +export type EoaFramePayerAccountImplementation< + owner extends EoaFramePayerOwner = EoaFramePayerOwner, + extend extends object = object, +> = FramePayerAccountImplementation + +export type ToEoaFramePayerAccountParameters< + owner extends EoaFramePayerOwner = EoaFramePayerOwner, + extend extends object = object, +> = { + owner: owner + extend?: extend | undefined +} + +export type ToEoaFramePayerAccountReturnType< + owner extends EoaFramePayerOwner = EoaFramePayerOwner, + extend extends object = object, +> = FramePayerAccount> + +/** Create a frame payer backed by the protocol's codeless EOA default code. */ +export function toEoaFramePayerAccount< + owner extends EoaFramePayerOwner, + extend extends object = object, +>( + parameters: ToEoaFramePayerAccountParameters, +): Promise> { + const { owner } = parameters + + function assertPayFrame(transaction: FrameTransaction): void { + const hasPayFrame = transaction.frames.some( + (frame) => + frame.mode === 1 && + frame.flags === 0x1 && + frame.target !== null && + isAddressEqual(frame.target, owner.address), + ) + if (!hasPayFrame) + throw new FrameEncodeError( + `transaction has no payment-only VERIFY frame targeting EOA payer ${owner.address}`, + ) + } + + return toFramePayerAccount({ + owner, + ...(parameters.extend === undefined ? {} : { extend: parameters.extend }), + async getAddress() { + return owner.address + }, + async getPayData() { + return '0x' + }, + async getSignatureEntries(transaction) { + assertPayFrame(transaction) + if (transaction.signatures.length !== 1) + throw new FrameEncodeError( + `codeless EOA payer signature must be inserted at index 1; found ${transaction.signatures.length} existing entries`, + ) + + return [ + { + scheme: 1, + signer: owner.address, + msg: '0x', + signature: '0x', + }, + ] + }, + async signFrameTransaction(transaction: FrameTransaction) { + assertPayFrame(transaction) + const signature = transaction.signatures[1] + if (signature === undefined) + throw new FrameEncodeError('codeless EOA payer requires signature index 1') + if (signature.signer === null || !isAddressEqual(signature.signer, owner.address)) + throw new FrameEncodeError( + `signature 1 signer must match EOA payer ${owner.address}`, + ) + + return signFrameSignature(transaction, 1, owner) + }, + }) +} diff --git a/src/accounts/toFramePayerAccount.ts b/src/accounts/toFramePayerAccount.ts new file mode 100644 index 0000000..e9938df --- /dev/null +++ b/src/accounts/toFramePayerAccount.ts @@ -0,0 +1,31 @@ +import type { + FramePayerAccount, + FramePayerAccountImplementation, +} from './types.js' + +export type ToFramePayerAccountParameters< + implementation extends + FramePayerAccountImplementation = FramePayerAccountImplementation, +> = implementation + +export type ToFramePayerAccountReturnType< + implementation extends + FramePayerAccountImplementation = FramePayerAccountImplementation, +> = FramePayerAccount + +/** Resolve a payer implementation into the object consumed by frame actions. */ +export async function toFramePayerAccount< + const implementation extends FramePayerAccountImplementation, +>( + implementation: ToFramePayerAccountParameters, +): Promise> { + const { extend, ...rest } = implementation + const address = await implementation.getAddress() + + return { + ...extend, + ...rest, + address, + type: 'framePayer', + } as ToFramePayerAccountReturnType +} diff --git a/src/accounts/types.ts b/src/accounts/types.ts index c45c4cd..98ceadb 100644 --- a/src/accounts/types.ts +++ b/src/accounts/types.ts @@ -9,7 +9,11 @@ import type { LocalAccount, Transport, } from 'viem' -import type { FrameTransaction } from '../types.js' +import type { + FrameLimits, + FrameSignature, + FrameTransaction, +} from '../types.js' export type FrameCall = { to: Address @@ -28,12 +32,44 @@ export type GetValidationDataParameters = { chainId: bigint nonceKeys: readonly bigint[] nonceSeq: bigint + paymaster?: FramePaymasterParameters | undefined } export type DirectFrameExecution = { type: 'direct' } +export type FramePayerAccountImplementation< + owner extends Account | undefined = Account | undefined, + extend extends object = object, +> = { + /** Account or signer that controls the payer. */ + owner: owner + /** Add implementation-specific properties to the resolved payer account. */ + extend?: extend | undefined + /** Resolve the address that calls `APPROVE(0x1)` and pays for the transaction. */ + getAddress: () => Promise
+ /** Produce calldata for the payer's EIP-8141 `pay` VERIFY frame. */ + getPayData: (transaction: FrameTransaction) => Promise + /** Describe the payer-owned outer signature entries before anything signs. */ + getSignatureEntries: ( + transaction: FrameTransaction, + ) => Promise + /** Populate the payer-owned signature entries in a prepared transaction. */ + signFrameTransaction: ( + transaction: FrameTransaction, + ) => Promise +} + +/** Parameters used to construct an EIP-8141 `pay` validation frame. */ +export type FramePaymasterParameters< + implementation extends + FramePayerAccountImplementation = FramePayerAccountImplementation, +> = { + account: FramePayerAccount + limits: FrameLimits +} + /** Account-specific behavior required to construct and sign frame transactions. */ export type FrameAccountImplementation< chain extends Chain | undefined = Chain | undefined, @@ -58,6 +94,10 @@ export type FrameAccountImplementation< getNonce: (parameters?: GetFrameNonceParameters) => Promise /** Produce calldata for the account's EIP-8141 validation frame. */ getValidationData: (parameters: GetValidationDataParameters) => Promise + /** Describe the sender-owned outer signature entries before anything signs. */ + getSignatureEntries: ( + transaction: FrameTransaction, + ) => Promise /** Apply the account's signature scheme and ordering to a frame transaction. */ signFrameTransaction: ( transaction: FrameTransaction, @@ -93,3 +133,26 @@ export type FrameAccount< > > > + +type PayerAccountExtension< + implementation extends FramePayerAccountImplementation, +> = NonNullable + +/** A resolved account that authorizes and funds an EIP-8141 `pay` frame. */ +export type FramePayerAccount< + implementation extends + FramePayerAccountImplementation = FramePayerAccountImplementation, +> = Simplify< + Assign< + PayerAccountExtension, + Assign< + Omit, + { + /** Resolved payer address. */ + address: Address + /** Discriminator for frame-payer-aware APIs. */ + type: 'framePayer' + } + > + > +> diff --git a/src/index.ts b/src/index.ts index 3954e2a..aff6edb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,9 +6,24 @@ export { type FrameAccount, type FrameAccountImplementation, type FrameCall, + type FramePaymasterParameters, + type FramePayerAccount, + type FramePayerAccountImplementation, type GetFrameNonceParameters, type GetValidationDataParameters, } from './accounts/types.js' +export { + type ToFramePayerAccountParameters, + type ToFramePayerAccountReturnType, + toFramePayerAccount, +} from './accounts/toFramePayerAccount.js' +export { + type EoaFramePayerAccountImplementation, + type EoaFramePayerOwner, + type ToEoaFramePayerAccountParameters, + type ToEoaFramePayerAccountReturnType, + toEoaFramePayerAccount, +} from './accounts/toEoaFramePayerAccount.js' export { type ToFrameAccountParameters, type ToFrameAccountReturnType, @@ -32,7 +47,16 @@ export { type PrepareFrameTransactionOptions, prepareFrameTransaction, } from './prepareFrameTransaction.js' -export { signFrameTransaction } from './signFrameTransaction.js' +export { + type SignFrameTransactionOptions, + signFrameTransaction, +} from './signFrameTransaction.js' +export { + type SendFrameCall, + type SendFrameTransactionLimits, + type SendFrameTransactionOptions, + sendFrameTransaction, +} from './sendFrameTransaction.js' export { rlpUint, parseRlpUint, byteLength } from './rlp.js' export { encodeFrameTx, @@ -53,6 +77,7 @@ export { assertValidFrameTx, recoverFrameSigner, resolveSigner, + signFrameSignature, signFrameTx, } from './signatures.js' export { diff --git a/src/prepareFrameTransaction.ts b/src/prepareFrameTransaction.ts index 058560a..87445e4 100644 --- a/src/prepareFrameTransaction.ts +++ b/src/prepareFrameTransaction.ts @@ -1,7 +1,12 @@ import type { BlockTag, Chain, Hex } from 'viem' import { MAX_FRAMES, assertNonceKeys } from './envelope.js' import { FrameEncodeError } from './errors.js' -import type { FrameAccount, FrameAccountImplementation, FrameCall } from './accounts/types.js' +import type { + FrameAccount, + FrameAccountImplementation, + FrameCall, + FramePaymasterParameters, +} from './accounts/types.js' import type { FrameLimits, FrameTransaction } from './types.js' export type PrepareFrameLimits = { @@ -22,6 +27,8 @@ export type PrepareFrameTransactionOptions = { * key `0` only on its own. */ nonceKeys?: readonly bigint[] | undefined + /** Optional payer represented by an EIP-8141 `pay` VERIFY frame. */ + paymaster?: FramePaymasterParameters | undefined } type RpcBlock = { @@ -69,9 +76,11 @@ async function getFees( /** * Build an unsigned direct-execution frame transaction. * - * The returned transaction contains one leading VERIFY frame followed by one - * SENDER frame per call. Pass it to `account.signFrameTransaction` to produce - * the transaction that can be validated and encoded. + * Without a paymaster, the returned transaction contains one `self_verify` + * frame followed by one SENDER frame per call. With a paymaster, it contains + * `only_verify`, `pay`, then the SENDER frames. Pass it to + * `signFrameTransaction`, including the payer when present, to populate the + * prepared signature entries. */ export async function prepareFrameTransaction< implementation extends FrameAccountImplementation, @@ -81,11 +90,13 @@ export async function prepareFrameTransaction< frameLimits: PrepareFrameLimits, options: PrepareFrameTransactionOptions = {}, ): Promise { + const { paymaster } = options + const validationFrameCount = paymaster === undefined ? 1 : 2 if (calls.length === 0) throw new FrameEncodeError('prepareFrameTransaction requires at least one call') - if (calls.length + 1 > MAX_FRAMES) + if (calls.length + validationFrameCount > MAX_FRAMES) throw new FrameEncodeError( - `prepareFrameTransaction supports at most ${MAX_FRAMES - 1} calls because the validation frame also counts toward the ${MAX_FRAMES}-frame limit`, + `prepareFrameTransaction supports at most ${MAX_FRAMES - validationFrameCount} calls with ${validationFrameCount} validation frame${validationFrameCount === 1 ? '' : 's'}`, ) if (frameLimits.calls.length !== calls.length) throw new FrameEncodeError( @@ -93,6 +104,7 @@ export async function prepareFrameTransaction< ) assertLimits(frameLimits.validation, 'frameLimits.validation') + if (paymaster !== undefined) assertLimits(paymaster.limits, 'paymaster.limits') for (const [index, limits] of frameLimits.calls.entries()) assertLimits(limits, `frameLimits.calls[${index}]`) @@ -115,9 +127,10 @@ export async function prepareFrameTransaction< chainId, nonceKeys, nonceSeq, + ...(paymaster === undefined ? {} : { paymaster }), }) - return { + const transaction: FrameTransaction = { chainId, nonceKeys, nonceSeq, @@ -125,12 +138,24 @@ export async function prepareFrameTransaction< frames: [ { mode: 1, - flags: 0x3, + flags: paymaster === undefined ? 0x3 : 0x2, target: null, limits: frameLimits.validation, value: 0n, data: validationData, }, + ...(paymaster === undefined + ? [] + : [ + { + mode: 1 as const, + flags: 0x1, + target: paymaster.account.address, + limits: paymaster.limits, + value: 0n, + data: '0x' as const, + }, + ]), ...calls.map((call, index) => ({ mode: 2 as const, flags: 0, @@ -145,4 +170,21 @@ export async function prepareFrameTransaction< maxFeePerBlobGas: 0n, blobVersionedHashes: [], } + + if (paymaster !== undefined) { + const payFrame = transaction.frames[1]! + transaction.frames[1] = { + ...payFrame, + data: await paymaster.account.getPayData(transaction), + } + } + + const senderEntries = await account.getSignatureEntries(transaction) + transaction.signatures = [...senderEntries] + if (paymaster !== undefined) { + const payerEntries = await paymaster.account.getSignatureEntries(transaction) + transaction.signatures.push(...payerEntries) + } + + return transaction } diff --git a/src/sendFrameTransaction.ts b/src/sendFrameTransaction.ts new file mode 100644 index 0000000..bf7293a --- /dev/null +++ b/src/sendFrameTransaction.ts @@ -0,0 +1,81 @@ +import type { Address, Chain, Hex } from 'viem' +import type { + FrameAccount, + FrameAccountImplementation, + FramePayerAccount, + FramePayerAccountImplementation, +} from './accounts/types.js' +import { encodeFrameTx } from './envelope.js' +import { + prepareFrameTransaction, + type PrepareFrameTransactionOptions, +} from './prepareFrameTransaction.js' +import { sendRawFrameTransaction } from './rpc.js' +import { signFrameTransaction } from './signFrameTransaction.js' +import type { FrameLimits } from './types.js' + +export type SendFrameCall = { + to: Address + value?: bigint | undefined + data?: Hex | undefined +} + +export type SendFrameTransactionLimits = { + /** Limits for the sender's leading VERIFY frame. */ + validation: FrameLimits + /** One mandatory limit entry for each call, in the same order as `calls`. */ + calls: readonly FrameLimits[] +} + +export type SendFrameTransactionOptions< + payerImplementation extends + FramePayerAccountImplementation = FramePayerAccountImplementation, +> = Omit & { + limits: SendFrameTransactionLimits + paymaster?: + | { + account: FramePayerAccount + limits: FrameLimits + } + | undefined +} + +/** Prepare, sign, encode, and broadcast a frame transaction. */ +export async function sendFrameTransaction< + implementation extends FrameAccountImplementation, + payerImplementation extends + FramePayerAccountImplementation = FramePayerAccountImplementation, +>( + account: FrameAccount, + calls: readonly SendFrameCall[], + options: SendFrameTransactionOptions, +): Promise { + const normalizedCalls = calls.map((call) => ({ + to: call.to, + value: call.value ?? 0n, + data: call.data ?? ('0x' as const), + })) + const paymaster = options.paymaster + const transaction = await prepareFrameTransaction( + account, + normalizedCalls, + options.limits, + { + ...(options.blockTag === undefined ? {} : { blockTag: options.blockTag }), + ...(options.nonceKeys === undefined ? {} : { nonceKeys: options.nonceKeys }), + ...(paymaster === undefined + ? {} + : { + paymaster: { + account: paymaster.account, + limits: paymaster.limits, + }, + }), + }, + ) + const signed = await signFrameTransaction(account, transaction, { + ...(paymaster === undefined ? {} : { payer: paymaster.account }), + }) + + return sendRawFrameTransaction(account.client, encodeFrameTx(signed)) +} diff --git a/src/signFrameTransaction.ts b/src/signFrameTransaction.ts index c8df940..2eb836b 100644 --- a/src/signFrameTransaction.ts +++ b/src/signFrameTransaction.ts @@ -1,19 +1,41 @@ import { isAddressEqual } from 'viem' -import type { FrameAccount, FrameAccountImplementation } from './accounts/types.js' +import type { + FrameAccount, + FrameAccountImplementation, + FramePayerAccount, + FramePayerAccountImplementation, +} from './accounts/types.js' import { FrameEncodeError } from './errors.js' +import { assertValidFrameTx } from './signatures.js' import type { FrameTransaction } from './types.js' +export type SignFrameTransactionOptions< + payerImplementation extends + FramePayerAccountImplementation = FramePayerAccountImplementation, +> = { + payer?: FramePayerAccount | undefined +} + /** Sign a prepared transaction using its frame account's signing strategy. */ export async function signFrameTransaction< implementation extends FrameAccountImplementation, + payerImplementation extends + FramePayerAccountImplementation = FramePayerAccountImplementation, >( account: FrameAccount, transaction: FrameTransaction, + options: SignFrameTransactionOptions = {}, ): Promise { if (!isAddressEqual(transaction.sender, account.address)) throw new FrameEncodeError( `transaction sender ${transaction.sender} does not match frame account ${account.address}`, ) - return account.signFrameTransaction(transaction) + const senderSigned = await account.signFrameTransaction(transaction) + const signed = + options.payer === undefined + ? senderSigned + : await options.payer.signFrameTransaction(senderSigned) + assertValidFrameTx(signed) + return signed } diff --git a/src/signatures.ts b/src/signatures.ts index 4c77d90..8996f90 100644 --- a/src/signatures.ts +++ b/src/signatures.ts @@ -147,6 +147,52 @@ export type FrameSigner = { sign?: ((parameters: { hash: Hex }) => Promise) | undefined } +function resolveFrameSigner(signer: Hex | FrameSigner): FrameSigner { + return typeof signer === 'string' ? privateKeyToAccount(signer) : signer +} + +/** Sign one empty-message SECP256K1 entry without requiring other entries to be complete. */ +export async function signFrameSignature( + tx: FrameTransaction, + index: number, + signer: Hex | FrameSigner, +): Promise { + const account = resolveFrameSigner(signer) + if (typeof account.sign !== 'function') + throw new FrameEncodeError( + `account ${account.address} cannot sign a raw 32-byte digest: it has no ` + + '`sign` method. A JSON-RPC account cannot sign one at all, and ' + + '`signMessage` is not a substitute — it EIP-191-prefixes its argument.', + ) + + const entry = tx.signatures[index] + if (entry === undefined) + throw new FrameEncodeError(`no signature at index ${index}`) + if (entry.scheme !== 1 || entry.msg !== '0x') + throw new FrameEncodeError( + `signature ${index}: slot signing requires SECP256K1 with an empty msg`, + ) + + const resolvedSigner = entry.signer ?? tx.sender + if (!sameAddress(resolvedSigner, account.address)) + throw new FrameEncodeError( + `signature ${index}: resolved signer ${resolvedSigner} does not match ` + + `the signing account ${account.address}`, + ) + + const flat = await account.sign({ hash: frameTxSigHash(tx) }) + const r = sliceHex(flat, 0, 32) + const s = sliceHex(flat, 32, 64) + const v = bareRecoveryId(BigInt(sliceHex(flat, 64, 65)), index) + const signature = `0x${v.toString(16).padStart(2, '0')}${r.slice(2)}${s.slice(2)}` as Hex + const signedEntry = { ...entry, signature } + assertCanonicalSignature(signedEntry, index) + + const signatures = [...tx.signatures] + signatures[index] = signedEntry + return { ...tx, signatures } +} + /** * Sign every empty-`msg` SECP256K1 entry over the transaction's sig-hash. * @@ -160,7 +206,7 @@ export async function signFrameTx( tx: FrameTransaction, signer: Hex | FrameSigner, ): Promise { - const account = typeof signer === 'string' ? privateKeyToAccount(signer) : signer + const account = resolveFrameSigner(signer) if (typeof account.sign !== 'function') throw new FrameEncodeError( `account ${account.address} cannot sign a raw 32-byte digest: it has no ` + diff --git a/test/accounts.test.ts b/test/accounts.test.ts index 6f4709e..694292e 100644 --- a/test/accounts.test.ts +++ b/test/accounts.test.ts @@ -4,6 +4,8 @@ import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' import { toFrameAccount } from '../src/accounts/toFrameAccount.js' import { toEoaFrameAccount } from '../src/accounts/toEoaFrameAccount.js' +import { toEoaFramePayerAccount } from '../src/accounts/toEoaFramePayerAccount.js' +import { toFramePayerAccount } from '../src/accounts/toFramePayerAccount.js' import { recoverFrameSigner } from '../src/signatures.js' import type { FrameTransaction } from '../src/types.js' import { GOLDEN_TX } from './fixtures/golden.js' @@ -27,6 +29,7 @@ describe('toFrameAccount', () => { async getAddress() { return address }, async getNonce() { return 1n }, async getValidationData({ nonceSeq }) { return nonceSeq === 1n ? '0xabcd' : '0x' }, + async getSignatureEntries() { return [] }, async signFrameTransaction(transaction) { return transaction }, }) @@ -55,6 +58,7 @@ describe('toFrameAccount', () => { getAddress: async () => owner.address, getNonce: async () => 0n, getValidationData: async () => '0x', + getSignatureEntries: async () => [], signFrameTransaction: async (transaction) => transaction, }) @@ -63,6 +67,95 @@ describe('toFrameAccount', () => { }) }) +describe('toEoaFramePayerAccount', () => { + test('uses default-code payment approval and signs index 1 as the payer', async () => { + const sender = privateKeyToAccount(OWNER_KEY) + const payerOwner = privateKeyToAccount(`0x${'22'.repeat(32)}`) + const payer = await toEoaFramePayerAccount({ owner: payerOwner }) + const transaction = { + ...GOLDEN_TX, + sender: sender.address, + frames: [ + { + ...GOLDEN_TX.frames[0]!, + flags: 0x1, + target: payerOwner.address, + }, + ...GOLDEN_TX.frames.slice(1), + ], + signatures: [ + { scheme: 1 as const, signer: null, msg: '0x' as const, signature: '0x' as const }, + ], + } + + expect(payer.address).toBe(payerOwner.address) + expect(payer.type).toBe('framePayer') + expect(await payer.getPayData(transaction)).toBe('0x') + + const entries = await payer.getSignatureEntries(transaction) + expect(entries).toEqual([ + { scheme: 1, signer: payerOwner.address, msg: '0x', signature: '0x' }, + ]) + + const signed = await payer.signFrameTransaction({ + ...transaction, + signatures: [...transaction.signatures, ...entries], + }) + expect(await recoverFrameSigner(signed, 1)).toBe(payerOwner.address) + }) + + test('requires its signature metadata at protocol-reserved index 1', async () => { + const payer = await toEoaFramePayerAccount({ + owner: privateKeyToAccount(`0x${'22'.repeat(32)}`), + }) + + await expect( + payer.getSignatureEntries({ + ...GOLDEN_TX, + frames: [ + { + ...GOLDEN_TX.frames[0]!, + flags: 0x1, + target: payer.address, + }, + ...GOLDEN_TX.frames.slice(1), + ], + signatures: [], + }), + ).rejects.toThrow(/inserted at index 1/) + }) + + test('refuses to sign without a pay frame targeting the payer', async () => { + const payer = await toEoaFramePayerAccount({ + owner: privateKeyToAccount(`0x${'22'.repeat(32)}`), + }) + + await expect( + payer.signFrameTransaction({ ...GOLDEN_TX, signatures: [] }), + ).rejects.toThrow(/no payment-only VERIFY frame/) + }) +}) + +describe('toFramePayerAccount', () => { + test('resolves methods and extensions', async () => { + const owner = privateKeyToAccount(OWNER_KEY) + const address = getAddress('0x0000000000000000000000000000000000009999') + const payer = await toFramePayerAccount({ + owner, + extend: { implementationName: 'test-payer' as const }, + getAddress: async () => address, + getPayData: async (_transaction: FrameTransaction) => '0xabcd', + getSignatureEntries: async () => [], + signFrameTransaction: async (transaction) => transaction, + }) + + expect(payer.address).toBe(address) + expect(payer.type).toBe('framePayer') + expect(payer.implementationName).toBe('test-payer') + expect(await payer.getPayData(GOLDEN_TX)).toBe('0xabcd') + }) +}) + describe('toEoaFrameAccount', () => { test('uses default-code validation and signs as the EOA', async () => { const owner = privateKeyToAccount(OWNER_KEY) diff --git a/test/prepareFrameTransaction.test.ts b/test/prepareFrameTransaction.test.ts index 3b4b976..1238d81 100644 --- a/test/prepareFrameTransaction.test.ts +++ b/test/prepareFrameTransaction.test.ts @@ -3,12 +3,29 @@ import { createClient, custom, getAddress } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' import { toEoaFrameAccount } from '../src/accounts/toEoaFrameAccount.js' +import { toEoaFramePayerAccount } from '../src/accounts/toEoaFramePayerAccount.js' +import { toFramePayerAccount } from '../src/accounts/toFramePayerAccount.js' import { keyedNonceSlot } from '../src/nonce.js' import { prepareFrameTransaction } from '../src/prepareFrameTransaction.js' -import { assertValidFrameTx } from '../src/signatures.js' +import { signFrameTransaction } from '../src/signFrameTransaction.js' +import { assertValidFrameTx, recoverFrameSigner } from '../src/signatures.js' const OWNER_KEY = `0x${'11'.repeat(32)}` as const +async function contractPayer( + owner: ReturnType, + address: ReturnType, + data: `0x${string}` = '0x', +) { + return toFramePayerAccount({ + owner, + getAddress: async () => address, + getPayData: async () => data, + getSignatureEntries: async () => [], + signFrameTransaction: async (transaction) => transaction, + }) +} + /** `storage` maps a NONCE_MANAGER slot to its value; unlisted slots read zero. */ function testClient(storage: Record = {}) { const requests: { method: string; params?: unknown }[] = [] @@ -63,7 +80,9 @@ describe('prepareFrameTransaction', () => { nonceKeys: [0n], nonceSeq: 7n, sender: owner.address, - signatures: [], + signatures: [ + { scheme: 1, signer: null, msg: '0x', signature: '0x' }, + ], maxPriorityFeePerGas: 1_000_000_000n, maxFeePerGas: 5_000_000_000n, maxFeePerBlobGas: 0n, @@ -101,6 +120,138 @@ describe('prepareFrameTransaction', () => { expect(requests.some(({ method }) => method === 'eth_chainId')).toBe(false) }) + test('builds only_verify and pay frames before sponsored calls', async () => { + const { client, owner } = testClient() + const account = await toEoaFrameAccount({ client, owner }) + const paymaster = getAddress('0x0000000000000000000000000000000000009999') + const payer = await contractPayer(owner, paymaster, '0xabcdef') + const recipient = getAddress('0x0000000000000000000000000000000000001234') + + const transaction = await prepareFrameTransaction( + account, + [{ to: recipient, value: 1n, data: '0x1234' }], + { + validation: { execution: 80_000n, state: 0n }, + calls: [{ execution: 30_000n, state: 100_000n }], + }, + { + paymaster: { + account: payer, + limits: { execution: 60_000n, state: 200_000n }, + }, + }, + ) + + expect(transaction.frames).toEqual([ + { + mode: 1, + flags: 0x2, + target: null, + limits: { execution: 80_000n, state: 0n }, + value: 0n, + data: '0x', + }, + { + mode: 1, + flags: 0x1, + target: paymaster, + limits: { execution: 60_000n, state: 200_000n }, + value: 0n, + data: '0xabcdef', + }, + { + mode: 2, + flags: 0, + target: recipient, + limits: { execution: 30_000n, state: 100_000n }, + value: 1n, + data: '0x1234', + }, + ]) + }) + + test('prepares and signs with a distinct codeless EOA payer', async () => { + const { client, owner } = testClient() + const account = await toEoaFrameAccount({ client, owner }) + const payerOwner = privateKeyToAccount(`0x${'22'.repeat(32)}`) + const payer = await toEoaFramePayerAccount({ owner: payerOwner }) + + const transaction = await prepareFrameTransaction( + account, + [{ to: owner.address, value: 1n, data: '0x' }], + { + validation: { execution: 80_000n, state: 0n }, + calls: [{ execution: 30_000n, state: 0n }], + }, + { + paymaster: { + account: payer, + limits: { execution: 30_000n, state: 200_000n }, + }, + }, + ) + + expect(transaction.signatures).toEqual([ + { scheme: 1, signer: null, msg: '0x', signature: '0x' }, + { scheme: 1, signer: payer.address, msg: '0x', signature: '0x' }, + ]) + + const signed = await signFrameTransaction(account, transaction, { payer }) + expect(await recoverFrameSigner(signed, 0)).toBe(owner.address) + expect(await recoverFrameSigner(signed, 1)).toBe(payer.address) + expect(() => assertValidFrameTx(signed)).not.toThrow() + }) + + test('rejects negative paymaster limits before making RPC requests', async () => { + const { client, owner, requests } = testClient() + const account = await toEoaFrameAccount({ client, owner }) + const payer = await contractPayer(owner, owner.address) + + await expect( + prepareFrameTransaction( + account, + [{ to: owner.address, value: 0n, data: '0x' }], + { validation: { execution: 1n, state: 0n }, calls: [{ execution: 1n, state: 0n }] }, + { + paymaster: { + account: payer, + limits: { execution: -1n, state: 0n }, + }, + }, + ), + ).rejects.toThrow(/paymaster\.limits\.execution must not be negative/) + expect(requests).toEqual([]) + }) + + test('accounts for the pay frame in the transaction frame limit', async () => { + const { client, owner, requests } = testClient() + const account = await toEoaFrameAccount({ client, owner }) + const payer = await contractPayer(owner, owner.address) + const calls = Array.from({ length: 63 }, () => ({ + to: owner.address, + value: 0n, + data: '0x' as const, + })) + + await expect( + prepareFrameTransaction( + account, + calls, + { + validation: { execution: 1n, state: 0n }, + calls: calls.map(() => ({ execution: 1n, state: 0n })), + }, + { + paymaster: { + account: payer, + limits: { execution: 1n, state: 0n }, + }, + }, + ), + ).rejects.toThrow(/at most 62 calls with 2 validation frames/) + expect(requests).toEqual([]) + }) + test('selects non-zero keys at their shared NONCE_MANAGER sequence', async () => { const owner = privateKeyToAccount(OWNER_KEY) const [one, nine] = [1n, 9n].map((key) => keyedNonceSlot(owner.address, key)) diff --git a/test/sendFrameTransaction.test.ts b/test/sendFrameTransaction.test.ts new file mode 100644 index 0000000..cea7d19 --- /dev/null +++ b/test/sendFrameTransaction.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, test } from 'vitest' +import { createClient, custom, getAddress, keccak256, type Hex } from 'viem' +import { privateKeyToAccount } from 'viem/accounts' +import { mainnet } from 'viem/chains' +import { toEoaFrameAccount } from '../src/accounts/toEoaFrameAccount.js' +import { toEoaFramePayerAccount } from '../src/accounts/toEoaFramePayerAccount.js' +import { decodeFrameTx } from '../src/envelope.js' +import { sendFrameTransaction } from '../src/sendFrameTransaction.js' + +const OWNER_KEY = `0x${'11'.repeat(32)}` as const +const PAYER_KEY = `0x${'22'.repeat(32)}` as const + +function testClient() { + const owner = privateKeyToAccount(OWNER_KEY) + const requests: { method: string; params?: unknown }[] = [] + let submittedRaw: Hex | undefined + const client = createClient({ + account: owner, + chain: { ...mainnet, id: 8_141 }, + transport: custom({ + async request(request) { + requests.push(request) + switch (request.method) { + case 'eth_getTransactionCount': return '0x7' + case 'eth_maxPriorityFeePerGas': return '0x3b9aca00' + case 'eth_gasPrice': return '0x77359400' + case 'eth_getBlockByNumber': return { baseFeePerGas: '0x77359400' } + case 'eth_sendRawTransaction': { + submittedRaw = (request.params as [Hex])[0] + return keccak256(submittedRaw) + } + default: throw new Error(`unexpected RPC method ${request.method}`) + } + }, + }), + }) + return { client, owner, requests, getSubmittedRaw: () => submittedRaw } +} + +describe('sendFrameTransaction', () => { + test('defaults optional call fields and returns the node hash', async () => { + const { client, owner, getSubmittedRaw } = testClient() + const account = await toEoaFrameAccount({ client, owner }) + const recipient = getAddress('0x0000000000000000000000000000000000001234') + + const limits = { + validation: { execution: 30_000n, state: 0n }, + calls: [{ execution: 40_000n, state: 200_000n }], + } + const hash = await sendFrameTransaction(account, [{ to: recipient }], { + limits, + }) + const raw = getSubmittedRaw() + expect(raw).toBeDefined() + expect(hash).toBe(keccak256(raw!)) + + const transaction = decodeFrameTx(raw!) + expect(transaction.frames[0]!.limits).toEqual(limits.validation) + expect(transaction.frames[1]).toMatchObject({ + target: recipient, + value: 0n, + data: '0x', + limits: limits.calls[0], + }) + }) + + test('applies overrides and signs with a distinct EOA payer', async () => { + const { client, owner, getSubmittedRaw } = testClient() + const account = await toEoaFrameAccount({ client, owner }) + const payer = await toEoaFramePayerAccount({ + owner: privateKeyToAccount(PAYER_KEY), + }) + + await sendFrameTransaction( + account, + [{ to: owner.address, value: 1n }], + { + limits: { + validation: { execution: 20_000n, state: 0n }, + calls: [{ execution: 40_000n, state: 10_000n }], + }, + paymaster: { + account: payer, + limits: { execution: 25_000n, state: 100_000n }, + }, + }, + ) + + const transaction = decodeFrameTx(getSubmittedRaw()!) + expect(transaction.frames.map((frame) => frame.limits)).toEqual([ + { execution: 20_000n, state: 0n }, + { execution: 25_000n, state: 100_000n }, + { execution: 40_000n, state: 10_000n }, + ]) + expect(transaction.signatures).toHaveLength(2) + }) + + test('requires one per-call override for every call', async () => { + const { client, owner, requests } = testClient() + const account = await toEoaFrameAccount({ client, owner }) + + await expect( + sendFrameTransaction( + account, + [{ to: owner.address }, { to: owner.address }], + { + limits: { + validation: { execution: 1n, state: 0n }, + calls: [{ execution: 1n, state: 0n }], + }, + }, + ), + ).rejects.toThrow(/expected 2, got 1/) + expect(requests).toEqual([]) + }) +}) diff --git a/test/signFrameTransaction.test.ts b/test/signFrameTransaction.test.ts index 8489ace..fd8b334 100644 --- a/test/signFrameTransaction.test.ts +++ b/test/signFrameTransaction.test.ts @@ -3,6 +3,7 @@ import { createClient, custom, getAddress } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' import { toEoaFrameAccount } from '../src/accounts/toEoaFrameAccount.js' +import { toEoaFramePayerAccount } from '../src/accounts/toEoaFramePayerAccount.js' import { signFrameTransaction } from '../src/signFrameTransaction.js' import { recoverFrameSigner } from '../src/signatures.js' import { GOLDEN_TX } from './fixtures/golden.js' @@ -46,4 +47,43 @@ describe('signFrameTransaction', () => { ).rejects.toThrow(/does not match frame account/) expect(spy).not.toHaveBeenCalled() }) + + test('signs sender index 0 and distinct EOA payer index 1', async () => { + const owner = privateKeyToAccount(OWNER_KEY) + const payerOwner = privateKeyToAccount(`0x${'22'.repeat(32)}`) + const client = createClient({ + account: owner, + chain: mainnet, + transport: custom({ async request() {} }), + }) + const account = await toEoaFrameAccount({ client, owner }) + const payer = await toEoaFramePayerAccount({ owner: payerOwner }) + const base = { + ...GOLDEN_TX, + sender: owner.address, + frames: [ + { ...GOLDEN_TX.frames[0]!, flags: 0x2, target: null }, + { + ...GOLDEN_TX.frames[0]!, + flags: 0x1, + target: payer.address, + data: '0x' as const, + }, + ...GOLDEN_TX.frames.slice(1), + ], + signatures: [], + } + const senderEntries = await account.getSignatureEntries(base) + const withSenderEntries = { ...base, signatures: [...senderEntries] } + const payerEntries = await payer.getSignatureEntries(withSenderEntries) + const prepared = { + ...withSenderEntries, + signatures: [...withSenderEntries.signatures, ...payerEntries], + } + + const signed = await signFrameTransaction(account, prepared, { payer }) + + expect(await recoverFrameSigner(signed, 0)).toBe(owner.address) + expect(await recoverFrameSigner(signed, 1)).toBe(payerOwner.address) + }) }) From 6be99c0545f1dc67e44e7dab690274b4a743f742 Mon Sep 17 00:00:00 2001 From: Ghadi Mhawej Date: Mon, 28 Sep 2026 11:43:15 +0300 Subject: [PATCH 4/8] chore(repo): make the sender-paid example script actually sender-paid send-frame-transaction.ts documented PRIVATE_KEY and RECIPIENT as its only inputs and said the sender pays gas, but it also required PAYMASTER_PRIVATE_KEY and attached a paymaster. The sponsored flow already lives in send-eth-paymaster.ts, so drop the paymaster here. Co-Authored-By: Claude Opus 5.5 --- scripts/send-frame-transaction.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/scripts/send-frame-transaction.ts b/scripts/send-frame-transaction.ts index edbcc99..2709e0e 100644 --- a/scripts/send-frame-transaction.ts +++ b/scripts/send-frame-transaction.ts @@ -26,7 +26,6 @@ import { hegotaTestnet, sendFrameTransaction, toEoaFrameAccount, - toEoaFramePayerAccount, } from '../src/index.js' import { frameActions } from '../src/viem.js' @@ -46,7 +45,6 @@ function privateKeyFromEnv(name: string): Hex { async function main(): Promise { const rpcUrl = process.env.RPC_URL ?? hegotaTestnet.rpcUrls.default.http[0] const owner = privateKeyToAccount(privateKeyFromEnv('PRIVATE_KEY')) - const payer = privateKeyToAccount(privateKeyFromEnv('PAYMASTER_PRIVATE_KEY')) const recipient: Address = getAddress(requiredEnv('RECIPIENT')) const amount = parseEther(process.env.AMOUNT_ETH ?? '0.001') const client = createPublicClient({ @@ -67,10 +65,6 @@ async function main(): Promise { validation: { execution: 30_000n, state: 0n }, calls: [{ execution: 30_000n, state: 200_000n }], }, - paymaster: { - account: await toEoaFramePayerAccount({ owner: payer }), - limits: { execution: 30_000n, state: 200_000n }, - }, }, ) From 19a95d73a633f1463d5c9138a73d83a6c745a9fe Mon Sep 17 00:00:00 2001 From: nikhil kumar Date: Sun, 4 Oct 2026 14:16:05 +0530 Subject: [PATCH 5/8] feat: add P-256 frame account support --- README.md | 39 +++++- bun.lock | 1 + docs/DESIGN.md | 8 +- package.json | 1 + scripts/send-eth-p256.ts | 173 ++++++++++++++++++++++++++ src/accounts/toP256FrameAccount.ts | 98 +++++++++++++++ src/index.ts | 13 ++ src/p256.ts | 148 ++++++++++++++++++++++ test/p256.test.ts | 190 +++++++++++++++++++++++++++++ 9 files changed, 667 insertions(+), 4 deletions(-) create mode 100644 scripts/send-eth-p256.ts create mode 100644 src/accounts/toP256FrameAccount.ts create mode 100644 src/p256.ts create mode 100644 test/p256.test.ts diff --git a/README.md b/README.md index 45bcea5..6d6ce5c 100644 --- a/README.md +++ b/README.md @@ -103,9 +103,42 @@ argument, so the signature recovers to nothing. A `JsonRpcAccount` (a browser wa cannot sign a raw digest at all — both are refused with an error rather than producing a transaction the chain silently rejects. -P256 and ARBITRARY entries are left untouched; build those signatures yourself and let -`assertValidFrameTx` check them. The low-level `signFrameTx` handles one signer at a time; -`signFrameTransaction` coordinates a sender and an optional `FramePayerAccount`. +ARBITRARY entries are left untouched; build those signatures yourself and let +`assertValidFrameTx` check them. The low-level `signFrameTx` handles one secp256k1 signer +at a time; `signFrameTransaction` coordinates a sender and an optional +`FramePayerAccount`. + +For an EIP-7702 delegated account authorized by P-256, create a signer from its raw +32-byte private scalar and resolve the delegated EOA separately. P-256 signatures are +made directly over the frame sig-hash, normalized to low `s`, checked locally, and encoded +as `r || s || qx || qy`. + +```ts +import { + privateKeyToP256FrameSigner, + toP256FrameAccount, +} from '@jaw.id/frametx-kit' + +const signer = privateKeyToP256FrameSigner(p256PrivateKey) +const account = await toP256FrameAccount({ + client, + address: delegatedEoa, + signer, +}) +``` + +To exercise a PEM-backed delegated account end to end against the Ethrex testnet: + +```bash +RPC_URL=https://rpc1.privacy.ethrex.xyz \ +SENDER=0x... \ +RECIPIENT=0x... \ +P256_PRIVATE_KEY_PATH=/absolute/path/to/p256-private.pem \ +bun run scripts/send-eth-p256.ts +``` + +The script checks that the PEM-derived identity equals the delegated account's on-chain +`p256Signer()`, then sends through the high-level `sendFrameTransaction` action. Sending walks the strict path for you — `assertValidFrameTx`, `encodeFrameTx`, `eth_sendRawTransaction` — and checks that the hash the node returns is `keccak256` of the diff --git a/bun.lock b/bun.lock index f1e175d..339709f 100644 --- a/bun.lock +++ b/bun.lock @@ -8,6 +8,7 @@ "@semantic-release/changelog": "^7.0.0", "@semantic-release/git": "^11.0.1", "@types/node": "^20.16.0", + "ox": "0.14.44", "semantic-release": "^25.0.9", "tsup": "^8.5.1", "tsx": "^4.19.0", diff --git a/docs/DESIGN.md b/docs/DESIGN.md index c913158..835e51b 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -26,7 +26,7 @@ Not supported: blob-carrying transaction must be broadcast in the EIP-7594 wrapper, which the library does not produce. - **UTXO frames** (mode 5, EIP-8312), inert on this chain. -- **P256 and ARBITRARY signing.** Both are validated, neither is produced by `signFrameTx`. +- **ARBITRARY signing.** It is validated but not produced by this library. ## 2. The envelope @@ -146,6 +146,12 @@ strategy; `toFrameAccount` resolves it into a `FrameAccount`. from `eth_getTransactionCount`, other keys from `NONCE_MANAGER` via `eth_getStorageAt`, empty validation data, and one empty-`msg`, empty-`signer` SECP256K1 entry. +`toP256FrameAccount` targets an EIP-7702 delegated EOA whose validation code authorizes a +P-256 signer. It emits one empty-`msg` P256 entry with the explicit signer identity +`last20Bytes(keccak256(qx || qy))` at index `0`. Its signer signs the already-computed +frame sig-hash directly, without applying SHA-256 a second time, normalizes `s` low, and +encodes `r || s || qx || qy`. + A `FramePayerAccountImplementation` supplies `getAddress()`, `getPayData(tx)`, `getSignatureEntries(tx)` and `signFrameTransaction(tx)`; `toFramePayerAccount` resolves it into a `FramePayerAccount`. `toEoaFramePayerAccount` implements the protocol's codeless diff --git a/package.json b/package.json index 3a918ee..f21d06e 100644 --- a/package.json +++ b/package.json @@ -80,6 +80,7 @@ "@semantic-release/changelog": "^7.0.0", "@semantic-release/git": "^11.0.1", "@types/node": "^20.16.0", + "ox": "0.14.44", "semantic-release": "^25.0.9", "tsup": "^8.5.1", "tsx": "^4.19.0", diff --git a/scripts/send-eth-p256.ts b/scripts/send-eth-p256.ts new file mode 100644 index 0000000..6a5c33f --- /dev/null +++ b/scripts/send-eth-p256.ts @@ -0,0 +1,173 @@ +/** + * Send native ETH from an EIP-7702 delegated EOA using a P-256-authorized + * EIP-8141 frame transaction. + * + * Required: + * SENDER=0x... + * RECIPIENT=0x... + * P256_PRIVATE_KEY_PATH=/absolute/path/to/p256-private.pem + * + * Optional: + * RPC_URL=https://rpc1.privacy.ethrex.xyz + * AMOUNT_ETH=0.000001 + * P256_PRIVATE_KEY_PASSPHRASE=... + * P256_SIGNER_IDENTITY=0x... independently assert the expected identity + */ +import { createPrivateKey } from 'node:crypto' +import { readFileSync } from 'node:fs' +import { + type Hex, + createPublicClient, + decodeFunctionResult, + encodeFunctionData, + formatEther, + getAddress, + http, + isAddressEqual, + parseEther, +} from 'viem' +import { + hegotaTestnet, + parseRpcFrameReceipt, + privateKeyToP256FrameSigner, + sendFrameTransaction, + toP256FrameAccount, + type FrameRpcClient, + type RpcFrameReceiptJson, +} from '../src/index.js' + +const RECEIPT_TIMEOUT_MS = 120_000 +const P256_ACCOUNT_ABI = [ + { + type: 'function', + name: 'p256Signer', + stateMutability: 'view', + inputs: [], + outputs: [{ name: '', type: 'address' }], + }, +] as const + +function requiredEnv(name: string): string { + const value = process.env[name] + if (!value) throw new Error(`${name} is required`) + return value +} + +function loadP256PrivateKey(path: string): Hex { + const pem = readFileSync(path) + const passphrase = process.env.P256_PRIVATE_KEY_PASSPHRASE + const key = createPrivateKey( + passphrase === undefined ? pem : { key: pem, passphrase }, + ) + const jwk = key.export({ format: 'jwk' }) + if (jwk.kty !== 'EC' || jwk.crv !== 'P-256' || jwk.d === undefined) + throw new Error('P256_PRIVATE_KEY_PATH must contain a P-256 private PEM key') + + const privateKey = `0x${Buffer.from(jwk.d, 'base64url').toString('hex')}` as Hex + if (!/^0x[0-9a-f]{64}$/.test(privateKey)) + throw new Error('P-256 private scalar must be exactly 32 bytes') + return privateKey +} + +async function waitForFrameReceipt( + client: FrameRpcClient, + hash: Hex, +): Promise { + const deadline = Date.now() + RECEIPT_TIMEOUT_MS + while (Date.now() < deadline) { + const receipt = (await client.request({ + method: 'eth_getTransactionReceipt', + params: [hash], + })) as RpcFrameReceiptJson | null + if (receipt !== null) return receipt + await new Promise((resolve) => setTimeout(resolve, 1_000)) + } + throw new Error( + `transaction ${hash} was not mined within ${RECEIPT_TIMEOUT_MS / 1_000}s`, + ) +} + +async function main(): Promise { + const rpcUrl = process.env.RPC_URL ?? 'https://rpc1.privacy.ethrex.xyz' + const sender = getAddress(requiredEnv('SENDER')) + const recipient = getAddress(requiredEnv('RECIPIENT')) + const amount = parseEther(process.env.AMOUNT_ETH ?? '0.000001') + const signer = privateKeyToP256FrameSigner( + loadP256PrivateKey(requiredEnv('P256_PRIVATE_KEY_PATH')), + ) + + const expectedIdentity = process.env.P256_SIGNER_IDENTITY + if ( + expectedIdentity !== undefined && + !isAddressEqual(signer.address, getAddress(expectedIdentity)) + ) + throw new Error( + `PEM signer identity ${signer.address} does not match P256_SIGNER_IDENTITY ${expectedIdentity}`, + ) + + const client = createPublicClient({ + chain: hegotaTestnet, + transport: http(rpcUrl), + }) + const code = await client.getCode({ address: sender }) + if (code === undefined || !code.toLowerCase().startsWith('0xef0100')) + throw new Error(`sender ${sender} does not have an EIP-7702 delegation`) + + const signerCall = await client.call({ + to: sender, + data: encodeFunctionData({ abi: P256_ACCOUNT_ABI, functionName: 'p256Signer' }), + }) + if (signerCall.data === undefined) + throw new Error(`p256Signer() returned no data for ${sender}`) + const configuredSigner = decodeFunctionResult({ + abi: P256_ACCOUNT_ABI, + functionName: 'p256Signer', + data: signerCall.data, + }) + if (!isAddressEqual(configuredSigner, signer.address)) + throw new Error( + `delegated account authorizes ${configuredSigner}, but the PEM identity is ${signer.address}`, + ) + + const account = await toP256FrameAccount({ client, address: sender, signer }) + const [senderBalanceBefore, recipientBalanceBefore] = await Promise.all([ + client.getBalance({ address: sender }), + client.getBalance({ address: recipient }), + ]) + + console.log(`sender: ${sender}`) + console.log(`recipient: ${recipient}`) + console.log(`amount: ${formatEther(amount)} ETH`) + console.log(`P-256 signer: ${signer.address}`) + + const submittedHash = await sendFrameTransaction( + account, + [{ to: recipient, value: amount }], + { + limits: { + validation: { execution: 100_000n, state: 0n }, + calls: [{ execution: 30_000n, state: 200_000n }], + }, + }, + ) + + console.log(`submitted: ${submittedHash}`) + const rpcReceipt = await waitForFrameReceipt(client, submittedHash) + const receipt = parseRpcFrameReceipt(rpcReceipt) + const [senderBalanceAfter, recipientBalanceAfter] = await Promise.all([ + client.getBalance({ address: sender }), + client.getBalance({ address: recipient }), + ]) + + console.log('payer:', receipt.payer) + console.log('frames:', receipt.frameReceipts) + console.log(`sender delta: ${formatEther(senderBalanceAfter - senderBalanceBefore)} ETH`) + console.log( + `recipient delta: ${formatEther(recipientBalanceAfter - recipientBalanceBefore)} ETH`, + ) +} + +main().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : error) + process.exitCode = 1 +}) diff --git a/src/accounts/toP256FrameAccount.ts b/src/accounts/toP256FrameAccount.ts new file mode 100644 index 0000000..c149b0b --- /dev/null +++ b/src/accounts/toP256FrameAccount.ts @@ -0,0 +1,98 @@ +import { + type Address, + type Chain, + type Client, + type JsonRpcAccount, + type LocalAccount, + type Transport, + isAddressEqual, +} from 'viem' +import { FrameEncodeError } from '../errors.js' +import { getFrameNonceSeq } from '../nonce.js' +import { + type P256FrameSigner, + signP256FrameSignature, +} from '../p256.js' +import type { FrameTransaction } from '../types.js' +import { toFrameAccount } from './toFrameAccount.js' +import type { FrameAccount, FrameAccountImplementation } from './types.js' + +export type P256FrameAccountImplementation< + chain extends Chain | undefined = Chain | undefined, + extend extends object = object, +> = FrameAccountImplementation + +export type ToP256FrameAccountParameters< + chain extends Chain | undefined = Chain | undefined, + extend extends object = object, +> = { + client: Client + /** EIP-7702 delegated EOA represented by this frame account. */ + address: Address + signer: P256FrameSigner + extend?: extend | undefined +} + +export type ToP256FrameAccountReturnType< + chain extends Chain | undefined = Chain | undefined, + extend extends object = object, +> = FrameAccount> + +/** Create a direct-execution frame account authorized by a P-256 signer. */ +export async function toP256FrameAccount< + chain extends Chain | undefined, + extend extends object = object, +>( + parameters: ToP256FrameAccountParameters, +): Promise> { + const { address, client, signer } = parameters + + return toFrameAccount({ + client, + owner: undefined, + execution: { type: 'direct' }, + ...(parameters.extend === undefined ? {} : { extend: parameters.extend }), + async getAddress() { + return address + }, + async getNonce(nonceParameters = {}) { + return getFrameNonceSeq(client, { address, ...nonceParameters }) + }, + async getValidationData() { + return '0x' + }, + async getSignatureEntries() { + return [ + { + scheme: 2, + signer: signer.address, + msg: '0x', + signature: '0x', + }, + ] + }, + async signFrameTransaction(transaction: FrameTransaction) { + if (!isAddressEqual(transaction.sender, address)) + throw new FrameEncodeError( + `transaction sender ${transaction.sender} does not match P-256 frame account ${address}`, + ) + + const prepared = + transaction.signatures.length === 0 + ? { + ...transaction, + signatures: [ + { + scheme: 2 as const, + signer: signer.address, + msg: '0x' as const, + signature: '0x' as const, + }, + ], + } + : transaction + + return signP256FrameSignature(prepared, 0, signer) + }, + }) +} diff --git a/src/index.ts b/src/index.ts index aff6edb..5478b19 100644 --- a/src/index.ts +++ b/src/index.ts @@ -36,6 +36,12 @@ export { type ToEoaFrameAccountReturnType, toEoaFrameAccount, } from './accounts/toEoaFrameAccount.js' +export { + type P256FrameAccountImplementation, + type ToP256FrameAccountParameters, + type ToP256FrameAccountReturnType, + toP256FrameAccount, +} from './accounts/toP256FrameAccount.js' export { type GetFrameNonceSeqParameters, NONCE_MANAGER, @@ -69,6 +75,13 @@ export { EXPIRY_VERIFIER, } from './envelope.js' export { frameTxSigHash } from './sighash.js' +export { + type P256FrameSigner, + type P256PublicKey, + p256SignerIdentity, + privateKeyToP256FrameSigner, + signP256FrameSignature, +} from './p256.js' export { SECP256K1_N, SECP256R1_N, diff --git a/src/p256.ts b/src/p256.ts new file mode 100644 index 0000000..4df7eb1 --- /dev/null +++ b/src/p256.ts @@ -0,0 +1,148 @@ +import { + type Address, + type Hex, + concatHex, + getAddress, + isAddressEqual, + keccak256, + numberToHex, + size, + sliceHex, +} from 'viem' +import * as P256 from 'ox/P256' +import { sameAddress } from './envelope.js' +import { FrameEncodeError } from './errors.js' +import { frameTxSigHash } from './sighash.js' +import { SECP256R1_N, assertCanonicalSignature } from './signatures.js' +import type { FrameTransaction } from './types.js' + +export type P256PublicKey = { + qx: Hex + qy: Hex +} + +export type P256FrameSigner = { + /** `last20Bytes(keccak256(qx || qy))`. */ + address: Address + publicKey: P256PublicKey + /** Sign an already-hashed 32-byte digest without hashing it again. */ + sign: (parameters: { hash: Hex }) => Promise<{ r: bigint; s: bigint }> +} + +function assertBytes32(value: Hex, label: string): void { + if (size(value) !== 32) + throw new FrameEncodeError(`${label} must be exactly 32 bytes`) +} + +function oxPublicKey(publicKey: P256PublicKey) { + assertBytes32(publicKey.qx, 'P-256 qx') + assertBytes32(publicKey.qy, 'P-256 qy') + const value = { + prefix: 4 as const, + x: BigInt(publicKey.qx), + y: BigInt(publicKey.qy), + } + + try { + P256.noble.ProjectivePoint.fromHex( + concatHex(['0x04', publicKey.qx, publicKey.qy]).slice(2), + ) + } catch { + throw new FrameEncodeError('P-256 public key is not a point on the curve') + } + return value +} + +/** Derive the EIP-8141 P-256 signer identity from its public coordinates. */ +export function p256SignerIdentity(publicKey: P256PublicKey): Address { + oxPublicKey(publicKey) + return getAddress(sliceHex(keccak256(concatHex([publicKey.qx, publicKey.qy])), 12)) +} + +/** Create a raw-digest P-256 signer from a 32-byte private scalar. */ +export function privateKeyToP256FrameSigner(privateKey: Hex): P256FrameSigner { + assertBytes32(privateKey, 'P-256 private key') + + let point: ReturnType + try { + point = P256.getPublicKey({ privateKey }) + } catch { + throw new FrameEncodeError('P-256 private key is not a valid scalar') + } + + const publicKey = { + qx: numberToHex(point.x, { size: 32 }), + qy: numberToHex(point.y, { size: 32 }), + } satisfies P256PublicKey + + return { + address: p256SignerIdentity(publicKey), + publicKey, + async sign({ hash }) { + assertBytes32(hash, 'P-256 signing hash') + // The frame sig-hash is already a digest. `hash` is deliberately omitted, + // otherwise Ox would SHA-256 it again before ECDSA signing. + const { r, s } = P256.sign({ + payload: hash, + privateKey, + extraEntropy: false, + }) + return { r, s } + }, + } +} + +/** Sign one empty-message P-256 entry without changing any other signature. */ +export async function signP256FrameSignature( + transaction: FrameTransaction, + index: number, + signer: P256FrameSigner, +): Promise { + const entry = transaction.signatures[index] + if (entry === undefined) + throw new FrameEncodeError(`no signature at index ${index}`) + if (entry.scheme !== 2 || entry.msg !== '0x') + throw new FrameEncodeError( + `signature ${index}: slot signing requires P256 with an empty msg`, + ) + + const derivedIdentity = p256SignerIdentity(signer.publicKey) + if (!isAddressEqual(derivedIdentity, signer.address)) + throw new FrameEncodeError( + `P-256 signer address ${signer.address} does not match public key identity ${derivedIdentity}`, + ) + + const resolvedSigner = entry.signer ?? transaction.sender + if (!sameAddress(resolvedSigner, signer.address)) + throw new FrameEncodeError( + `signature ${index}: resolved signer ${resolvedSigner} does not match ` + + `the P-256 signer ${signer.address}`, + ) + + const hash = frameTxSigHash(transaction) + const signed = await signer.sign({ hash }) + if (signed.r <= 0n || signed.r >= SECP256R1_N) + throw new FrameEncodeError(`signature ${index}: signer returned r outside (0, n)`) + if (signed.s <= 0n || signed.s >= SECP256R1_N) + throw new FrameEncodeError(`signature ${index}: signer returned s outside (0, n)`) + + const s = signed.s > SECP256R1_N / 2n ? SECP256R1_N - signed.s : signed.s + const publicKey = oxPublicKey(signer.publicKey) + if (!P256.verify({ payload: hash, publicKey, signature: { r: signed.r, s } })) + throw new FrameEncodeError( + `signature ${index}: signer returned a signature that does not verify against its public key`, + ) + + const signature = concatHex([ + numberToHex(signed.r, { size: 32 }), + numberToHex(s, { size: 32 }), + signer.publicKey.qx, + signer.publicKey.qy, + ]) + const signedEntry = { ...entry, signature } + assertCanonicalSignature(signedEntry, index) + + const signatures = [...transaction.signatures] + signatures[index] = signedEntry + return { ...transaction, signatures } +} diff --git a/test/p256.test.ts b/test/p256.test.ts new file mode 100644 index 0000000..25fa0e0 --- /dev/null +++ b/test/p256.test.ts @@ -0,0 +1,190 @@ +import { describe, expect, test } from 'vitest' +import { + concatHex, + createClient, + custom, + getAddress, + numberToHex, + sliceHex, +} from 'viem' +import { mainnet } from 'viem/chains' +import * as P256 from 'ox/P256' +import { toP256FrameAccount } from '../src/accounts/toP256FrameAccount.js' +import { FrameEncodeError } from '../src/errors.js' +import { + type P256FrameSigner, + p256SignerIdentity, + privateKeyToP256FrameSigner, + signP256FrameSignature, +} from '../src/p256.js' +import { frameTxSigHash } from '../src/sighash.js' +import { SECP256R1_N, assertCanonicalSignature } from '../src/signatures.js' +import { GOLDEN_TX } from './fixtures/golden.js' + +const PRIVATE_KEY = numberToHex(1n, { size: 32 }) +const DELEGATED_EOA = getAddress('0x0000000000000000000000000000000000001234') + +describe('P-256 signer identity', () => { + test('private scalar 1 derives the published P-256 generator coordinates', () => { + const signer = privateKeyToP256FrameSigner(PRIVATE_KEY) + + expect(signer.publicKey.qx).toBe( + '0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296', + ) + expect(signer.publicKey.qy).toBe( + '0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5', + ) + }) + + test('derives the independently pinned last-20-byte keccak identity', () => { + const signer = privateKeyToP256FrameSigner(PRIVATE_KEY) + + expect(signer.address.toLowerCase()).toBe( + '0xd3a9f047ad43d7e2e4e7e491f1fe2e657a2651b6', + ) + expect(p256SignerIdentity(signer.publicKey)).toBe(signer.address) + }) + + test('rejects a public key that is not on P-256', () => { + expect(() => + p256SignerIdentity({ + qx: numberToHex(1n, { size: 32 }), + qy: numberToHex(1n, { size: 32 }), + }), + ).toThrow(/not a point on the curve/) + }) +}) + +describe('signP256FrameSignature', () => { + test('signs the raw frame sig-hash as r || s || qx || qy', async () => { + const signer = privateKeyToP256FrameSigner(PRIVATE_KEY) + const unsigned = { + ...GOLDEN_TX, + sender: DELEGATED_EOA, + signatures: [ + { + scheme: 2 as const, + signer: signer.address, + msg: '0x' as const, + signature: '0x' as const, + }, + ], + } + const hash = frameTxSigHash(unsigned) + const signed = await signP256FrameSignature(unsigned, 0, signer) + const bytes = signed.signatures[0]!.signature + + expect(bytes.length).toBe(2 + 128 * 2) + expect(sliceHex(bytes, 64, 96)).toBe(signer.publicKey.qx) + expect(sliceHex(bytes, 96, 128)).toBe(signer.publicKey.qy) + expect(() => assertCanonicalSignature(signed.signatures[0]!, 0)).not.toThrow() + + const signature = { + r: BigInt(sliceHex(bytes, 0, 32)), + s: BigInt(sliceHex(bytes, 32, 64)), + } + const publicKey = { + prefix: 4 as const, + x: BigInt(signer.publicKey.qx), + y: BigInt(signer.publicKey.qy), + } + expect(P256.verify({ payload: hash, publicKey, signature })).toBe(true) + expect(P256.verify({ payload: hash, publicKey, signature, hash: true })).toBe(false) + }) + + test('normalizes a valid high-s signer response', async () => { + const base = privateKeyToP256FrameSigner(PRIVATE_KEY) + const signer: P256FrameSigner = { + ...base, + async sign(parameters) { + const signature = await base.sign(parameters) + return { ...signature, s: SECP256R1_N - signature.s } + }, + } + const unsigned = { + ...GOLDEN_TX, + sender: DELEGATED_EOA, + signatures: [ + { scheme: 2 as const, signer: signer.address, msg: '0x' as const, signature: '0x' as const }, + ], + } + const signed = await signP256FrameSignature(unsigned, 0, signer) + const s = BigInt(sliceHex(signed.signatures[0]!.signature, 32, 64)) + + expect(s).toBeLessThanOrEqual(SECP256R1_N / 2n) + }) + + test('rejects a signer response that does not verify', async () => { + const base = privateKeyToP256FrameSigner(PRIVATE_KEY) + const signer: P256FrameSigner = { + ...base, + async sign() { + return { r: 1n, s: 1n } + }, + } + const unsigned = { + ...GOLDEN_TX, + sender: DELEGATED_EOA, + signatures: [ + { scheme: 2 as const, signer: signer.address, msg: '0x' as const, signature: '0x' as const }, + ], + } + + await expect(signP256FrameSignature(unsigned, 0, signer)).rejects.toThrow( + /does not verify/, + ) + }) +}) + +describe('toP256FrameAccount', () => { + test('prepares and signs scheme-2 entry zero for a delegated EOA', async () => { + const signer = privateKeyToP256FrameSigner(PRIVATE_KEY) + const client = createClient({ + chain: mainnet, + transport: custom({ async request() {} }), + }) + const account = await toP256FrameAccount({ + client, + address: DELEGATED_EOA, + signer, + }) + const entries = await account.getSignatureEntries(GOLDEN_TX) + const unsigned = { + ...GOLDEN_TX, + sender: DELEGATED_EOA, + signatures: [...entries], + } + const signed = await account.signFrameTransaction(unsigned) + + expect(account.address).toBe(DELEGATED_EOA) + expect(signed.signatures[0]).toMatchObject({ + scheme: 2, + signer: signer.address, + msg: '0x', + }) + expect(signed.signatures[0]!.signature).toBe( + concatHex([ + sliceHex(signed.signatures[0]!.signature, 0, 64), + signer.publicKey.qx, + signer.publicKey.qy, + ]), + ) + }) + + test('rejects a transaction for a different sender', async () => { + const signer = privateKeyToP256FrameSigner(PRIVATE_KEY) + const client = createClient({ + chain: mainnet, + transport: custom({ async request() {} }), + }) + const account = await toP256FrameAccount({ + client, + address: DELEGATED_EOA, + signer, + }) + + await expect(account.signFrameTransaction(GOLDEN_TX)).rejects.toThrow( + FrameEncodeError, + ) + }) +}) From 288a7ce7ec34a9de50769c3d86f1b1ab976f1fb4 Mon Sep 17 00:00:00 2001 From: Ghadi Mhawej Date: Mon, 5 Oct 2026 11:24:35 +0300 Subject: [PATCH 6/8] fix(deps): ship ox as a runtime dependency src/p256.ts imports ox/P256 at runtime, but ox was only a devDependency, so tsup inlined ox and its @noble/curves and @noble/hashes code into dist (dist/index.js 11.4 KB -> 109.7 KB). Declaring it as a dependency keeps it external; ^0.14.45 matches the version viem already resolves, so installs dedupe to a single copy. --- bun.lock | 4 +++- package.json | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/bun.lock b/bun.lock index 339709f..802c88a 100644 --- a/bun.lock +++ b/bun.lock @@ -4,11 +4,13 @@ "workspaces": { "": { "name": "frames-ts", + "dependencies": { + "ox": "^0.14.45", + }, "devDependencies": { "@semantic-release/changelog": "^7.0.0", "@semantic-release/git": "^11.0.1", "@types/node": "^20.16.0", - "ox": "0.14.44", "semantic-release": "^25.0.9", "tsup": "^8.5.1", "tsx": "^4.19.0", diff --git a/package.json b/package.json index f21d06e..79e4048 100644 --- a/package.json +++ b/package.json @@ -73,6 +73,9 @@ "test:watch": "vitest", "typecheck": "tsc --noEmit" }, + "dependencies": { + "ox": "^0.14.45" + }, "peerDependencies": { "viem": "^2.21.0" }, @@ -80,7 +83,6 @@ "@semantic-release/changelog": "^7.0.0", "@semantic-release/git": "^11.0.1", "@types/node": "^20.16.0", - "ox": "0.14.44", "semantic-release": "^25.0.9", "tsup": "^8.5.1", "tsx": "^4.19.0", From 5af36cbf086297b2a9afd765f10802ce82eab049 Mon Sep 17 00:00:00 2001 From: nikhil kumar Date: Thu, 8 Oct 2026 01:38:58 +0530 Subject: [PATCH 7/8] feat: unify P-256 signing across frame accounts and payers --- README.md | 33 +++-- scripts/send-eth-p256.ts | 16 +-- src/accounts/toP256FrameAccount.ts | 30 ++-- src/accounts/types.ts | 7 +- src/index.ts | 6 +- src/p256.ts | 114 ++++------------ src/signatures.ts | 211 +++++++++++++++++++---------- test/accounts.test.ts | 32 ++++- test/p256.test.ts | 78 ++++++----- test/signatures.test.ts | 79 ++++++++--- 10 files changed, 360 insertions(+), 246 deletions(-) diff --git a/README.md b/README.md index 6d6ce5c..686f473 100644 --- a/README.md +++ b/README.md @@ -80,22 +80,23 @@ assertValidFrameTx(signed) const raw = encodeFrameTx(signed) ``` -`signFrameTx` also takes a `FrameSigner` instead of a key — anything with an `address` and a -raw-digest `sign`, which covers viem's `privateKeyToAccount` and `mnemonicToAccount`, a -`toAccount` source, and your own wrapper around a hardware wallet, an HSM or a remote -signer. It signs every SECP256K1 entry whose `msg` is empty, and refuses if the entry's -resolved signer is not that account's address. +`signFrameTx` also takes a `FrameAccountOwner` instead of a key. This includes viem's +`privateKeyToAccount` and `mnemonicToAccount`, a `toAccount` source, the tagged owner from +`privateKeyToP256Account`, and viem accounts backed by hardware wallets, HSMs or remote signers. +It signs every ECDSA entry whose `msg` is empty and refuses if either the signature scheme +or resolved signer does not match the supplied owner. ```ts -import { privateKeyToAccount } from 'viem/accounts' +import { privateKeyToAccount, toAccount } from 'viem/accounts' const signed = await signFrameTx(tx, privateKeyToAccount(privateKey)) -// a remote signer needs nothing else: -const signed = await signFrameTx(tx, { +// Wrap a remote signer as a viem Account: +const remoteAccount = toAccount({ address: '0x…', sign: ({ hash }) => myKms.signDigest(hash), // r||s||v, v as 27/28 or a bare 0/1 }) +const signed = await signFrameTx(tx, remoteAccount) ``` A raw-digest `sign` is required. `signMessage` will not do: it EIP-191-prefixes its @@ -103,9 +104,15 @@ argument, so the signature recovers to nothing. A `JsonRpcAccount` (a browser wa cannot sign a raw digest at all — both are refused with an error rather than producing a transaction the chain silently rejects. +The same restriction applies to P-256 signers. WebCrypto's ECDSA API hashes its input +internally, so passing the frame sig-hash to it signs `SHA-256(frameSigHash)`, not the +frame sig-hash itself. Passkeys/WebAuthn sign authenticator data and client data rather +than an arbitrary 32-byte digest. Use a P-256 backend that explicitly supports raw or +prehashed ECDSA digests; `privateKeyToP256Account` does so for a local private scalar. + ARBITRARY entries are left untouched; build those signatures yourself and let -`assertValidFrameTx` check them. The low-level `signFrameTx` handles one secp256k1 signer -at a time; `signFrameTransaction` coordinates a sender and an optional +`assertValidFrameTx` check them. The low-level `signFrameTx` handles one owner and +signature scheme at a time; `signFrameTransaction` coordinates a sender and an optional `FramePayerAccount`. For an EIP-7702 delegated account authorized by P-256, create a signer from its raw @@ -115,15 +122,15 @@ as `r || s || qx || qy`. ```ts import { - privateKeyToP256FrameSigner, + privateKeyToP256Account, toP256FrameAccount, } from '@jaw.id/frametx-kit' -const signer = privateKeyToP256FrameSigner(p256PrivateKey) +const owner = privateKeyToP256Account(p256PrivateKey) const account = await toP256FrameAccount({ client, address: delegatedEoa, - signer, + owner, }) ``` diff --git a/scripts/send-eth-p256.ts b/scripts/send-eth-p256.ts index 6a5c33f..ca8356e 100644 --- a/scripts/send-eth-p256.ts +++ b/scripts/send-eth-p256.ts @@ -29,7 +29,7 @@ import { import { hegotaTestnet, parseRpcFrameReceipt, - privateKeyToP256FrameSigner, + privateKeyToP256Account, sendFrameTransaction, toP256FrameAccount, type FrameRpcClient, @@ -92,17 +92,17 @@ async function main(): Promise { const sender = getAddress(requiredEnv('SENDER')) const recipient = getAddress(requiredEnv('RECIPIENT')) const amount = parseEther(process.env.AMOUNT_ETH ?? '0.000001') - const signer = privateKeyToP256FrameSigner( + const owner = privateKeyToP256Account( loadP256PrivateKey(requiredEnv('P256_PRIVATE_KEY_PATH')), ) const expectedIdentity = process.env.P256_SIGNER_IDENTITY if ( expectedIdentity !== undefined && - !isAddressEqual(signer.address, getAddress(expectedIdentity)) + !isAddressEqual(owner.address, getAddress(expectedIdentity)) ) throw new Error( - `PEM signer identity ${signer.address} does not match P256_SIGNER_IDENTITY ${expectedIdentity}`, + `PEM signer identity ${owner.address} does not match P256_SIGNER_IDENTITY ${expectedIdentity}`, ) const client = createPublicClient({ @@ -124,12 +124,12 @@ async function main(): Promise { functionName: 'p256Signer', data: signerCall.data, }) - if (!isAddressEqual(configuredSigner, signer.address)) + if (!isAddressEqual(configuredSigner, owner.address)) throw new Error( - `delegated account authorizes ${configuredSigner}, but the PEM identity is ${signer.address}`, + `delegated account authorizes ${configuredSigner}, but the PEM identity is ${owner.address}`, ) - const account = await toP256FrameAccount({ client, address: sender, signer }) + const account = await toP256FrameAccount({ client, address: sender, owner }) const [senderBalanceBefore, recipientBalanceBefore] = await Promise.all([ client.getBalance({ address: sender }), client.getBalance({ address: recipient }), @@ -138,7 +138,7 @@ async function main(): Promise { console.log(`sender: ${sender}`) console.log(`recipient: ${recipient}`) console.log(`amount: ${formatEther(amount)} ETH`) - console.log(`P-256 signer: ${signer.address}`) + console.log(`P-256 signer: ${owner.address}`) const submittedHash = await sendFrameTransaction( account, diff --git a/src/accounts/toP256FrameAccount.ts b/src/accounts/toP256FrameAccount.ts index c149b0b..785ddb4 100644 --- a/src/accounts/toP256FrameAccount.ts +++ b/src/accounts/toP256FrameAccount.ts @@ -9,47 +9,49 @@ import { } from 'viem' import { FrameEncodeError } from '../errors.js' import { getFrameNonceSeq } from '../nonce.js' -import { - type P256FrameSigner, - signP256FrameSignature, -} from '../p256.js' +import type { P256FrameSigner } from '../p256.js' +import { signFrameSignature } from '../signatures.js' import type { FrameTransaction } from '../types.js' import { toFrameAccount } from './toFrameAccount.js' import type { FrameAccount, FrameAccountImplementation } from './types.js' export type P256FrameAccountImplementation< chain extends Chain | undefined = Chain | undefined, + owner extends P256FrameSigner = P256FrameSigner, extend extends object = object, -> = FrameAccountImplementation +> = FrameAccountImplementation export type ToP256FrameAccountParameters< chain extends Chain | undefined = Chain | undefined, + owner extends P256FrameSigner = P256FrameSigner, extend extends object = object, > = { client: Client /** EIP-7702 delegated EOA represented by this frame account. */ address: Address - signer: P256FrameSigner + owner: owner extend?: extend | undefined } export type ToP256FrameAccountReturnType< chain extends Chain | undefined = Chain | undefined, + owner extends P256FrameSigner = P256FrameSigner, extend extends object = object, -> = FrameAccount> +> = FrameAccount> /** Create a direct-execution frame account authorized by a P-256 signer. */ export async function toP256FrameAccount< chain extends Chain | undefined, + owner extends P256FrameSigner, extend extends object = object, >( - parameters: ToP256FrameAccountParameters, -): Promise> { - const { address, client, signer } = parameters + parameters: ToP256FrameAccountParameters, +): Promise> { + const { address, client, owner } = parameters return toFrameAccount({ client, - owner: undefined, + owner, execution: { type: 'direct' }, ...(parameters.extend === undefined ? {} : { extend: parameters.extend }), async getAddress() { @@ -65,7 +67,7 @@ export async function toP256FrameAccount< return [ { scheme: 2, - signer: signer.address, + signer: owner.address, msg: '0x', signature: '0x', }, @@ -84,7 +86,7 @@ export async function toP256FrameAccount< signatures: [ { scheme: 2 as const, - signer: signer.address, + signer: owner.address, msg: '0x' as const, signature: '0x' as const, }, @@ -92,7 +94,7 @@ export async function toP256FrameAccount< } : transaction - return signP256FrameSignature(prepared, 0, signer) + return signFrameSignature(prepared, 0, owner) }, }) } diff --git a/src/accounts/types.ts b/src/accounts/types.ts index 98ceadb..87aa75f 100644 --- a/src/accounts/types.ts +++ b/src/accounts/types.ts @@ -14,6 +14,9 @@ import type { FrameSignature, FrameTransaction, } from '../types.js' +import type { P256FrameSigner } from '../p256.js' + +export type FrameAccountOwner = Account | P256FrameSigner export type FrameCall = { to: Address @@ -40,7 +43,7 @@ export type DirectFrameExecution = { } export type FramePayerAccountImplementation< - owner extends Account | undefined = Account | undefined, + owner extends FrameAccountOwner | undefined = FrameAccountOwner | undefined, extend extends object = object, > = { /** Account or signer that controls the payer. */ @@ -73,7 +76,7 @@ export type FramePaymasterParameters< /** Account-specific behavior required to construct and sign frame transactions. */ export type FrameAccountImplementation< chain extends Chain | undefined = Chain | undefined, - owner extends Account | undefined = Account | undefined, + owner extends FrameAccountOwner | undefined = FrameAccountOwner | undefined, extend extends object = object, > = { /** Client used to read account and nonce state. */ diff --git a/src/index.ts b/src/index.ts index 5478b19..4cf2825 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,6 +5,7 @@ export { type DirectFrameExecution, type FrameAccount, type FrameAccountImplementation, + type FrameAccountOwner, type FrameCall, type FramePaymasterParameters, type FramePayerAccount, @@ -77,15 +78,12 @@ export { export { frameTxSigHash } from './sighash.js' export { type P256FrameSigner, - type P256PublicKey, p256SignerIdentity, - privateKeyToP256FrameSigner, - signP256FrameSignature, + privateKeyToP256Account, } from './p256.js' export { SECP256K1_N, SECP256R1_N, - type FrameSigner, assertCanonicalSignature, assertValidFrameTx, recoverFrameSigner, diff --git a/src/p256.ts b/src/p256.ts index 4df7eb1..dd284ff 100644 --- a/src/p256.ts +++ b/src/p256.ts @@ -3,30 +3,22 @@ import { type Hex, concatHex, getAddress, - isAddressEqual, keccak256, numberToHex, size, sliceHex, } from 'viem' import * as P256 from 'ox/P256' -import { sameAddress } from './envelope.js' import { FrameEncodeError } from './errors.js' -import { frameTxSigHash } from './sighash.js' -import { SECP256R1_N, assertCanonicalSignature } from './signatures.js' -import type { FrameTransaction } from './types.js' - -export type P256PublicKey = { - qx: Hex - qy: Hex -} export type P256FrameSigner = { + type: 'p256' /** `last20Bytes(keccak256(qx || qy))`. */ address: Address - publicKey: P256PublicKey - /** Sign an already-hashed 32-byte digest without hashing it again. */ - sign: (parameters: { hash: Hex }) => Promise<{ r: bigint; s: bigint }> + /** Uncompressed SEC1 public key encoded as `0x04 || qx || qy`. */ + publicKey: Hex + /** Sign an already-hashed 32-byte digest as `r || s` without hashing it again. */ + sign: (parameters: { hash: Hex }) => Promise } function assertBytes32(value: Hex, label: string): void { @@ -34,33 +26,35 @@ function assertBytes32(value: Hex, label: string): void { throw new FrameEncodeError(`${label} must be exactly 32 bytes`) } -function oxPublicKey(publicKey: P256PublicKey) { - assertBytes32(publicKey.qx, 'P-256 qx') - assertBytes32(publicKey.qy, 'P-256 qy') +function oxPublicKey(publicKey: Hex) { + if (size(publicKey) !== 65 || sliceHex(publicKey, 0, 1) !== '0x04') + throw new FrameEncodeError( + 'P-256 public key must be 65-byte uncompressed SEC1 data (0x04 || qx || qy)', + ) + const qx = sliceHex(publicKey, 1, 33) + const qy = sliceHex(publicKey, 33, 65) const value = { prefix: 4 as const, - x: BigInt(publicKey.qx), - y: BigInt(publicKey.qy), + x: BigInt(qx), + y: BigInt(qy), } try { - P256.noble.ProjectivePoint.fromHex( - concatHex(['0x04', publicKey.qx, publicKey.qy]).slice(2), - ) + P256.noble.ProjectivePoint.fromHex(publicKey.slice(2)) } catch { throw new FrameEncodeError('P-256 public key is not a point on the curve') } return value } -/** Derive the EIP-8141 P-256 signer identity from its public coordinates. */ -export function p256SignerIdentity(publicKey: P256PublicKey): Address { +/** Derive the EIP-8141 P-256 signer identity from an uncompressed public key. */ +export function p256SignerIdentity(publicKey: Hex): Address { oxPublicKey(publicKey) - return getAddress(sliceHex(keccak256(concatHex([publicKey.qx, publicKey.qy])), 12)) + return getAddress(sliceHex(keccak256(sliceHex(publicKey, 1)), 12)) } /** Create a raw-digest P-256 signer from a 32-byte private scalar. */ -export function privateKeyToP256FrameSigner(privateKey: Hex): P256FrameSigner { +export function privateKeyToP256Account(privateKey: Hex): P256FrameSigner { assertBytes32(privateKey, 'P-256 private key') let point: ReturnType @@ -70,12 +64,14 @@ export function privateKeyToP256FrameSigner(privateKey: Hex): P256FrameSigner { throw new FrameEncodeError('P-256 private key is not a valid scalar') } - const publicKey = { - qx: numberToHex(point.x, { size: 32 }), - qy: numberToHex(point.y, { size: 32 }), - } satisfies P256PublicKey + const publicKey = concatHex([ + '0x04', + numberToHex(point.x, { size: 32 }), + numberToHex(point.y, { size: 32 }), + ]) return { + type: 'p256', address: p256SignerIdentity(publicKey), publicKey, async sign({ hash }) { @@ -87,62 +83,10 @@ export function privateKeyToP256FrameSigner(privateKey: Hex): P256FrameSigner { privateKey, extraEntropy: false, }) - return { r, s } + return concatHex([ + numberToHex(r, { size: 32 }), + numberToHex(s, { size: 32 }), + ]) }, } } - -/** Sign one empty-message P-256 entry without changing any other signature. */ -export async function signP256FrameSignature( - transaction: FrameTransaction, - index: number, - signer: P256FrameSigner, -): Promise { - const entry = transaction.signatures[index] - if (entry === undefined) - throw new FrameEncodeError(`no signature at index ${index}`) - if (entry.scheme !== 2 || entry.msg !== '0x') - throw new FrameEncodeError( - `signature ${index}: slot signing requires P256 with an empty msg`, - ) - - const derivedIdentity = p256SignerIdentity(signer.publicKey) - if (!isAddressEqual(derivedIdentity, signer.address)) - throw new FrameEncodeError( - `P-256 signer address ${signer.address} does not match public key identity ${derivedIdentity}`, - ) - - const resolvedSigner = entry.signer ?? transaction.sender - if (!sameAddress(resolvedSigner, signer.address)) - throw new FrameEncodeError( - `signature ${index}: resolved signer ${resolvedSigner} does not match ` + - `the P-256 signer ${signer.address}`, - ) - - const hash = frameTxSigHash(transaction) - const signed = await signer.sign({ hash }) - if (signed.r <= 0n || signed.r >= SECP256R1_N) - throw new FrameEncodeError(`signature ${index}: signer returned r outside (0, n)`) - if (signed.s <= 0n || signed.s >= SECP256R1_N) - throw new FrameEncodeError(`signature ${index}: signer returned s outside (0, n)`) - - const s = signed.s > SECP256R1_N / 2n ? SECP256R1_N - signed.s : signed.s - const publicKey = oxPublicKey(signer.publicKey) - if (!P256.verify({ payload: hash, publicKey, signature: { r: signed.r, s } })) - throw new FrameEncodeError( - `signature ${index}: signer returned a signature that does not verify against its public key`, - ) - - const signature = concatHex([ - numberToHex(signed.r, { size: 32 }), - numberToHex(s, { size: 32 }), - signer.publicKey.qx, - signer.publicKey.qy, - ]) - const signedEntry = { ...entry, signature } - assertCanonicalSignature(signedEntry, index) - - const signatures = [...transaction.signatures] - signatures[index] = signedEntry - return { ...transaction, signatures } -} diff --git a/src/signatures.ts b/src/signatures.ts index 8996f90..0f0072e 100644 --- a/src/signatures.ts +++ b/src/signatures.ts @@ -1,7 +1,22 @@ -import { type Address, type Hex, recoverAddress, sliceHex } from 'viem' +import { + type Account, + type Address, + type Hex, + concatHex, + numberToHex, + recoverAddress, + size, + sliceHex, +} from 'viem' import { privateKeyToAccount } from 'viem/accounts' +import * as P256 from 'ox/P256' +import type { FrameAccountOwner } from './accounts/types.js' import { sameAddress, validateFrameTx } from './envelope.js' import { FrameEncodeError, FrameRlpError } from './errors.js' +import { + type P256FrameSigner, + p256SignerIdentity, +} from './p256.js' import { byteLength } from './rlp.js' import { frameTxSigHash } from './sighash.js' import type { FrameSignature, FrameTransaction } from './types.js' @@ -130,62 +145,146 @@ function bareRecoveryId(v: bigint, index: number): bigint { ) } -/** - * Anything that can sign a raw 32-byte digest for a known address: viem's - * `privateKeyToAccount` and `mnemonicToAccount`, a `toAccount` source, or a - * hand-rolled wrapper around a hardware wallet, an HSM or a remote signer. - * - * `sign` is optional because it is optional on viem's own `LocalAccount` — a - * `toAccount` source need not provide it — so requiring it here would reject - * every `LocalAccount` at the type level. `signFrameTx` checks for it instead. - * - * `signMessage` is deliberately not an accepted substitute: it prefixes its - * argument per EIP-191, so it cannot produce a signature over a sig-hash. - */ -export type FrameSigner = { - address: Address - sign?: ((parameters: { hash: Hex }) => Promise) | undefined +function resolveFrameSigner(signer: Hex | FrameAccountOwner): FrameAccountOwner { + return typeof signer === 'string' ? privateKeyToAccount(signer) : signer } -function resolveFrameSigner(signer: Hex | FrameSigner): FrameSigner { - return typeof signer === 'string' ? privateKeyToAccount(signer) : signer +function signerScheme(signer: FrameAccountOwner): 1 | 2 { + return signer.type === 'p256' ? 2 : 1 } -/** Sign one empty-message SECP256K1 entry without requiring other entries to be complete. */ -export async function signFrameSignature( +function schemeName(scheme: number): string { + if (scheme === 1) return 'SECP256K1' + if (scheme === 2) return 'P256' + return 'ARBITRARY' +} + +function assertSignerMatches( tx: FrameTransaction, index: number, - signer: Hex | FrameSigner, -): Promise { - const account = resolveFrameSigner(signer) - if (typeof account.sign !== 'function') + signer: FrameAccountOwner, +): void { + const resolvedSigner = resolveSigner(tx, index) + if (!sameAddress(resolvedSigner, signer.address)) throw new FrameEncodeError( - `account ${account.address} cannot sign a raw 32-byte digest: it has no ` + + `signature ${index}: resolved signer ${resolvedSigner} does not match ` + + `the signing account ${signer.address}`, + ) +} + +async function signSecp256k1Entry( + tx: FrameTransaction, + index: number, + signer: Account, + digest: Hex, +): Promise { + if (typeof signer.sign !== 'function') + throw new FrameEncodeError( + `account ${signer.address} cannot sign a raw 32-byte digest: it has no ` + '`sign` method. A JSON-RPC account cannot sign one at all, and ' + '`signMessage` is not a substitute — it EIP-191-prefixes its argument.', ) + assertSignerMatches(tx, index, signer) + const entry = tx.signatures[index]! + const flat = await signer.sign({ hash: digest }) + const r = sliceHex(flat, 0, 32) + const s = sliceHex(flat, 32, 64) + const v = bareRecoveryId(BigInt(sliceHex(flat, 64, 65)), index) + const signature = `0x${v.toString(16).padStart(2, '0')}${r.slice(2)}${s.slice(2)}` as Hex + return { ...entry, signature } +} + +async function signP256Entry( + tx: FrameTransaction, + index: number, + signer: P256FrameSigner, + digest: Hex, +): Promise { + const derivedIdentity = p256SignerIdentity(signer.publicKey) + if (!sameAddress(derivedIdentity, signer.address)) + throw new FrameEncodeError( + `P-256 signer address ${signer.address} does not match public key identity ${derivedIdentity}`, + ) + + assertSignerMatches(tx, index, signer) + const entry = tx.signatures[index]! + const compactSignature = await signer.sign({ hash: digest }) + if (size(compactSignature) !== 64) + throw new FrameEncodeError( + `signature ${index}: P-256 signer must return exactly 64 bytes (r || s)`, + ) + const r = BigInt(sliceHex(compactSignature, 0, 32)) + const returnedS = BigInt(sliceHex(compactSignature, 32, 64)) + if (r <= 0n || r >= SECP256R1_N) + throw new FrameEncodeError(`signature ${index}: signer returned r outside (0, n)`) + if (returnedS <= 0n || returnedS >= SECP256R1_N) + throw new FrameEncodeError(`signature ${index}: signer returned s outside (0, n)`) + + const s = returnedS > SECP256R1_N / 2n ? SECP256R1_N - returnedS : returnedS + const publicKey = { + prefix: 4 as const, + x: BigInt(sliceHex(signer.publicKey, 1, 33)), + y: BigInt(sliceHex(signer.publicKey, 33, 65)), + } + if (!P256.verify({ payload: digest, publicKey, signature: { r, s } })) + throw new FrameEncodeError( + `signature ${index}: signer returned a signature that does not verify against its public key`, + ) + + return { + ...entry, + signature: concatHex([ + numberToHex(r, { size: 32 }), + numberToHex(s, { size: 32 }), + sliceHex(signer.publicKey, 1), + ]), + } +} + +async function signFrameEntry( + tx: FrameTransaction, + index: number, + signer: FrameAccountOwner, + digest: Hex, +): Promise { const entry = tx.signatures[index] if (entry === undefined) throw new FrameEncodeError(`no signature at index ${index}`) - if (entry.scheme !== 1 || entry.msg !== '0x') + if (entry.msg !== '0x' || entry.scheme === 0) throw new FrameEncodeError( - `signature ${index}: slot signing requires SECP256K1 with an empty msg`, + `signature ${index}: slot signing requires SECP256K1 or P256 with an empty msg`, ) - const resolvedSigner = entry.signer ?? tx.sender - if (!sameAddress(resolvedSigner, account.address)) + const ownerScheme = signerScheme(signer) + if (entry.scheme !== ownerScheme) throw new FrameEncodeError( - `signature ${index}: resolved signer ${resolvedSigner} does not match ` + - `the signing account ${account.address}`, + `signature ${index}: ${schemeName(entry.scheme)} entry cannot be signed by ` + + `a ${schemeName(ownerScheme)} owner`, ) - const flat = await account.sign({ hash: frameTxSigHash(tx) }) - const r = sliceHex(flat, 0, 32) - const s = sliceHex(flat, 32, 64) - const v = bareRecoveryId(BigInt(sliceHex(flat, 64, 65)), index) - const signature = `0x${v.toString(16).padStart(2, '0')}${r.slice(2)}${s.slice(2)}` as Hex - const signedEntry = { ...entry, signature } + return ownerScheme === 2 + ? signP256Entry(tx, index, signer as P256FrameSigner, digest) + : signSecp256k1Entry(tx, index, signer as Account, digest) +} + +/** Sign one empty-message SECP256K1 or P256 entry. */ +export async function signFrameSignature( + tx: FrameTransaction, + index: number, + signer: Hex | FrameAccountOwner, +): Promise { + const account = resolveFrameSigner(signer) + + const entry = tx.signatures[index] + if (entry === undefined) + throw new FrameEncodeError(`no signature at index ${index}`) + const signedEntry = await signFrameEntry( + tx, + index, + account, + frameTxSigHash(tx), + ) assertCanonicalSignature(signedEntry, index) const signatures = [...tx.signatures] @@ -194,50 +293,26 @@ export async function signFrameSignature( } /** - * Sign every empty-`msg` SECP256K1 entry over the transaction's sig-hash. + * Sign every empty-`msg` SECP256K1 or P256 entry over the transaction's sig-hash. * - * Takes either a raw private key or a `FrameSigner` — a hardware wallet, a - * KMS, an HD account, anything that signs a digest for a known address. + * Takes either a raw private key or a `FrameAccountOwner`. A secp256k1 owner + * must be a viem `Account`; a P-256 owner is created by + * `privateKeyToP256Account` or implements the same interface. * * Idempotent: the sig-hash elides empty-`msg` signature bytes, so re-signing an * already-signed transaction produces the same bytes. */ export async function signFrameTx( tx: FrameTransaction, - signer: Hex | FrameSigner, + signer: Hex | FrameAccountOwner, ): Promise { const account = resolveFrameSigner(signer) - if (typeof account.sign !== 'function') - throw new FrameEncodeError( - `account ${account.address} cannot sign a raw 32-byte digest: it has no ` + - `\`sign\` method. A JSON-RPC account cannot sign one at all, and ` + - `\`signMessage\` is not a substitute — it EIP-191-prefixes its argument.`, - ) - const sign = account.sign const digest = frameTxSigHash(tx) const signatures = await Promise.all( tx.signatures.map(async (sig, i) => { - if (sig.scheme !== 1 || sig.msg !== '0x') return sig - - // An entry names its own signer (or, if empty, resolves to tx.sender). Signing - // it with this key when that resolved signer is some OTHER address would - // produce a signature that recovers to the wrong address — a transaction the - // chain rejects at consensus, with no error from this library unless we check. - const resolvedSigner = sig.signer ?? tx.sender - if (!sameAddress(resolvedSigner, account.address)) - throw new FrameEncodeError( - `signature ${i}: resolved signer ${resolvedSigner} does not match ` + - `the signing account ${account.address}`, - ) - - const flat = await sign({ hash: digest }) - // viem returns r||s||v with v in {27,28}; the frame layout is v||r||s with a bare id. - const r = sliceHex(flat, 0, 32) - const s = sliceHex(flat, 32, 64) - const v = bareRecoveryId(BigInt(sliceHex(flat, 64, 65)), i) - const signature = `0x${v.toString(16).padStart(2, '0')}${r.slice(2)}${s.slice(2)}` as Hex - return { ...sig, signature } + if (sig.scheme === 0 || sig.msg !== '0x') return sig + return signFrameEntry(tx, i, account, digest) }), ) diff --git a/test/accounts.test.ts b/test/accounts.test.ts index 694292e..fdc2a88 100644 --- a/test/accounts.test.ts +++ b/test/accounts.test.ts @@ -1,12 +1,13 @@ import { describe, expect, test } from 'vitest' -import { createClient, custom, getAddress } from 'viem' +import { createClient, custom, getAddress, size } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' import { toFrameAccount } from '../src/accounts/toFrameAccount.js' import { toEoaFrameAccount } from '../src/accounts/toEoaFrameAccount.js' import { toEoaFramePayerAccount } from '../src/accounts/toEoaFramePayerAccount.js' import { toFramePayerAccount } from '../src/accounts/toFramePayerAccount.js' -import { recoverFrameSigner } from '../src/signatures.js' +import { privateKeyToP256Account } from '../src/p256.js' +import { recoverFrameSigner, signFrameSignature } from '../src/signatures.js' import type { FrameTransaction } from '../src/types.js' import { GOLDEN_TX } from './fixtures/golden.js' @@ -154,6 +155,33 @@ describe('toFramePayerAccount', () => { expect(payer.implementationName).toBe('test-payer') expect(await payer.getPayData(GOLDEN_TX)).toBe('0xabcd') }) + + test('accepts a P-256 owner and signs a payer-owned scheme-2 entry', async () => { + const owner = privateKeyToP256Account(`0x${'01'.padStart(64, '0')}`) + const payerAddress = getAddress('0x0000000000000000000000000000000000009999') + const payer = await toFramePayerAccount({ + owner, + getAddress: async () => payerAddress, + getPayData: async () => '0x', + getSignatureEntries: async () => [ + { scheme: 2, signer: owner.address, msg: '0x', signature: '0x' }, + ], + signFrameTransaction: async (transaction) => + signFrameSignature(transaction, 1, owner), + }) + const transaction = { + ...GOLDEN_TX, + signatures: [ + GOLDEN_TX.signatures[0]!, + { scheme: 2 as const, signer: owner.address, msg: '0x' as const, signature: '0x' as const }, + ], + } + + const signed = await payer.signFrameTransaction(transaction) + + expect(payer.owner).toBe(owner) + expect(size(signed.signatures[1]!.signature)).toBe(128) + }) }) describe('toEoaFrameAccount', () => { diff --git a/test/p256.test.ts b/test/p256.test.ts index 25fa0e0..76c44a7 100644 --- a/test/p256.test.ts +++ b/test/p256.test.ts @@ -14,11 +14,14 @@ import { FrameEncodeError } from '../src/errors.js' import { type P256FrameSigner, p256SignerIdentity, - privateKeyToP256FrameSigner, - signP256FrameSignature, + privateKeyToP256Account, } from '../src/p256.js' import { frameTxSigHash } from '../src/sighash.js' -import { SECP256R1_N, assertCanonicalSignature } from '../src/signatures.js' +import { + SECP256R1_N, + assertCanonicalSignature, + signFrameSignature, +} from '../src/signatures.js' import { GOLDEN_TX } from './fixtures/golden.js' const PRIVATE_KEY = numberToHex(1n, { size: 32 }) @@ -26,18 +29,17 @@ const DELEGATED_EOA = getAddress('0x0000000000000000000000000000000000001234') describe('P-256 signer identity', () => { test('private scalar 1 derives the published P-256 generator coordinates', () => { - const signer = privateKeyToP256FrameSigner(PRIVATE_KEY) + const signer = privateKeyToP256Account(PRIVATE_KEY) - expect(signer.publicKey.qx).toBe( - '0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296', - ) - expect(signer.publicKey.qy).toBe( - '0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5', + expect(signer.type).toBe('p256') + expect(signer.publicKey).toBe( + '0x046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296' + + '4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5', ) }) test('derives the independently pinned last-20-byte keccak identity', () => { - const signer = privateKeyToP256FrameSigner(PRIVATE_KEY) + const signer = privateKeyToP256Account(PRIVATE_KEY) expect(signer.address.toLowerCase()).toBe( '0xd3a9f047ad43d7e2e4e7e491f1fe2e657a2651b6', @@ -47,17 +49,20 @@ describe('P-256 signer identity', () => { test('rejects a public key that is not on P-256', () => { expect(() => - p256SignerIdentity({ - qx: numberToHex(1n, { size: 32 }), - qy: numberToHex(1n, { size: 32 }), - }), + p256SignerIdentity( + concatHex([ + '0x04', + numberToHex(1n, { size: 32 }), + numberToHex(1n, { size: 32 }), + ]), + ), ).toThrow(/not a point on the curve/) }) }) -describe('signP256FrameSignature', () => { +describe('signFrameSignature with a P-256 owner', () => { test('signs the raw frame sig-hash as r || s || qx || qy', async () => { - const signer = privateKeyToP256FrameSigner(PRIVATE_KEY) + const signer = privateKeyToP256Account(PRIVATE_KEY) const unsigned = { ...GOLDEN_TX, sender: DELEGATED_EOA, @@ -71,12 +76,11 @@ describe('signP256FrameSignature', () => { ], } const hash = frameTxSigHash(unsigned) - const signed = await signP256FrameSignature(unsigned, 0, signer) + const signed = await signFrameSignature(unsigned, 0, signer) const bytes = signed.signatures[0]!.signature expect(bytes.length).toBe(2 + 128 * 2) - expect(sliceHex(bytes, 64, 96)).toBe(signer.publicKey.qx) - expect(sliceHex(bytes, 96, 128)).toBe(signer.publicKey.qy) + expect(sliceHex(bytes, 64, 128)).toBe(sliceHex(signer.publicKey, 1)) expect(() => assertCanonicalSignature(signed.signatures[0]!, 0)).not.toThrow() const signature = { @@ -85,20 +89,25 @@ describe('signP256FrameSignature', () => { } const publicKey = { prefix: 4 as const, - x: BigInt(signer.publicKey.qx), - y: BigInt(signer.publicKey.qy), + x: BigInt(sliceHex(signer.publicKey, 1, 33)), + y: BigInt(sliceHex(signer.publicKey, 33, 65)), } expect(P256.verify({ payload: hash, publicKey, signature })).toBe(true) expect(P256.verify({ payload: hash, publicKey, signature, hash: true })).toBe(false) }) test('normalizes a valid high-s signer response', async () => { - const base = privateKeyToP256FrameSigner(PRIVATE_KEY) + const base = privateKeyToP256Account(PRIVATE_KEY) const signer: P256FrameSigner = { ...base, async sign(parameters) { const signature = await base.sign(parameters) - return { ...signature, s: SECP256R1_N - signature.s } + return concatHex([ + sliceHex(signature, 0, 32), + numberToHex(SECP256R1_N - BigInt(sliceHex(signature, 32, 64)), { + size: 32, + }), + ]) }, } const unsigned = { @@ -108,18 +117,21 @@ describe('signP256FrameSignature', () => { { scheme: 2 as const, signer: signer.address, msg: '0x' as const, signature: '0x' as const }, ], } - const signed = await signP256FrameSignature(unsigned, 0, signer) + const signed = await signFrameSignature(unsigned, 0, signer) const s = BigInt(sliceHex(signed.signatures[0]!.signature, 32, 64)) expect(s).toBeLessThanOrEqual(SECP256R1_N / 2n) }) test('rejects a signer response that does not verify', async () => { - const base = privateKeyToP256FrameSigner(PRIVATE_KEY) + const base = privateKeyToP256Account(PRIVATE_KEY) const signer: P256FrameSigner = { ...base, async sign() { - return { r: 1n, s: 1n } + return concatHex([ + numberToHex(1n, { size: 32 }), + numberToHex(1n, { size: 32 }), + ]) }, } const unsigned = { @@ -130,7 +142,7 @@ describe('signP256FrameSignature', () => { ], } - await expect(signP256FrameSignature(unsigned, 0, signer)).rejects.toThrow( + await expect(signFrameSignature(unsigned, 0, signer)).rejects.toThrow( /does not verify/, ) }) @@ -138,7 +150,7 @@ describe('signP256FrameSignature', () => { describe('toP256FrameAccount', () => { test('prepares and signs scheme-2 entry zero for a delegated EOA', async () => { - const signer = privateKeyToP256FrameSigner(PRIVATE_KEY) + const signer = privateKeyToP256Account(PRIVATE_KEY) const client = createClient({ chain: mainnet, transport: custom({ async request() {} }), @@ -146,7 +158,7 @@ describe('toP256FrameAccount', () => { const account = await toP256FrameAccount({ client, address: DELEGATED_EOA, - signer, + owner: signer, }) const entries = await account.getSignatureEntries(GOLDEN_TX) const unsigned = { @@ -157,6 +169,7 @@ describe('toP256FrameAccount', () => { const signed = await account.signFrameTransaction(unsigned) expect(account.address).toBe(DELEGATED_EOA) + expect(account.owner).toBe(signer) expect(signed.signatures[0]).toMatchObject({ scheme: 2, signer: signer.address, @@ -165,14 +178,13 @@ describe('toP256FrameAccount', () => { expect(signed.signatures[0]!.signature).toBe( concatHex([ sliceHex(signed.signatures[0]!.signature, 0, 64), - signer.publicKey.qx, - signer.publicKey.qy, + sliceHex(signer.publicKey, 1), ]), ) }) test('rejects a transaction for a different sender', async () => { - const signer = privateKeyToP256FrameSigner(PRIVATE_KEY) + const signer = privateKeyToP256Account(PRIVATE_KEY) const client = createClient({ chain: mainnet, transport: custom({ async request() {} }), @@ -180,7 +192,7 @@ describe('toP256FrameAccount', () => { const account = await toP256FrameAccount({ client, address: DELEGATED_EOA, - signer, + owner: signer, }) await expect(account.signFrameTransaction(GOLDEN_TX)).rejects.toThrow( diff --git a/test/signatures.test.ts b/test/signatures.test.ts index ee8a893..781c096 100644 --- a/test/signatures.test.ts +++ b/test/signatures.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from 'vitest' import type { Address, Hex } from 'viem' -import { privateKeyToAccount } from 'viem/accounts' +import { privateKeyToAccount, toAccount } from 'viem/accounts' +import { privateKeyToP256Account } from '../src/p256.js' import { SECP256K1_N, SECP256R1_N, @@ -8,6 +9,7 @@ import { assertValidFrameTx, recoverFrameSigner, resolveSigner, + signFrameSignature, signFrameTx, } from '../src/signatures.js' import { FrameEncodeError } from '../src/errors.js' @@ -180,6 +182,18 @@ describe('signFrameTx and recoverFrameSigner', () => { expect(() => assertCanonicalSignature(signed.signatures[0]!, 0)).not.toThrow() }) + test('preserves the published scheme-1 signing bytes', async () => { + const account = privateKeyToAccount(PRIVATE_KEY) + const tx = { ...GOLDEN_TX, sender: account.address, + signatures: [{ scheme: 1 as const, signer: null, msg: '0x' as const, signature: '0x' as const }] } + const signed = await signFrameTx(tx, PRIVATE_KEY) + + expect(signed.signatures[0]!.signature).toBe( + '0x00ba2811495d0849ea73518ef0d3300622d85d4b7f80b68743b0b7d0d254df00' + + 'ac29c77311f162c523bd114d22484b6b08f856e157832705afd925dbc244358e13', + ) + }) + test('signing is stable under the elision rule', async () => { const account = privateKeyToAccount(PRIVATE_KEY) const tx = { ...GOLDEN_TX, sender: account.address, @@ -358,14 +372,12 @@ describe('signFrameTx with an account', () => { expect(viaAccount.signatures[0]!.signature).toBe(viaKey.signatures[0]!.signature) }) - // What a KMS or hardware wrapper looks like: an address and a raw-digest signer, - // with none of viem's other account surface. - test('signs with a bare { address, sign } remote signer', async () => { + test('signs with a remote signer wrapped as a viem account', async () => { const inner = privateKeyToAccount(PRIVATE_KEY) - const remote = { - address: inner.address, + const remote = toAccount({ + ...inner, sign: ({ hash }: { hash: Hex }) => inner.sign({ hash }), - } + }) const signed = await signFrameTx(oneEmptyEntry(inner.address), remote) expect(await recoverFrameSigner(signed, 0)).toBe(inner.address) }) @@ -373,13 +385,13 @@ describe('signFrameTx with an account', () => { test('signs over the transaction sig-hash, not some other digest', async () => { const inner = privateKeyToAccount(PRIVATE_KEY) const seen: Hex[] = [] - const remote = { - address: inner.address, + const remote = toAccount({ + ...inner, sign: ({ hash }: { hash: Hex }) => { seen.push(hash) return inner.sign({ hash }) }, - } + }) const tx = oneEmptyEntry(inner.address) await signFrameTx(tx, remote) expect(seen).toEqual([frameTxSigHash(tx)]) @@ -406,7 +418,7 @@ describe('signFrameTx with an account', () => { await expect(signFrameTx(tx, account)).rejects.toThrow(new RegExp(other, 'i')) }) - test('leaves a P256 entry untouched', async () => { + test('rejects a P256 entry for a secp256k1 owner', async () => { const account = privateKeyToAccount(PRIVATE_KEY) const p256 = { scheme: 2 as const, @@ -415,8 +427,37 @@ describe('signFrameTx with an account', () => { signature: `0x${'11'.repeat(128)}` as const, } const tx = { ...GOLDEN_TX, sender: account.address, signatures: [p256] } - const signed = await signFrameTx(tx, account) - expect(signed.signatures[0]).toEqual(p256) + await expect(signFrameTx(tx, account)).rejects.toThrow( + /P256 entry cannot be signed by a SECP256K1 owner/, + ) + }) + + test('signs a P256 entry through the shared signFrameTx path', async () => { + const owner = privateKeyToP256Account(`0x${'01'.padStart(64, '0')}`) + const tx = { + ...GOLDEN_TX, + signatures: [ + { + scheme: 2 as const, + signer: owner.address, + msg: '0x' as const, + signature: '0x' as const, + }, + ], + } + const signed = await signFrameTx(tx, owner) + + expect(signed.signatures[0]!.signature).toHaveLength(2 + 128 * 2) + expect(() => assertCanonicalSignature(signed.signatures[0]!, 0)).not.toThrow() + }) + + test('rejects a SECP256K1 entry for a P256 owner', async () => { + const owner = privateKeyToP256Account(`0x${'01'.padStart(64, '0')}`) + const tx = oneEmptyEntry(owner.address) + + await expect(signFrameSignature(tx, 0, owner)).rejects.toThrow( + /SECP256K1 entry cannot be signed by a P256 owner/, + ) }) }) @@ -425,8 +466,12 @@ describe('signFrameTx with an account', () => { // recovery id. Getting this wrong writes a malformed `v` byte into a signature // the chain rejects at consensus, so it is checked rather than assumed. describe('signFrameTx recovery-id normalization', () => { - const signerReturning = (address: Address, vByte: string, flat: Hex) => ({ - address, + const signerReturning = ( + inner: ReturnType, + vByte: string, + flat: Hex, + ) => toAccount({ + ...inner, sign: async () => `0x${flat.slice(2, 130)}${vByte}` as Hex, }) @@ -443,7 +488,7 @@ describe('signFrameTx recovery-id normalization', () => { const v27 = BigInt(`0x${flat.slice(130)}`) const bare = (v27 - 27n).toString(16).padStart(2, '0') - const viaBare = await signFrameTx(tx, signerReturning(inner.address, bare, flat)) + const viaBare = await signFrameTx(tx, signerReturning(inner, bare, flat)) const viaPrefixed = await signFrameTx(tx, inner) expect(viaBare.signatures[0]!.signature).toBe(viaPrefixed.signatures[0]!.signature) }) @@ -459,7 +504,7 @@ describe('signFrameTx recovery-id normalization', () => { } const flat = await inner.sign({ hash: frameTxSigHash(tx) }) await expect( - signFrameTx(tx, signerReturning(inner.address, '25', flat)), + signFrameTx(tx, signerReturning(inner, '25', flat)), ).rejects.toThrow(/signer returned v=37/) }) }) From 9fe2472ceaa8cf3c0b9b477084a1b69d8c295f2f Mon Sep 17 00:00:00 2001 From: Ghadi Mhawej Date: Thu, 8 Oct 2026 14:24:16 +0300 Subject: [PATCH 8/8] fix(signatures): leave other-scheme entries alone in signFrameTx signFrameTx sent every empty-msg P256 entry to the owner, so signing a secp256k1 payer after the P-256 sender slot was signed threw "P256 entry cannot be signed by a SECP256K1 owner". Entries of another scheme belong to another owner and are now skipped; signFrameSignature still rejects a mismatched slot because the caller names it. --- docs/DESIGN.md | 7 +++--- src/signatures.ts | 6 ++++- test/signatures.test.ts | 49 +++++++++++++++++++++++++++++++++++++++-- 3 files changed, 56 insertions(+), 6 deletions(-) diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 835e51b..6d4193a 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -94,9 +94,10 @@ invalidates the transaction at consensus. `signFrameTx` normalizes whatever a si returns into this form. **Signer resolution.** An empty `signer` resolves to `tx.sender` for SECP256K1 and P256. -`signFrameTx` signs every empty-`msg` SECP256K1 entry whose resolved signer is the signing -account, and refuses a signer that cannot sign a raw digest (EIP-191 `signMessage`, JSON-RPC -accounts) rather than produce a signature that recovers to nothing. +`signFrameTx` signs every empty-`msg` entry of the owner's scheme (SECP256K1 for a viem +account, P256 for a P-256 owner) whose resolved signer is the owner, leaves entries of the +other scheme as they are, and refuses a signer that cannot sign a raw digest (EIP-191 +`signMessage`, JSON-RPC accounts) rather than produce a signature that recovers to nothing. ## 4. Gas diff --git a/src/signatures.ts b/src/signatures.ts index 0f0072e..5be2a42 100644 --- a/src/signatures.ts +++ b/src/signatures.ts @@ -307,11 +307,15 @@ export async function signFrameTx( signer: Hex | FrameAccountOwner, ): Promise { const account = resolveFrameSigner(signer) + const scheme = signerScheme(account) const digest = frameTxSigHash(tx) const signatures = await Promise.all( tx.signatures.map(async (sig, i) => { - if (sig.scheme === 0 || sig.msg !== '0x') return sig + // Entries of another scheme belong to another owner, e.g. a P-256 sender + // signed earlier with `signFrameSignature` while this call signs a secp256k1 + // payer, so they are left as they are. + if (sig.scheme !== scheme || sig.msg !== '0x') return sig return signFrameEntry(tx, i, account, digest) }), ) diff --git a/test/signatures.test.ts b/test/signatures.test.ts index 781c096..d8ada79 100644 --- a/test/signatures.test.ts +++ b/test/signatures.test.ts @@ -418,7 +418,7 @@ describe('signFrameTx with an account', () => { await expect(signFrameTx(tx, account)).rejects.toThrow(new RegExp(other, 'i')) }) - test('rejects a P256 entry for a secp256k1 owner', async () => { + test('leaves a P256 entry untouched', async () => { const account = privateKeyToAccount(PRIVATE_KEY) const p256 = { scheme: 2 as const, @@ -427,7 +427,52 @@ describe('signFrameTx with an account', () => { signature: `0x${'11'.repeat(128)}` as const, } const tx = { ...GOLDEN_TX, sender: account.address, signatures: [p256] } - await expect(signFrameTx(tx, account)).rejects.toThrow( + const signed = await signFrameTx(tx, account) + expect(signed.signatures[0]).toEqual(p256) + }) + + test('signs a secp256k1 payer after the P256 sender slot was signed', async () => { + const owner = privateKeyToP256Account(`0x${'01'.padStart(64, '0')}`) + const payer = privateKeyToAccount(PRIVATE_KEY) + const tx = { + ...GOLDEN_TX, + signatures: [ + { scheme: 2 as const, signer: owner.address, msg: '0x' as const, signature: '0x' as const }, + { scheme: 1 as const, signer: payer.address, msg: '0x' as const, signature: '0x' as const }, + ], + } + const senderSigned = await signFrameSignature(tx, 0, owner) + const signed = await signFrameTx(senderSigned, payer) + + expect(signed.signatures[0]).toEqual(senderSigned.signatures[0]) + expect(await recoverFrameSigner(signed, 1)).toBe(payer.address) + }) + + test('signs a P256 sender after the secp256k1 payer slot was signed', async () => { + const owner = privateKeyToP256Account(`0x${'01'.padStart(64, '0')}`) + const payer = privateKeyToAccount(PRIVATE_KEY) + const tx = { + ...GOLDEN_TX, + signatures: [ + { scheme: 2 as const, signer: owner.address, msg: '0x' as const, signature: '0x' as const }, + { scheme: 1 as const, signer: payer.address, msg: '0x' as const, signature: '0x' as const }, + ], + } + const payerSigned = await signFrameSignature(tx, 1, payer) + const signed = await signFrameTx(payerSigned, owner) + + expect(signed.signatures[1]).toEqual(payerSigned.signatures[1]) + expect(signed.signatures[0]!.signature).toHaveLength(2 + 128 * 2) + }) + + test('rejects a P256 slot for a secp256k1 owner', async () => { + const account = privateKeyToAccount(PRIVATE_KEY) + const tx = { + ...GOLDEN_TX, + sender: account.address, + signatures: [{ scheme: 2 as const, signer: null, msg: '0x' as const, signature: '0x' as const }], + } + await expect(signFrameSignature(tx, 0, account)).rejects.toThrow( /P256 entry cannot be signed by a SECP256K1 owner/, ) })