From e77bc7c730ce03b153eebcb082acc35bf5296a97 Mon Sep 17 00:00:00 2001 From: Oxyn Kuvatov Date: Thu, 22 Oct 2026 18:37:01 +0500 Subject: [PATCH] require transaction_data in Express sign/data docs and recipes --- recipes/server-wallets/aave-yield.mdx | 19 ++++- .../server-wallets/alchemy-smart-wallets.mdx | 75 +++++++++++++++---- .../server-wallets/hyperliquid-trading.mdx | 57 ++++++++++---- recipes/server-wallets/lifi-swap.mdx | 19 ++++- recipes/server-wallets/morpho-yield.mdx | 19 ++++- recipes/server-wallets/send-usdc.mdx | 19 ++++- recipes/server-wallets/x402-payments.mdx | 40 +++++++--- .../express-api/data-preparation/evm.mdx | 68 +++++++++++++++-- .../express-api/policy/transaction-data.mdx | 15 ++-- .../express-api/wallet-operations.mdx | 28 ++++++- 10 files changed, 298 insertions(+), 61 deletions(-) diff --git a/recipes/server-wallets/aave-yield.mdx b/recipes/server-wallets/aave-yield.mdx index 26a2a93..6d20db0 100644 --- a/recipes/server-wallets/aave-yield.mdx +++ b/recipes/server-wallets/aave-yield.mdx @@ -87,12 +87,27 @@ const publicClient = createPublicClient({ transport: http("YOUR_BASE_RPC_URL"), }); +// The transaction's fields, so Magic can recompute the hash before signing. +// Integers go as decimal strings, since JSON can't carry bigints. +const transactionData = (tx: TransactionSerializable) => ({ + method: "eth_signTransaction", + to: tx.to, + value: (tx.value ?? 0n).toString(), + data: tx.data ?? "0x", + chainId: tx.chainId, + nonce: tx.nonce, + gasLimit: tx.gas?.toString(), + maxFeePerGas: tx.maxFeePerGas?.toString(), + maxPriorityFeePerGas: tx.maxPriorityFeePerGas?.toString(), + gasPrice: tx.gasPrice?.toString(), +}); + async function signAndSend(jwt: string, tx: TransactionSerializable) { const serialized = serializeTransaction(tx); const hash = keccak256(serialized); const { r, s, v } = await teeRequest<{ r: string; s: string; v: string }>( - "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, chain: "ETH" } + "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, transaction_data: transactionData(tx) } ); const yParity = Number(v) >= 27 ? Number(v) - 27 : Number(v); @@ -374,7 +389,7 @@ The aUSDC balance increases over time as interest accrues. Unlike vault-based pr | Endpoint | Purpose | |----------|---------| | `POST /v1/wallet` | Get or create an EOA wallet | -| `POST /v1/wallet/sign/data` | Sign a raw transaction hash | +| `POST /v1/wallet/sign/data` | Sign a transaction hash, sent with its fields as `transaction_data` | --- diff --git a/recipes/server-wallets/alchemy-smart-wallets.mdx b/recipes/server-wallets/alchemy-smart-wallets.mdx index be7badb..68d3ce6 100644 --- a/recipes/server-wallets/alchemy-smart-wallets.mdx +++ b/recipes/server-wallets/alchemy-smart-wallets.mdx @@ -102,26 +102,45 @@ const { public_address: eoaAddress } = await walletRes.json(); The signer needs three methods: - **`signMessage`** — hash the message locally with `hashMessage()` (EIP-191), then send the raw hash to the TEE's `sign/data` endpoint: + **`signMessage`** — hash the message locally with `hashMessage()` (EIP-191), then send the hash and the message to the TEE's `sign/data` endpoint, which checks that they match: ```ts TypeScript icon="square-js" -import { hashMessage, hashTypedData, serializeSignature } from "viem"; +import { + bytesToHex, getTypesForEIP712Domain, hashMessage, hashTypedData, serializeSignature, + stringToHex, type Hex, type SignableMessage, type TypedDataDefinition, +} from "viem"; // Helper: convert TEE's decimal r/s values to 0x-prefixed hex const decToHex = (dec: string): Hex => `0x${BigInt(dec).toString(16).padStart(64, "0")}` as Hex; -// Sign a raw hash via TEE and return a serialized signature -const signRawHash = async (hash: Hex): Promise => { +// The message bytes as hex, so Magic can recompute the EIP-191 hash. +const messageHex = (message: SignableMessage): Hex => + typeof message === "string" ? stringToHex(message) + : typeof message.raw === "string" ? message.raw + : bytesToHex(message.raw); + +// The typed data with the domain type viem hashed it with. +// Integers go as decimal strings, since JSON can't carry bigints. +const typedDataJson = (params: TypedDataDefinition) => { + const domain = params.domain ?? {}; + const types = { EIP712Domain: getTypesForEIP712Domain({ domain }), ...params.types }; + return JSON.parse( + JSON.stringify({ ...params, domain, types }, (_, v) => (typeof v === "bigint" ? v.toString() : v)) + ); +}; + +// Sign a hash via TEE, with the content it was computed from, and return a serialized signature +const signViaTee = async (hash: Hex, transactionData: object): Promise => { const res = await teeRequest<{ r: string; s: string; v: number }>( - "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, chain: "ETH" } + "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, transaction_data: transactionData } ); const yParity = Number(res.v) >= 27 ? Number(res.v) - 27 : Number(res.v); return serializeSignature({ r: decToHex(res.r), s: decToHex(res.s), yParity }); }; ``` - **`signTypedData`** — same pattern, using `hashTypedData()` for EIP-712 structured data. + **`signTypedData`** — same pattern, using `hashTypedData()` for EIP-712 structured data and sending the typed data with it. **`signAuthorization`** — for EIP-7702 delegation, call the TEE's dedicated `sign/eip7702` endpoint: @@ -154,8 +173,13 @@ const signer = { signerType: "magic-tee", inner: {}, getAddress: async () => eoaAddress, - signMessage: async (message) => signRawHash(hashMessage(message)), - signTypedData: async (params) => signRawHash(hashTypedData(params)), + signMessage: async (message) => + signViaTee(hashMessage(message), { method: "eth_sign", data: messageHex(message) }), + signTypedData: async (params) => + signViaTee(hashTypedData(params), { + method: "eth_signTypedData_v4", + typedData: typedDataJson(params), + }), signAuthorization: async (unsignedAuth) => { // ... EIP-7702 signing as shown above }, @@ -216,8 +240,26 @@ import { alchemy, baseSepolia } from "@account-kit/infra"; import { NextResponse } from "next/server"; import { getServerSession } from "next-auth"; import { authOptions } from "@/app/api/auth/[...nextauth]/route"; -import { hashMessage, hashTypedData, serializeSignature } from "viem"; -import type { Address, Hex, SignedAuthorization } from "viem"; +import { + bytesToHex, getTypesForEIP712Domain, hashMessage, hashTypedData, serializeSignature, stringToHex, +} from "viem"; +import type { Address, Hex, SignableMessage, SignedAuthorization, TypedDataDefinition } from "viem"; + +// The message bytes as hex, so Magic can recompute the EIP-191 hash. +const messageHex = (message: SignableMessage): Hex => + typeof message === "string" ? stringToHex(message) + : typeof message.raw === "string" ? message.raw + : bytesToHex(message.raw); + +// The typed data with the domain type viem hashed it with. +// Integers go as decimal strings, since JSON can't carry bigints. +const typedDataJson = (params: TypedDataDefinition) => { + const domain = params.domain ?? {}; + const types = { EIP712Domain: getTypesForEIP712Domain({ domain }), ...params.types }; + return JSON.parse( + JSON.stringify({ ...params, domain, types }, (_, v) => (typeof v === "bigint" ? v.toString() : v)) + ); +}; const TEE_BASE = "https://tee.express.magiclabs.com"; @@ -255,9 +297,9 @@ export async function POST(req: Request) { const decToHex = (dec: string): Hex => `0x${BigInt(dec).toString(16).padStart(64, "0")}` as Hex; - const signRawHash = async (hash: Hex): Promise => { + const signViaTee = async (hash: Hex, transactionData: object): Promise => { const res = await teeRequest<{ r: string; s: string; v: number }>( - "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, chain: "ETH" } + "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, transaction_data: transactionData } ); const yParity = Number(res.v) >= 27 ? Number(res.v) - 27 : Number(res.v); return serializeSignature({ r: decToHex(res.r), s: decToHex(res.s), yParity }); @@ -267,8 +309,13 @@ export async function POST(req: Request) { signerType: "magic-tee", inner: {}, getAddress: async (): Promise
=> eoaAddress as Address, - signMessage: async (message: any) => signRawHash(hashMessage(message)), - signTypedData: async (params: any) => signRawHash(hashTypedData(params)), + signMessage: async (message: any) => + signViaTee(hashMessage(message), { method: "eth_sign", data: messageHex(message) }), + signTypedData: async (params: any) => + signViaTee(hashTypedData(params), { + method: "eth_signTypedData_v4", + typedData: typedDataJson(params), + }), signAuthorization: async (unsignedAuth: any): Promise> => { const res = await teeRequest<{ r: string; s: string; y_parity: number }>( "/v1/wallet/sign/eip7702", jwt, { diff --git a/recipes/server-wallets/hyperliquid-trading.mdx b/recipes/server-wallets/hyperliquid-trading.mdx index ce45546..8e37a74 100644 --- a/recipes/server-wallets/hyperliquid-trading.mdx +++ b/recipes/server-wallets/hyperliquid-trading.mdx @@ -78,30 +78,46 @@ The Hyperliquid SDK expects a wallet with a `signTypedData` method. Create a cus ```ts TypeScript icon="square-js" import { toAccount } from "viem/accounts"; -import { hashTypedData, hashMessage, serializeSignature, type Address, type Hex } from "viem"; +import { + bytesToHex, getTypesForEIP712Domain, hashMessage, hashTypedData, + serializeSignature, stringToHex, type Address, type Hex, +} from "viem"; function createTeeAccount(jwt: string, address: Address) { return toAccount({ address, signMessage: async ({ message }) => { - const hash = typeof message === "string" - ? hashMessage(message) - : hashMessage({ raw: message as Hex }); - return signHashViaTee(jwt, hash); + // Send the message bytes as hex so Magic can recompute the EIP-191 hash. + const data = + typeof message === "string" ? stringToHex(message) + : typeof message.raw === "string" ? message.raw + : bytesToHex(message.raw); + return signViaTee(jwt, hashMessage(message), { method: "eth_sign", data }); }, signTransaction: async () => { throw new Error("Use signAndSend for transactions"); }, - signTypedData: async ({ domain, types, primaryType, message }) => { - const hash = hashTypedData({ domain, types, primaryType, message }); - return signHashViaTee(jwt, hash); + signTypedData: async (typedData) => { + // Send the typed data with the domain type viem hashed it with. + // Integers go as decimal strings, since JSON can't carry bigints. + const domain = typedData.domain ?? {}; + const types = { EIP712Domain: getTypesForEIP712Domain({ domain }), ...typedData.types }; + return signViaTee(jwt, hashTypedData(typedData), { + method: "eth_signTypedData_v4", + typedData: JSON.parse( + JSON.stringify({ ...typedData, domain, types }, (_, v) => + typeof v === "bigint" ? v.toString() : v + ) + ), + }); }, }); } -async function signHashViaTee(jwt: string, hash: Hex): Promise { +// Signs a hash together with the content it was computed from, which Magic checks. +async function signViaTee(jwt: string, hash: Hex, transactionData: object): Promise { const { r, s, v } = await teeRequest<{ r: string; s: string; v: string }>( - "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, chain: "ETH" } + "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, transaction_data: transactionData } ); return serializeSignature({ r: r as Hex, s: s as Hex, yParity: Number(v) - 27 }); } @@ -152,12 +168,27 @@ const arbClient = createPublicClient({ transport: http("https://arb1.arbitrum.io/rpc"), }); +// The transaction's fields, so Magic can recompute the hash before signing. +// Integers go as decimal strings, since JSON can't carry bigints. +const transactionData = (tx: TransactionSerializable) => ({ + method: "eth_signTransaction", + to: tx.to, + value: (tx.value ?? 0n).toString(), + data: tx.data ?? "0x", + chainId: tx.chainId, + nonce: tx.nonce, + gasLimit: tx.gas?.toString(), + maxFeePerGas: tx.maxFeePerGas?.toString(), + maxPriorityFeePerGas: tx.maxPriorityFeePerGas?.toString(), + gasPrice: tx.gasPrice?.toString(), +}); + async function signAndSend(jwt: string, tx: TransactionSerializable) { const serialized = serializeTransaction(tx); const hash = keccak256(serialized); const { r, s, v } = await teeRequest<{ r: string; s: string; v: string }>( - "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, chain: "ETH" } + "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, transaction_data: transactionData(tx) } ); const yParity = Number(v) >= 27 ? Number(v) - 27 : Number(v); @@ -389,7 +420,7 @@ Asset indices can change between testnet and mainnet. In production, use `info.m | Endpoint | Purpose | |----------|---------| | `POST /v1/wallet` | Get or create an EOA wallet | -| `POST /v1/wallet/sign/data` | Sign a raw data hash (EIP-712 typed data hash) | +| `POST /v1/wallet/sign/data` | Sign a hash, sent with the typed data or message as `transaction_data` | --- @@ -410,7 +441,7 @@ Asset indices can change between testnet and mainnet. In production, use `info.m **Symptoms:** Hyperliquid rejects the order with a signature error. **Solutions:** -- Verify the `signHashViaTee` function correctly reconstructs the signature from r, s, v components +- Verify the `signViaTee` function correctly reconstructs the signature from r, s, v components - Ensure the TEE account address matches the address that deposited USDC on Hyperliquid - Check that `serializeSignature` is imported from `viem` diff --git a/recipes/server-wallets/lifi-swap.mdx b/recipes/server-wallets/lifi-swap.mdx index 755fe20..6760f87 100644 --- a/recipes/server-wallets/lifi-swap.mdx +++ b/recipes/server-wallets/lifi-swap.mdx @@ -87,12 +87,27 @@ const publicClient = createPublicClient({ transport: http("YOUR_BASE_RPC_URL"), }); +// The transaction's fields, so Magic can recompute the hash before signing. +// Integers go as decimal strings, since JSON can't carry bigints. +const transactionData = (tx: TransactionSerializable) => ({ + method: "eth_signTransaction", + to: tx.to, + value: (tx.value ?? 0n).toString(), + data: tx.data ?? "0x", + chainId: tx.chainId, + nonce: tx.nonce, + gasLimit: tx.gas?.toString(), + maxFeePerGas: tx.maxFeePerGas?.toString(), + maxPriorityFeePerGas: tx.maxPriorityFeePerGas?.toString(), + gasPrice: tx.gasPrice?.toString(), +}); + async function signAndSend(jwt: string, tx: TransactionSerializable) { const serialized = serializeTransaction(tx); const hash = keccak256(serialized); const { r, s, v } = await teeRequest<{ r: string; s: string; v: string }>( - "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, chain: "ETH" } + "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, transaction_data: transactionData(tx) } ); const yParity = Number(v) >= 27 ? Number(v) - 27 : Number(v); @@ -338,7 +353,7 @@ Li.Fi also accepts token symbols (e.g., `"ETH"`, `"USDC"`) instead of addresses, | Endpoint | Purpose | |----------|---------| | `POST /v1/wallet` | Get or create an EOA wallet | -| `POST /v1/wallet/sign/data` | Sign a raw transaction hash | +| `POST /v1/wallet/sign/data` | Sign a transaction hash, sent with its fields as `transaction_data` | --- diff --git a/recipes/server-wallets/morpho-yield.mdx b/recipes/server-wallets/morpho-yield.mdx index b15900f..f2a7c5e 100644 --- a/recipes/server-wallets/morpho-yield.mdx +++ b/recipes/server-wallets/morpho-yield.mdx @@ -94,6 +94,21 @@ const publicClient = createPublicClient({ transport: http("YOUR_BASE_RPC_URL"), }); +// The transaction's fields, so Magic can recompute the hash before signing. +// Integers go as decimal strings, since JSON can't carry bigints. +const transactionData = (tx: TransactionSerializable) => ({ + method: "eth_signTransaction", + to: tx.to, + value: (tx.value ?? 0n).toString(), + data: tx.data ?? "0x", + chainId: tx.chainId, + nonce: tx.nonce, + gasLimit: tx.gas?.toString(), + maxFeePerGas: tx.maxFeePerGas?.toString(), + maxPriorityFeePerGas: tx.maxPriorityFeePerGas?.toString(), + gasPrice: tx.gasPrice?.toString(), +}); + async function signAndSend(jwt: string, tx: TransactionSerializable) { // Serialize the unsigned transaction and hash it const serialized = serializeTransaction(tx); @@ -101,7 +116,7 @@ async function signAndSend(jwt: string, tx: TransactionSerializable) { // Sign the hash via TEE const { r, s, v } = await teeRequest<{ r: string; s: string; v: string }>( - "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, chain: "ETH" } + "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, transaction_data: transactionData(tx) } ); // Serialize with signature and broadcast @@ -339,7 +354,7 @@ Individual vault addresses change as new vaults are deployed by curators. Use th | Endpoint | Purpose | |----------|---------| | `POST /v1/wallet` | Get or create an EOA wallet | -| `POST /v1/wallet/sign/data` | Sign a raw transaction hash | +| `POST /v1/wallet/sign/data` | Sign a transaction hash, sent with its fields as `transaction_data` | --- diff --git a/recipes/server-wallets/send-usdc.mdx b/recipes/server-wallets/send-usdc.mdx index aabc1dd..c0f4799 100644 --- a/recipes/server-wallets/send-usdc.mdx +++ b/recipes/server-wallets/send-usdc.mdx @@ -87,6 +87,21 @@ const publicClient = createPublicClient({ transport: http("YOUR_BASE_RPC_URL"), }); +// The transaction's fields, so Magic can recompute the hash before signing. +// Integers go as decimal strings, since JSON can't carry bigints. +const transactionData = (tx: TransactionSerializable) => ({ + method: "eth_signTransaction", + to: tx.to, + value: (tx.value ?? 0n).toString(), + data: tx.data ?? "0x", + chainId: tx.chainId, + nonce: tx.nonce, + gasLimit: tx.gas?.toString(), + maxFeePerGas: tx.maxFeePerGas?.toString(), + maxPriorityFeePerGas: tx.maxPriorityFeePerGas?.toString(), + gasPrice: tx.gasPrice?.toString(), +}); + async function signAndSend(jwt: string, tx: TransactionSerializable) { // Serialize the unsigned transaction and hash it const serialized = serializeTransaction(tx); @@ -94,7 +109,7 @@ async function signAndSend(jwt: string, tx: TransactionSerializable) { // Sign the hash via TEE const { r, s, v } = await teeRequest<{ r: string; s: string; v: string }>( - "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, chain: "ETH" } + "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, transaction_data: transactionData(tx) } ); // Serialize with signature and broadcast @@ -218,7 +233,7 @@ Base has both native USDC (`0x8335...`) and bridged USDbC (`0xd9aA...`). This gu | Endpoint | Purpose | |----------|---------| | `POST /v1/wallet` | Get or create an EOA wallet | -| `POST /v1/wallet/sign/data` | Sign a raw transaction hash | +| `POST /v1/wallet/sign/data` | Sign a transaction hash, sent with its fields as `transaction_data` | --- diff --git a/recipes/server-wallets/x402-payments.mdx b/recipes/server-wallets/x402-payments.mdx index 827aede..7fe6e84 100644 --- a/recipes/server-wallets/x402-payments.mdx +++ b/recipes/server-wallets/x402-payments.mdx @@ -78,30 +78,46 @@ The x402 SDK expects a viem `Account` object that can sign typed data. Create a ```ts TypeScript icon="square-js" import { toAccount } from "viem/accounts"; -import { hashTypedData, serializeSignature, type Address, type Hex } from "viem"; +import { + bytesToHex, getTypesForEIP712Domain, hashMessage, hashTypedData, + serializeSignature, stringToHex, type Address, type Hex, +} from "viem"; function createTeeAccount(jwt: string, address: Address) { return toAccount({ address, signMessage: async ({ message }) => { - const hash = typeof message === "string" - ? hashMessage(message) - : hashMessage({ raw: message as Hex }); - return signHashViaTee(jwt, hash); + // Send the message bytes as hex so Magic can recompute the EIP-191 hash. + const data = + typeof message === "string" ? stringToHex(message) + : typeof message.raw === "string" ? message.raw + : bytesToHex(message.raw); + return signViaTee(jwt, hashMessage(message), { method: "eth_sign", data }); }, signTransaction: async () => { throw new Error("Use signAndSend for transactions"); }, - signTypedData: async ({ domain, types, primaryType, message }) => { - const hash = hashTypedData({ domain, types, primaryType, message }); - return signHashViaTee(jwt, hash); + signTypedData: async (typedData) => { + // Send the typed data with the domain type viem hashed it with. + // Integers go as decimal strings, since JSON can't carry bigints. + const domain = typedData.domain ?? {}; + const types = { EIP712Domain: getTypesForEIP712Domain({ domain }), ...typedData.types }; + return signViaTee(jwt, hashTypedData(typedData), { + method: "eth_signTypedData_v4", + typedData: JSON.parse( + JSON.stringify({ ...typedData, domain, types }, (_, v) => + typeof v === "bigint" ? v.toString() : v + ) + ), + }); }, }); } -async function signHashViaTee(jwt: string, hash: Hex): Promise { +// Signs a hash together with the content it was computed from, which Magic checks. +async function signViaTee(jwt: string, hash: Hex, transactionData: object): Promise { const { r, s, v } = await teeRequest<{ r: string; s: string; v: string }>( - "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, chain: "ETH" } + "/v1/wallet/sign/data", jwt, { raw_data_hash: hash, transaction_data: transactionData } ); return serializeSignature({ r: r as Hex, s: s as Hex, yParity: Number(v) - 27 }); } @@ -259,7 +275,7 @@ const server = new x402ResourceServer(facilitatorClient) | Endpoint | Purpose | |----------|---------| | `POST /v1/wallet` | Get or create an EOA wallet | -| `POST /v1/wallet/sign/data` | Sign a raw data hash (EIP-712 typed data hash) | +| `POST /v1/wallet/sign/data` | Sign a hash, sent with the typed data or message as `transaction_data` | --- @@ -282,7 +298,7 @@ const server = new x402ResourceServer(facilitatorClient) **Solutions:** - Ensure the wallet has sufficient USDC on the correct network (Base Sepolia for testing, Base mainnet for production) - Verify the TEE is signing the correct EIP-712 hash -- Check that the `signHashViaTee` function is correctly reconstructing the signature from r, s, v components +- Check that the `signViaTee` function is correctly reconstructing the signature from r, s, v components diff --git a/server-wallets/express-api/data-preparation/evm.mdx b/server-wallets/express-api/data-preparation/evm.mdx index 1ee7b40..66fa847 100644 --- a/server-wallets/express-api/data-preparation/evm.mdx +++ b/server-wallets/express-api/data-preparation/evm.mdx @@ -31,7 +31,7 @@ const personalSign = async (data: string) => { ## Data Signing -For signing transaction data or other structured data, provide a keccak256 hash: +For `/v2/wallet/sign/data`, send the hash together with `transaction_data`, the content it was computed from. Magic recomputes the hash and rejects the request with `400 INVALID_SIGNING_PARAMS` if they don't match. ```typescript Typed Data V1 @@ -41,7 +41,10 @@ const signTypedDataV1 = async (data: TypedDataV1) => { // Compute hash for typed data V1 const rawDataHash = typedSignatureHash(data); - const body = { raw_data_hash: rawDataHash }; + const body = { + raw_data_hash: rawDataHash, + transaction_data: { method: 'eth_signTypedData', typedData: data }, + }; return await fetch('/v2/wallet/sign/data', { method: 'POST', headers: { @@ -76,7 +79,10 @@ const signTypedDataV3 = async (data: TypedMessage) => { // Compute EIP-712 hash for typed data V3 const rawDataHash = computeEip712Hash(data, SignTypedDataVersion.V3); - const body = { raw_data_hash: rawDataHash }; + const body = { + raw_data_hash: rawDataHash, + transaction_data: { method: 'eth_signTypedData_v3', typedData: data }, + }; return await fetch('/v2/wallet/sign/data', { method: 'POST', headers: { @@ -94,7 +100,10 @@ const signTypedDataV4 = async (data: TypedMessage) => { // Compute EIP-712 hash for typed data V4 const rawDataHash = computeEip712Hash(data, SignTypedDataVersion.V4); - const body = { raw_data_hash: rawDataHash }; + const body = { + raw_data_hash: rawDataHash, + transaction_data: { method: 'eth_signTypedData_v4', typedData: data }, + }; return await fetch('/v2/wallet/sign/data', { method: 'POST', headers: { @@ -120,8 +129,26 @@ const signTransaction = async (tx: TransactionRequest) => { // Create transaction object and get unsigned hash const btx = Transaction.from(txForSigning as TransactionLike); - - const body = { raw_data_hash: btx.unsignedHash }; + + // The transaction's fields, so Magic can recompute the unsigned hash. + // Integers go as decimal strings, since JSON can't carry bigints. + const transaction_data = { + method: 'eth_signTransaction', + to: btx.to, + value: btx.value.toString(), + data: btx.data, + chainId: Number(btx.chainId), + nonce: btx.nonce, + gasLimit: btx.gasLimit.toString(), + ...(btx.maxFeePerGas != null + ? { + maxFeePerGas: btx.maxFeePerGas.toString(), + maxPriorityFeePerGas: btx.maxPriorityFeePerGas!.toString(), + } + : { gasPrice: btx.gasPrice!.toString() }), + }; + + const body = { raw_data_hash: btx.unsignedHash, transaction_data }; const res = await fetch('/v2/wallet/sign/data', { method: 'POST', headers: { @@ -141,4 +168,33 @@ const signTransaction = async (tx: TransactionRequest) => { return btx.serialized; }; ``` + +```typescript eth_sign +import { getBytes, hashMessage, isHexString } from 'ethers'; + +const ethSign = async (message: string) => { + // EIP-191 hash: hex strings are signed as bytes, anything else as text. + const rawDataHash = hashMessage(isHexString(message) ? getBytes(message) : message); + + const body = { + raw_data_hash: rawDataHash, + transaction_data: { method: 'eth_sign', data: message }, + }; + return await fetch('/v2/wallet/sign/data', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${YOUR_JWT_TOKEN}`, + 'X-Magic-API-Key': 'YOUR_MAGIC_API_KEY', + 'X-OIDC-Provider-ID': 'YOUR_OIDC_PROVIDER_ID', + 'X-Magic-Chain': 'ETH' + }, + body: JSON.stringify(body) + }); +}; +``` + + +Transactions with an access list, blobs or an authorization list can't be described in `transaction_data` yet. To sign an EIP-7702 authorization, use [Sign EIP-7702 Authorization](/server-wallets/express-api/wallet-operations#sign-eip-7702-authorization), which computes the hash for you. + diff --git a/server-wallets/express-api/policy/transaction-data.mdx b/server-wallets/express-api/policy/transaction-data.mdx index bc7cd57..c569f51 100644 --- a/server-wallets/express-api/policy/transaction-data.mdx +++ b/server-wallets/express-api/policy/transaction-data.mdx @@ -8,7 +8,7 @@ description: "Learn how to structure and pass transaction data for policy evalua When using policies with Express API, you need to provide transaction data so that policy conditions can be evaluated. This data is used to check whether transactions meet your policy rules before signing occurs. -Transaction data is required when policy evaluation is enabled for your application. It must match the raw transaction data being signed to ensure policy conditions evaluate correctly. +Transaction data is required on every EVM `sign/data` request, whether or not policy evaluation is enabled. Magic recomputes `raw_data_hash` from it and rejects the request with `400 INVALID_SIGNING_PARAMS` if they don't match, so policy conditions always evaluate what is actually signed. ## Transaction Data Structure @@ -38,12 +38,13 @@ The `TransactionData` object contains information about the transaction or messa The signing method being used. Valid values: -- `eth_signTransaction` - Sign an Ethereum transaction -- `personal_sign` - Sign a message using personal_sign -- `eth_signTypedData` - Sign EIP-712 typed data (legacy) +- `eth_signTransaction`, `eth_sendTransaction` - Sign an Ethereum transaction +- `eth_signTypedData` - Sign typed data (v1, legacy) - `eth_signTypedData_v3` - Sign EIP-712 typed data v3 - `eth_signTypedData_v4` - Sign EIP-712 typed data v4 -- `eth_signMessage` - Sign fringe message format +- `eth_sign` - Sign a message, sent in `data` +- `eth_sign7702Authorization` - Sign an EIP-7702 authorization, with `chainId`, `address` and `nonce` +- `personal_sign` - Evaluated by policy on [Sign Message](/server-wallets/express-api/wallet-operations#sign-message); not accepted on `sign/data` @@ -82,6 +83,10 @@ Maximum priority fee per gas unit (EIP-1559 transactions). Can be provided as de Gas price for legacy transactions. Can be provided as decimal string or hex string. + +The EIP-7702 delegate contract. Required for `eth_sign7702Authorization`, together with `chainId` and `nonce`. + + EIP-712 typed data structure. Required for `eth_signTypedData_v3` and `eth_signTypedData_v4` methods. diff --git a/server-wallets/express-api/wallet-operations.mdx b/server-wallets/express-api/wallet-operations.mdx index 9853d0f..3076448 100644 --- a/server-wallets/express-api/wallet-operations.mdx +++ b/server-wallets/express-api/wallet-operations.mdx @@ -52,7 +52,7 @@ All signing operations use the `Authorization: Bearer` JWT as the operation JWT ### Sign Data -Sign a hash of arbitrary data using the wallet's private key. Useful for signing transaction data, typed data, or any structured information. +Sign a hash with the wallet's private key. Send the hash together with `transaction_data`, the content it was computed from. Magic recomputes the hash from that content and signs only when they match. ```bash cURL icon="square-terminal" curl -X POST 'https://tee.express.magiclabs.com/v2/wallet/sign/data' \ @@ -62,7 +62,11 @@ curl -X POST 'https://tee.express.magiclabs.com/v2/wallet/sign/data' \ -H 'X-OIDC-Provider-ID: YOUR_OIDC_PROVIDER_ID' \ -H 'X-Magic-Chain: ETH' \ -d '{ - "raw_data_hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" + "raw_data_hash": "0x50b2c43fd39106bafbba0da34fc430e1f91e3c96ea2acee2bc34119f92b37750", + "transaction_data": { + "method": "eth_sign", + "data": "0x68656c6c6f" + } }' ``` @@ -85,9 +89,27 @@ The blockchain to sign for. Available values: `ETH`, `SOL`, `BTC` -The keccak256 hash of the data to sign (hex string with 0x prefix). +The hash to sign (hex string with 0x prefix), computed from `transaction_data` as described below. + +What you're signing. Required for `ETH`. Set `method` and the fields for it: + +| `method` | Fields | `raw_data_hash` | +| --- | --- | --- | +| `eth_signTransaction`, `eth_sendTransaction` | `to`, `value`, `data`, `chainId`, `nonce`, `gasLimit`, and `maxFeePerGas` + `maxPriorityFeePerGas` (EIP-1559) or `gasPrice` (legacy) | The unsigned transaction hash | +| `eth_signTypedData_v4`, `eth_signTypedData_v3` | `typedData`: the full EIP-712 JSON (`types`, `primaryType`, `domain`, `message`) | The EIP-712 hash | +| `eth_signTypedData` | `typedData`: the v1 typed data array | eth-sig-util `typedSignatureHash` | +| `eth_sign` | `data`: the message, as `0x`-prefixed hex bytes or plain text | The EIP-191 hash | +| `eth_sign7702Authorization` | `chainId`, `address` (the delegate contract), `nonce` | keccak256(0x05 ‖ rlp([chainId, address, nonce])) | + +See [EVM data preparation](/server-wallets/express-api/data-preparation/evm) for code that builds each one. Transactions with an access list, blobs or an authorization list are not supported here. + + + +`raw_data_hash` without matching `transaction_data` is rejected with `400 INVALID_SIGNING_PARAMS`. To sign a plain message without hashing it yourself, use [Sign Message](#sign-message); for an EIP-7702 authorization, use [Sign EIP-7702 Authorization](#sign-eip-7702-authorization). + + #### Response Fields