Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 51 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,32 +80,72 @@ 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
argument, so the signature recovers to nothing. A `JsonRpcAccount` (a browser wallet)
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`.
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 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
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 {
privateKeyToP256Account,
toP256FrameAccount,
} from '@jaw.id/frametx-kit'

const owner = privateKeyToP256Account(p256PrivateKey)
const account = await toP256FrameAccount({
client,
address: delegatedEoa,
owner,
})
```

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
Expand Down
3 changes: 3 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 11 additions & 4 deletions docs/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -146,6 +147,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
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@
"test:watch": "vitest",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"ox": "^0.14.45"
},
"peerDependencies": {
"viem": "^2.21.0"
},
Expand Down
173 changes: 173 additions & 0 deletions scripts/send-eth-p256.ts
Original file line number Diff line number Diff line change
@@ -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,
privateKeyToP256Account,
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<RpcFrameReceiptJson> {
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<void> {
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 owner = privateKeyToP256Account(
loadP256PrivateKey(requiredEnv('P256_PRIVATE_KEY_PATH')),
)

const expectedIdentity = process.env.P256_SIGNER_IDENTITY
if (
expectedIdentity !== undefined &&
!isAddressEqual(owner.address, getAddress(expectedIdentity))
)
throw new Error(
`PEM signer identity ${owner.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, owner.address))
throw new Error(
`delegated account authorizes ${configuredSigner}, but the PEM identity is ${owner.address}`,
)

const account = await toP256FrameAccount({ client, address: sender, owner })
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: ${owner.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
})
Loading
Loading