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
19 changes: 17 additions & 2 deletions recipes/server-wallets/aave-yield.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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` |

---

Expand Down
75 changes: 61 additions & 14 deletions recipes/server-wallets/alchemy-smart-wallets.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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<Hex> => {
// 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<Hex> => {
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:

Expand Down Expand Up @@ -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
},
Expand Down Expand Up @@ -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";

Expand Down Expand Up @@ -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<Hex> => {
const signViaTee = async (hash: Hex, transactionData: object): Promise<Hex> => {
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 });
Expand All @@ -267,8 +309,13 @@ export async function POST(req: Request) {
signerType: "magic-tee",
inner: {},
getAddress: async (): Promise<Address> => 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<SignedAuthorization<number>> => {
const res = await teeRequest<{ r: string; s: string; y_parity: number }>(
"/v1/wallet/sign/eip7702", jwt, {
Expand Down
57 changes: 44 additions & 13 deletions recipes/server-wallets/hyperliquid-trading.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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<Hex> {
// Signs a hash together with the content it was computed from, which Magic checks.
async function signViaTee(jwt: string, hash: Hex, transactionData: object): Promise<Hex> {
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 });
}
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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` |

---

Expand All @@ -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`
</Accordion>
Expand Down
19 changes: 17 additions & 2 deletions recipes/server-wallets/lifi-swap.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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` |

---

Expand Down
19 changes: 17 additions & 2 deletions recipes/server-wallets/morpho-yield.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,29 @@ 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);
const hash = keccak256(serialized);

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

---

Expand Down
19 changes: 17 additions & 2 deletions recipes/server-wallets/send-usdc.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,29 @@ 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);
const hash = keccak256(serialized);

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

---

Expand Down
Loading
Loading