@toon-protocol/client 2.1.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/keys/KeyDerivation.ts","../src/utils/base58.ts","../src/presets.ts"],"sourcesContent":["/**\n * One BIP-39 phrase → an EVM key and a Solana key.\n *\n * ## Which path an EVM key comes from\n *\n * There are two, and the difference is historical rather than cryptographic.\n *\n * - **`standard`** — `m/44'/60'/0'/0/{accountIndex}`, BIP-44's registered coin\n * type for Ethereum. This is what every wallet derives, so the same phrase\n * typed into MetaMask or a hardware wallet produces the same address: the\n * channel wallet can be inspected, topped up or swept without this package.\n * New keystores use it.\n *\n * - **`legacy`** — `m/44'/1237'/0'/0/{accountIndex}`, Nostr's coin type. Before\n * 1.0 this client derived one secp256k1 key and used it for both a Nostr\n * identity and an EVM account, so the EVM key sat on Nostr's path. The Nostr\n * half is gone, but the addresses are not: they hold channels with real\n * collateral. A keystore written before 1.0 records no scheme and is read as\n * `legacy`, so nothing moves under an existing deployment.\n *\n * Solana is unaffected — `m/44'/501'/{accountIndex}'/0'`, SLIP-0010, all\n * hardened, which is what Phantom and the Solana CLI derive.\n */\nimport { privateKeyToAccount } from 'viem/accounts';\nimport { toHex } from 'viem';\nimport {\n generateMnemonic as _genMnemonic,\n validateMnemonic as _validateMnemonic,\n mnemonicToSeedSync,\n} from '@scure/bip39';\nimport { wordlist as english } from '@scure/bip39/wordlists/english';\nimport { HDKey } from '@scure/bip32';\nimport { hmac } from '@noble/hashes/hmac';\nimport { sha512 } from '@noble/hashes/sha512';\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { secp256k1 } from '@noble/curves/secp256k1.js';\nimport { base58Encode } from '../utils/base58.js';\nimport type { DerivedIdentity } from './types.js';\n\n/** How a mnemonic becomes an EVM key. See this module's own docs. */\nexport type KeyDerivationScheme = 'standard' | 'legacy';\n\n/** BIP-44 coin type 60: Ethereum, and every EVM chain by convention. */\nconst EVM_COIN_TYPE_STANDARD = 60;\n/** BIP-44 coin type 1237: Nostr. What this client used before 1.0. */\nconst EVM_COIN_TYPE_LEGACY = 1237;\n\n/** Generate a new 12-word BIP-39 mnemonic. */\nexport function generateMnemonic(): string {\n return _genMnemonic(english, 128);\n}\n\n/** Is this a well-formed BIP-39 phrase with a valid checksum? */\nexport function validateMnemonic(mnemonic: string): boolean {\n return _validateMnemonic(mnemonic, english);\n}\n\n/** Maximum valid BIP-32 non-hardened child index (2^31 − 1). */\nconst MAX_BIP32_INDEX = 0x7fffffff;\n\nfunction assertValidAccountIndex(accountIndex: number): void {\n if (\n !Number.isInteger(accountIndex) ||\n accountIndex < 0 ||\n accountIndex > MAX_BIP32_INDEX\n ) {\n throw new Error(\n `accountIndex must be an integer in [0, ${MAX_BIP32_INDEX}]; got ${String(accountIndex)}`\n );\n }\n}\n\n/** The BIP-44 path an EVM key is derived at, under a given scheme. */\nexport function evmDerivationPath(\n scheme: KeyDerivationScheme,\n accountIndex = 0\n): string {\n const coinType =\n scheme === 'legacy' ? EVM_COIN_TYPE_LEGACY : EVM_COIN_TYPE_STANDARD;\n return `m/44'/${String(coinType)}'/0'/0/${String(accountIndex)}`;\n}\n\nfunction deriveEvmKey(\n seed: Uint8Array,\n scheme: KeyDerivationScheme,\n accountIndex: number\n): DerivedIdentity['evm'] {\n const child = HDKey.fromMasterSeed(seed).derive(\n evmDerivationPath(scheme, accountIndex)\n );\n if (!child.privateKey) {\n throw new Error('Failed to derive an EVM private key from the seed');\n }\n return evmIdentityFromKey(new Uint8Array(child.privateKey));\n}\n\n/** The account an existing secp256k1 secret belongs to. */\nexport function evmIdentityFromKey(\n privateKey: Uint8Array\n): DerivedIdentity['evm'] {\n const account = privateKeyToAccount(toHex(privateKey));\n return { privateKey, address: account.address };\n}\n\n/**\n * SLIP-0010 Ed25519 derivation at `m/44'/501'/{accountIndex}'/0'`.\n *\n * Ed25519 has no non-hardened derivation, so every level is hardened and the\n * chain code is carried by hand rather than through `HDKey` (which implements\n * BIP-32 for secp256k1).\n */\nfunction deriveSolanaKey(\n seed: Uint8Array,\n accountIndex: number\n): DerivedIdentity['solana'] {\n const encoder = new TextEncoder();\n let I = hmac(sha512, encoder.encode('ed25519 seed'), seed);\n let key = I.slice(0, 32);\n let chainCode = I.slice(32);\n\n const indices = [\n 0x8000002c, // 44'\n 0x800001f5, // 501'\n (0x80000000 + accountIndex) >>> 0, // {accountIndex}'\n 0x80000000, // 0'\n ];\n\n for (const index of indices) {\n const data = new Uint8Array(37);\n data[0] = 0x00;\n data.set(key, 1);\n data[33] = (index >>> 24) & 0xff;\n data[34] = (index >>> 16) & 0xff;\n data[35] = (index >>> 8) & 0xff;\n data[36] = index & 0xff;\n\n I = hmac(sha512, chainCode, data);\n key = I.slice(0, 32);\n chainCode = I.slice(32);\n }\n\n const publicKeyBytes = ed25519.getPublicKey(key);\n // A Solana secret key is the 32-byte seed followed by its public key.\n const keypair = new Uint8Array(64);\n keypair.set(key, 0);\n keypair.set(publicKeyBytes, 32);\n\n return { secretKey: keypair, publicKey: base58Encode(publicKeyBytes) };\n}\n\nexport interface DeriveIdentityOptions {\n accountIndex?: number;\n /** Default `'standard'`. */\n scheme?: KeyDerivationScheme;\n}\n\n/**\n * Derive both chain keys from a mnemonic.\n *\n * The seed is zeroed before returning; the derived keys are not, because they\n * are the return value.\n */\nexport function deriveFullIdentity(\n mnemonic: string,\n options: DeriveIdentityOptions | number = {}\n): DerivedIdentity {\n // `deriveFullIdentity(mnemonic, 3)` used to mean account index 3.\n const opts: DeriveIdentityOptions =\n typeof options === 'number' ? { accountIndex: options } : options;\n const accountIndex = opts.accountIndex ?? 0;\n const scheme = opts.scheme ?? 'standard';\n assertValidAccountIndex(accountIndex);\n\n const seed = mnemonicToSeedSync(mnemonic);\n try {\n return {\n evm: deriveEvmKey(seed, scheme, accountIndex),\n solana: deriveSolanaKey(seed, accountIndex),\n };\n } finally {\n seed.fill(0);\n }\n}\n\n/**\n * A random identity, for tests and ephemeral use. The keys are unrelated to\n * each other and to any mnemonic, so nothing here can be recovered from a\n * phrase — generate a mnemonic instead if the keys need to outlive the process.\n */\nexport function generateRandomIdentity(): DerivedIdentity {\n const evmKey = secp256k1.utils.randomSecretKey();\n const solanaSeed = ed25519.utils.randomSecretKey();\n const solanaPublic = ed25519.getPublicKey(solanaSeed);\n const keypair = new Uint8Array(64);\n keypair.set(solanaSeed, 0);\n keypair.set(solanaPublic, 32);\n return {\n evm: evmIdentityFromKey(evmKey),\n solana: { secretKey: keypair, publicKey: base58Encode(solanaPublic) },\n };\n}\n","/**\n * Base58 (Bitcoin alphabet) — the encoding every Solana address, program id,\n * mint and signature-free pubkey arrives in.\n *\n * A thin wrapper over `@scure/base` rather than a hand-rolled implementation:\n * the same audited primitive already sits under `@scure/bip32`, so this adds no\n * install weight, and base58 decoding is exactly the kind of loop where a\n * hand-rolled version is wrong only for inputs you did not test.\n *\n * Replaces `@toon-protocol/core`'s `base58Encode`/`base58Decode`.\n */\nimport { base58 } from '@scure/base';\n\n/** Encode raw bytes as base58. */\nexport function base58Encode(bytes: Uint8Array): string {\n return base58.encode(bytes);\n}\n\n/**\n * Decode base58 text to raw bytes.\n *\n * Throws on any character outside the alphabet — a Solana pubkey that fails to\n * decode is a caller error worth surfacing, never something to coerce.\n */\nexport function base58Decode(text: string): Uint8Array {\n return base58.decode(text);\n}\n","/**\n * Well-known values for the public TOON devnet.\n *\n * **These are conveniences, never authorities.** Every settlement fact a client\n * actually pays against — the chain, the counterparty address, the token\n * network, the mint, the decimals — comes from the connector's own `GET /ilp`,\n * because the connector proved each of them against a live chain when it booted\n * (`self-description-spec.md` ND-07). Two declarations of one fact is how a\n * mainnet node comes to be described as devnet, so nothing here is ever\n * consulted in preference to the document a node answers with.\n *\n * What they are good for: a default RPC endpoint, a default faucet, and a URL to\n * put in an example so it can be run rather than adapted.\n *\n * Everything below is a **testnet**. Base Sepolia and Solana devnet carry no\n * real value, and the USDC is a mock mint anyone can draw from the faucet.\n */\n\n/** A connector on the public devnet. */\nexport interface DevnetNode {\n /** Client-edge base URL — `GET /ilp` here returns everything else. */\n url: string;\n /** The route this node terminates. */\n route: string;\n /** That route's base price, in base units of the settlement asset (USDC, 6dp). */\n price: bigint;\n /**\n * Added per kibibyte of sealed payload, on a route that meters by size. A\n * packet on such a route always costs strictly more than `price`.\n */\n pricePerKib?: bigint;\n /** Set when the route accepts only one carriage. */\n requiredTransport?: 'http' | 'btp';\n}\n\nexport const DEVNET = {\n /**\n * The store node: an Arweave-backed object store behind `g.toon.store`, and\n * the one route here that METERS — 1000 base units (0.001 USDC) plus 10 per\n * kibibyte of sealed payload, so no packet on it costs only `price`.\n */\n store: {\n url: 'https://proxy.ario.devnet.toonprotocol.dev',\n route: 'g.toon.store',\n price: 1000n,\n pricePerKib: 10n,\n } satisfies DevnetNode,\n\n /**\n * The gas station behind `g.toon.gas`, priced flat at 1000 base units.\n * Reachable directly, or through the relay at `g.toon.relay.gas`.\n */\n gas: {\n url: 'https://proxy.gas.devnet.toonprotocol.dev',\n route: 'g.toon.gas',\n price: 1000n,\n } satisfies DevnetNode,\n\n /**\n * The relay node behind `g.toon.relay`, priced at 1 base unit. Its route is\n * pinned to **BTP**: an HTTP one-shot to it is refused with the same terms\n * document an unpaid request gets, carrying `extra.requiredTransport`.\n */\n relay: {\n url: 'https://proxy.relay.devnet.toonprotocol.dev',\n route: 'g.toon.relay',\n price: 1n,\n requiredTransport: 'btp',\n } satisfies DevnetNode,\n\n /**\n * The relay's ephemeral lane, priced at **zero** — the one route on the devnet\n * that exercises the whole wire while holding no funds and no channel. Not\n * carriage-pinned, unlike `g.toon.relay` beside it.\n */\n ephemeral: {\n url: 'https://proxy.relay.devnet.toonprotocol.dev',\n route: 'g.toon.relay.ephemeral',\n price: 0n,\n } satisfies DevnetNode,\n\n /** Test funds. `POST /api/base-sepolia/request` and `/api/solana/usdc-request`. */\n faucet: 'https://faucet.devnet.toonprotocol.dev',\n\n /** Base Sepolia. The registry is the stable address; the token network is resolved from it. */\n evm: {\n chainId: 84532,\n rpcUrl: 'https://sepolia.base.org',\n tokenNetworkRegistry: '0x0c41D9D424d6B075A3cEa1068a694f7847a8CCa5',\n tokenNetwork: '0xe9E05dfecfe165266C88d73e61D483612651952a',\n /** Mock USDC, 6 decimals, ungated `mint()`. */\n tokenAddress: '0x49beE1Bca5d15Fb0963117923403F9498119a9Ce',\n decimals: 6,\n },\n\n /** Solana devnet — the public cluster, not a local validator. */\n solana: {\n rpcUrl: 'https://api.devnet.solana.com',\n /** The deployed `payment-channel` program. Bound into every claim (ADR 0053). */\n programId: '2aEVJ8koKD8LTZrLRSGtAtU7LBt4e7QjjCgf1kzQ7Rip',\n /** Mock USDC SPL mint, 6 decimals. */\n tokenAddress: '34eSxY7qxQ4GzyhDJ8GpUcTz1WWzruGbJbR8q6TtxfQU',\n decimals: 6,\n },\n} as const;\n\n/** The default RPC URL for a chain when a caller configures none. */\nexport function defaultRpcUrl(chain: 'evm' | 'solana'): string {\n return chain === 'evm' ? DEVNET.evm.rpcUrl : DEVNET.solana.rpcUrl;\n}\n"],"mappings":";AAuBA,SAAS,2BAA2B;AACpC,SAAS,aAAa;AACtB;AAAA,EACE,oBAAoB;AAAA,EACpB,oBAAoB;AAAA,EACpB;AAAA,OACK;AACP,SAAS,YAAY,eAAe;AACpC,SAAS,aAAa;AACtB,SAAS,YAAY;AACrB,SAAS,cAAc;AACvB,SAAS,eAAe;AACxB,SAAS,iBAAiB;;;ACxB1B,SAAS,cAAc;AAGhB,SAAS,aAAa,OAA2B;AACtD,SAAO,OAAO,OAAO,KAAK;AAC5B;AAQO,SAAS,aAAa,MAA0B;AACrD,SAAO,OAAO,OAAO,IAAI;AAC3B;;;ADiBA,IAAM,yBAAyB;AAE/B,IAAM,uBAAuB;AAGtB,SAAS,mBAA2B;AACzC,SAAO,aAAa,SAAS,GAAG;AAClC;AAGO,SAAS,iBAAiB,UAA2B;AAC1D,SAAO,kBAAkB,UAAU,OAAO;AAC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