Stealth payments with viem in 60 lines
Receive, send and find ERC-5564 stealth payments with viem and @noble/curves. One file, no SDK, works with every ERC-5564 wallet.
Stealth payments need less code than most people expect. This page is one TypeScript file of 55 lines that does all four parts of ERC-5564 scheme 1: make receiving keys, pay a meta-address, scan for payments, and recover the key that spends them. It uses only viem and @noble/curves.
Download: stealth-viem.ts.
It is the same math our client runs. Our test suite runs this exact file against the client and the ScopeLift SDK in both directions, and pays, finds and spends a real payment with it on a local chain. Because it follows the standard, other ERC-5564 wallets can find the payments it sends, and it finds the payments they send.
npm install viem @noble/curvesThe code
// Stealth payments on Ethereum (ERC-5564, scheme 1) with viem and @noble/curves.
import { secp256k1 } from '@noble/curves/secp256k1';
import { bytesToHex, hexToBytes, keccak256, parseAbi, type Account, type Chain, type Hex, type PublicClient, type Transport, type WalletClient } from 'viem';
import { publicKeyToAddress } from 'viem/accounts';
const ANNOUNCER = '0x55649E01B5Df198D18D95b5cc5051630cfD45564'; // same address on every chain
const abi = parseAbi([
'function announce(uint256 schemeId, address stealthAddress, bytes ephemeralPubKey, bytes metadata)',
'event Announcement(uint256 indexed schemeId, address indexed stealthAddress, address indexed caller, bytes ephemeralPubKey, bytes metadata)',
]);
const N = secp256k1.CURVE.n;
const randomKey = () => bytesToHex(secp256k1.utils.randomPrivateKey());
const pubOf = (k: Hex) => bytesToHex(secp256k1.getPublicKey(hexToBytes(k), true)); // compressed, 33 bytes
// keccak256 of the shared point. Its first byte is the view tag.
const secret = (priv: Hex, pub: Hex) => keccak256(secp256k1.getSharedSecret(hexToBytes(priv), hexToBytes(pub), true));
// The one-time address: spending public key + secret * G.
const stealthOf = (spendPub: Hex, h: Hex) => publicKeyToAddress(bytesToHex(secp256k1.ProjectivePoint.fromHex(spendPub.slice(2))
.add(secp256k1.ProjectivePoint.BASE.multiply(BigInt(h) % N)).toRawBytes(false)));
// 1. Receiver: two keys. Share the meta-address once; keep both private keys.
export function newKeys() {
const spend = randomKey(), view = randomKey();
return { spend, view, meta: `st:eth:0x${pubOf(spend).slice(2)}${pubOf(view).slice(2)}` };
}
// 2. Sender: derive a fresh address, announce it, then pay it.
export async function pay(wallet: WalletClient<Transport, Chain, Account>, meta: string, value: bigint) {
const m = meta.split(':').pop()!.slice(2);
const spendPub = `0x${m.slice(0, 66)}` as Hex, viewPub = `0x${m.slice(66)}` as Hex;
const eph = randomKey();
const h = secret(eph, viewPub);
const to = stealthOf(spendPub, h);
// Metadata: view tag, 0xeeeeeeee, the ETH placeholder token 0xEeee...EeeE, amount (57 bytes).
const metadata = `${h.slice(0, 4)}${'ee'.repeat(24)}${value.toString(16).padStart(64, '0')}` as Hex;
await wallet.writeContract({ address: ANNOUNCER, abi, functionName: 'announce', args: [1n, to, pubOf(eph), metadata] });
const hash = await wallet.sendTransaction({ to, value });
return { to, hash };
}
// 3. Receiver: scan announcements. The view tag skips 255 of 256 strangers' payments early.
export async function scan(client: PublicClient, keys: { spend: Hex; view: Hex }, fromBlock = 0n) {
const logs = await client.getContractEvents({ address: ANNOUNCER, abi, eventName: 'Announcement', args: { schemeId: 1n }, fromBlock });
const found: { address: Hex; privateKey: Hex }[] = [];
for (const { args: a } of logs) {
if (!a.ephemeralPubKey || !a.metadata || !a.stealthAddress) continue;
let h: Hex;
try { h = secret(keys.view, a.ephemeralPubKey); } catch { continue; } // anyone can announce garbage
if (h.slice(0, 4) !== a.metadata.slice(0, 4).toLowerCase()) continue; // view tag: not ours
if (stealthOf(pubOf(keys.spend), h) !== a.stealthAddress) continue; // full check
// 4. Only the receiver can spend: p_stealth = p_spend + secret (mod n).
const p = (BigInt(keys.spend) + BigInt(h)) % N;
found.push({ address: a.stealthAddress, privateKey: `0x${p.toString(16).padStart(64, '0')}` });
}
return found;
}Use it
import { createPublicClient, createWalletClient, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { sepolia } from 'viem/chains';
import { newKeys, pay, scan } from './stealth-viem';
const keys = newKeys(); // receiver: store keys.spend and keys.view safely, share keys.meta
const wallet = createWalletClient({ account: privateKeyToAccount(SENDER_KEY), chain: sepolia, transport: http() });
await pay(wallet, keys.meta, 10n ** 15n); // sender: 0.001 ETH to a fresh address
const client = createPublicClient({ chain: sepolia, transport: http() });
const found = await scan(client, keys, FROM_BLOCK); // receiver: [{ address, privateKey }]SENDER_KEY and FROM_BLOCK are yours to fill in. Start the scan near the block where you first shared the meta-address; public RPCs limit how many blocks one log query may cover, so a real client reads in ranges.
What each part does
Keys. The receiver holds two private keys. The spending key moves funds; the viewing key only finds payments, so it can live on a server or a phone that should not be able to spend. The meta-address st:eth:0x... is the two compressed public keys side by side. Our client derives both keys from one wallet signature instead of random bytes, so the wallet alone can recreate them (Key derivation).
Pay. The sender picks a random ephemeral key, multiplies it with the viewing public key, and hashes the shared point. The one-time address is the spending public key plus that hash times G. The sender announces first, then pays: if the payment never happens, the receiver sees an empty announcement, and nothing is lost. The metadata starts with the view tag and uses the standard 57-byte layout for ETH, so every client can show what was paid.
Scan. The receiver reads every scheme 1 announcement and repeats the multiplication with the viewing private key. If the first byte of the hash differs from the view tag, the announcement belongs to someone else, which is true for 255 of every 256. Only matches get the full address check. Anyone can announce anything, so a bad key is skipped, never trusted.
Spend. The private key of the one-time address is the spending private key plus the hash, modulo the curve order. Only the receiver can compute it.
The proof that sender and receiver reach the same address is in Stealth address math, and fixed inputs with every intermediate value are in Test vectors.
What the 60 lines leave out
Before you ship this to users
The math is the easy part. Our leak study found that withdrawals, not the cryptography, are what link stealth payments back to their owners.
- Withdrawing safely. Never send a payment back to the address that paid it, never to the wallet the keys came from, and never sweep several payments into one address. Our client blocks these by default (Withdraw without leaking).
- The registry. ERC-6538 lets a receiver publish the meta-address next to a normal address, so senders can look it up (Announcer and registry).
- Tokens. For ERC-20 payments the metadata names the token contract and the sender calls
transferinstead of sending ETH. - Gas for the one-time address. A fresh address holds no ETH for gas when it receives a token, and funding it from your main wallet links the two.
- Ranges and caching. A real scanner reads logs in block ranges and remembers how far it got.
More for wallet and app builders is in Build with ERC-5564.
Stay unlinked.