askrobots / dbbasic-browser
Public
A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.
danq9
site icons (favicons) in tabs, address bar suggestions and the bookmarks panel
7249579
16 hours, 4 minutes ago
History
exact-evm.ts · 4.4 KB · 131 lines
| 1 | /** The "exact" scheme on EVM: a gasless EIP-3009 transferWithAuthorization signature. */ |
| 2 | |
| 3 | import { getAddress, toHex, type LocalAccount } from "viem"; |
| 4 | import { lookupAsset, priceUsdMicro, type PinnedAsset } from "../assets.js"; |
| 5 | import type { Eip3009Authorization, PaymentPayload, PaymentRequired, PaymentRequirements, Quote } from "../types.js"; |
| 6 | |
| 7 | export const AUTHORIZATION_TYPES = { |
| 8 | TransferWithAuthorization: [ |
| 9 | { name: "from", type: "address" }, |
| 10 | { name: "to", type: "address" }, |
| 11 | { name: "value", type: "uint256" }, |
| 12 | { name: "validAfter", type: "uint256" }, |
| 13 | { name: "validBefore", type: "uint256" }, |
| 14 | { name: "nonce", type: "bytes32" }, |
| 15 | ], |
| 16 | } as const; |
| 17 | |
| 18 | /** CAIP-2 "eip155:8453" -> 8453 */ |
| 19 | export function evmChainId(network: string): number { |
| 20 | const m = /^eip155:(\d+)$/.exec(network); |
| 21 | if (!m) throw new Error(`not an EVM CAIP-2 network: ${network}`); |
| 22 | return Number(m[1]); |
| 23 | } |
| 24 | |
| 25 | /** |
| 26 | * Turn the server's `accepts[]` into quotes we can actually price. |
| 27 | * Anything referencing an asset outside the pinned registry is dropped: if we don't |
| 28 | * know an asset's decimals we cannot know what `amount` costs, and signing a number |
| 29 | * you can't price is how you lose money. |
| 30 | */ |
| 31 | export function quoteFrom(paymentRequired: PaymentRequired): { quotes: Quote[]; rejected: string[] } { |
| 32 | const quotes: Quote[] = []; |
| 33 | const rejected: string[] = []; |
| 34 | |
| 35 | for (const r of paymentRequired.accepts ?? []) { |
| 36 | if (r.scheme !== "exact") { |
| 37 | rejected.push(`${r.scheme}/${r.network}: unsupported scheme`); |
| 38 | continue; |
| 39 | } |
| 40 | const asset = lookupAsset(r.network, r.asset); |
| 41 | if (!asset) { |
| 42 | rejected.push(`${r.network} ${r.asset}: unknown asset, cannot price`); |
| 43 | continue; |
| 44 | } |
| 45 | let price: bigint; |
| 46 | try { |
| 47 | price = priceUsdMicro(asset, r.amount); |
| 48 | } catch { |
| 49 | rejected.push(`${r.network} ${r.asset}: malformed amount "${r.amount}"`); |
| 50 | continue; |
| 51 | } |
| 52 | quotes.push({ requirements: r, priceUsdMicro: price, assetSymbol: asset.symbol }); |
| 53 | } |
| 54 | return { quotes, rejected }; |
| 55 | } |
| 56 | |
| 57 | export interface SignOptions { |
| 58 | /** Clamp on the server's maxTimeoutSeconds. Bounds validBefore. */ |
| 59 | maxAuthorizationLifetimeSeconds: number; |
| 60 | now?: () => number; |
| 61 | randomBytes?: (n: number) => Uint8Array; |
| 62 | } |
| 63 | |
| 64 | /** |
| 65 | * Sign an EIP-3009 authorization. |
| 66 | * |
| 67 | * Two deliberate departures from the reference client: |
| 68 | * |
| 69 | * 1. The EIP-712 domain comes from our pinned registry, never from |
| 70 | * `requirements.extra`. The server does not get to choose the domain our key |
| 71 | * signs over. |
| 72 | * 2. `validBefore` is clamped to `maxAuthorizationLifetimeSeconds`. The reference |
| 73 | * client uses the server's `maxTimeoutSeconds` unbounded, which lets a server |
| 74 | * hold a valid signed authorization and settle it long after you walked away. |
| 75 | */ |
| 76 | export async function signExactEvm( |
| 77 | account: LocalAccount, |
| 78 | quote: Quote, |
| 79 | opts: SignOptions, |
| 80 | ): Promise<PaymentPayload> { |
| 81 | const r: PaymentRequirements = quote.requirements; |
| 82 | const asset = lookupAsset(r.network, r.asset); |
| 83 | if (!asset) throw new Error(`refusing to sign for unpinned asset ${r.asset} on ${r.network}`); |
| 84 | |
| 85 | const now = Math.floor((opts.now?.() ?? Date.now()) / 1000); |
| 86 | const rand = opts.randomBytes ?? ((n: number) => crypto.getRandomValues(new Uint8Array(n))); |
| 87 | |
| 88 | const lifetime = Math.min( |
| 89 | Math.max(1, r.maxTimeoutSeconds || 0), |
| 90 | opts.maxAuthorizationLifetimeSeconds, |
| 91 | ); |
| 92 | |
| 93 | const authorization: Eip3009Authorization = { |
| 94 | from: account.address, |
| 95 | to: getAddress(r.payTo), |
| 96 | value: r.amount, |
| 97 | // Backdated for clock skew between us and the settling facilitator. |
| 98 | validAfter: (now - 600).toString(), |
| 99 | validBefore: (now + lifetime).toString(), |
| 100 | nonce: toHex(rand(32)), |
| 101 | }; |
| 102 | |
| 103 | const signature = await account.signTypedData({ |
| 104 | domain: domainFor(asset), |
| 105 | types: AUTHORIZATION_TYPES, |
| 106 | primaryType: "TransferWithAuthorization", |
| 107 | message: { |
| 108 | from: getAddress(authorization.from), |
| 109 | to: getAddress(authorization.to), |
| 110 | value: BigInt(authorization.value), |
| 111 | validAfter: BigInt(authorization.validAfter), |
| 112 | validBefore: BigInt(authorization.validBefore), |
| 113 | nonce: authorization.nonce, |
| 114 | }, |
| 115 | }); |
| 116 | |
| 117 | return { |
| 118 | x402Version: 2, |
| 119 | accepted: r, |
| 120 | payload: { signature, authorization }, |
| 121 | }; |
| 122 | } |
| 123 | |
| 124 | export function domainFor(asset: PinnedAsset) { |
| 125 | return { |
| 126 | name: asset.eip712.name, |
| 127 | version: asset.eip712.version, |
| 128 | chainId: evmChainId(asset.network), |
| 129 | verifyingContract: getAddress(asset.address), |
| 130 | } as const; |
| 131 | } |