@toon-protocol/client 3.3.0 → 4.0.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.
- package/dist/{chunk-PTTRHLYV.js → chunk-2DGVNDKA.js} +2 -2
- package/dist/{chunk-G36D22II.js → chunk-CG3OXV74.js} +4379 -4912
- package/dist/chunk-CG3OXV74.js.map +1 -0
- package/dist/{chunk-O6KX7MHD.js → chunk-WJKJ6Y4N.js} +17 -8
- package/dist/{chunk-O6KX7MHD.js.map → chunk-WJKJ6Y4N.js.map} +1 -1
- package/dist/cli/main.js +134 -118
- package/dist/cli/main.js.map +1 -1
- package/dist/{client-FFEFAMJ4.js → client-7YIJOR5K.js} +7 -7
- package/dist/{hidden-service-BsBH2HNi.d.ts → hidden-service-BtIv3u0L.d.ts} +2 -123
- package/dist/index.d.ts +2743 -2972
- package/dist/index.js +125 -188
- package/dist/index.js.map +1 -1
- package/dist/transport/hidden-service.d.ts +1 -1
- package/package.json +2 -1
- package/dist/chunk-G36D22II.js.map +0 -1
- /package/dist/{chunk-PTTRHLYV.js.map → chunk-2DGVNDKA.js.map} +0 -0
- /package/dist/{client-FFEFAMJ4.js.map → client-7YIJOR5K.js.map} +0 -0
|
@@ -175,7 +175,8 @@ var DEVNET = {
|
|
|
175
175
|
/**
|
|
176
176
|
* The relay node behind `g.toon.relay`, priced at 1 base unit. Its route is
|
|
177
177
|
* pinned to **BTP**: an HTTP one-shot to it is refused with the same terms
|
|
178
|
-
* document an unpaid request gets, carrying `
|
|
178
|
+
* document an unpaid request gets, carrying `requiredTransport` in
|
|
179
|
+
* `extensions.toon.info`.
|
|
179
180
|
*/
|
|
180
181
|
relay: {
|
|
181
182
|
url: "https://proxy.relay.devnet.toonprotocol.dev",
|
|
@@ -195,12 +196,17 @@ var DEVNET = {
|
|
|
195
196
|
},
|
|
196
197
|
/** Test funds. `POST /api/base-sepolia/request` and `/api/solana/usdc-request`. */
|
|
197
198
|
faucet: "https://faucet.devnet.toonprotocol.dev",
|
|
198
|
-
/**
|
|
199
|
+
/**
|
|
200
|
+
* The Onboarder (toon-protocol/infra#23): a stock x402 facilitator on Base
|
|
201
|
+
* Sepolia that submits a channel deposit and pays its gas, so a wallet
|
|
202
|
+
* holding devnet USDC and no ETH can open a channel.
|
|
203
|
+
*/
|
|
204
|
+
facilitator: "https://onboard.devnet.toonprotocol.dev",
|
|
205
|
+
/** Base Sepolia. */
|
|
199
206
|
evm: {
|
|
200
207
|
chainId: 84532,
|
|
208
|
+
network: "eip155:84532",
|
|
201
209
|
rpcUrl: "https://sepolia.base.org",
|
|
202
|
-
tokenNetworkRegistry: "0x0c41D9D424d6B075A3cEa1068a694f7847a8CCa5",
|
|
203
|
-
tokenNetwork: "0x1B4606218ceE5Bf02B546e416905F4D3FC8a0249",
|
|
204
210
|
/** Devnet USDC: Circle FiatToken v2.2 (ERC-3009, EIP-2612), 6 decimals, minter-gated — fund via the faucet (connector#1337). */
|
|
205
211
|
tokenAddress: "0x0C996d7c934c79a6255254875607Fe69df25C0E1",
|
|
206
212
|
decimals: 6
|
|
@@ -208,8 +214,7 @@ var DEVNET = {
|
|
|
208
214
|
/** Solana devnet — the public cluster, not a local validator. */
|
|
209
215
|
solana: {
|
|
210
216
|
rpcUrl: "https://api.devnet.solana.com",
|
|
211
|
-
|
|
212
|
-
programId: "2aEVJ8koKD8LTZrLRSGtAtU7LBt4e7QjjCgf1kzQ7Rip",
|
|
217
|
+
network: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",
|
|
213
218
|
/** Mock USDC SPL mint, 6 decimals. */
|
|
214
219
|
tokenAddress: "34eSxY7qxQ4GzyhDJ8GpUcTz1WWzruGbJbR8q6TtxfQU",
|
|
215
220
|
decimals: 6
|
|
@@ -218,6 +223,9 @@ var DEVNET = {
|
|
|
218
223
|
function defaultRpcUrl(chain) {
|
|
219
224
|
return chain === "evm" ? DEVNET.evm.rpcUrl : DEVNET.solana.rpcUrl;
|
|
220
225
|
}
|
|
226
|
+
function defaultFacilitatorFor(network) {
|
|
227
|
+
return network === DEVNET.evm.network ? DEVNET.facilitator : void 0;
|
|
228
|
+
}
|
|
221
229
|
|
|
222
230
|
export {
|
|
223
231
|
HS_HOSTNAME_REGEX,
|
|
@@ -234,6 +242,7 @@ export {
|
|
|
234
242
|
deriveFullIdentity,
|
|
235
243
|
generateRandomIdentity,
|
|
236
244
|
DEVNET,
|
|
237
|
-
defaultRpcUrl
|
|
245
|
+
defaultRpcUrl,
|
|
246
|
+
defaultFacilitatorFor
|
|
238
247
|
};
|
|
239
|
-
//# sourceMappingURL=chunk-
|
|
248
|
+
//# sourceMappingURL=chunk-WJKJ6Y4N.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/transport/hs-hostname.ts","../src/keys/KeyDerivation.ts","../src/utils/base58.ts","../src/presets.ts"],"sourcesContent":["/**\n * Hidden-service hostname validation for the Anyone Protocol network.\n *\n * The `anon` binary routes hidden-service hostnames under the **`.anyone`** TLD\n * ONLY. A `<host>.anon` name is NOT recognized as a hidden service — anon treats\n * it as a clearnet name and tries to exit-resolve it, which fails\n * (`resolve failed` / `HostUnreachable`). Only `<host>.anyone` triggers anon's\n * `parse_extended_hostname: Anyone dns address lookup` and is validated.\n *\n * Historically this client accepted BOTH `.anon` and `.anyone`, so a `.anon`\n * address was silently accepted and then failed deep in the transport with an\n * opaque error. This module makes `.anyone` the single accepted HS TLD and\n * rejects the near-misses up front with an actionable message.\n *\n * `.onion` is a near-miss too, and a more tempting one: it is a real hidden\n * service, just on a network this client does not dial. We route through `anon`,\n * not `tor`, so accepting a `.onion` address would repeat the exact mistake\n * `.anon` taught us — an address we cannot reach, failing late and cryptically.\n *\n * This is a pure, browser-safe helper (no Node built-ins) so it can be imported\n * from any path, including config validation.\n */\n\n/**\n * A `<host>.anyone` hidden-service hostname. The label is base32 (`a-z2-7`),\n * matching the on-wire onion-style address alphabet anon uses.\n */\nexport const HS_HOSTNAME_REGEX = /^[a-z2-7]+\\.anyone$/;\n\n/** Max length of an HS hostname (defensive bound against pathological input). */\nexport const HS_HOSTNAME_MAX_LENGTH = 80;\n\n/**\n * Returns true iff `s` is a routable `.anyone` hidden-service hostname.\n * Does NOT accept `.anon` or `.onion` (see {@link assertRoutableHsHostname}).\n */\nexport function isRoutableHsHostname(s: unknown): s is string {\n return (\n typeof s === 'string' &&\n s.length <= HS_HOSTNAME_MAX_LENGTH &&\n HS_HOSTNAME_REGEX.test(s)\n );\n}\n\n/**\n * Returns true iff `url` addresses a hidden service — i.e. its host is a\n * routable `.anyone` address.\n *\n * Takes a URL string rather than a hostname because that is what a caller\n * actually holds: a `connector` config value, an `httpEndpoint` off a\n * self-description. A string that is not a URL at all is not a hidden service.\n */\nexport function isHiddenServiceUrl(url: unknown): boolean {\n if (typeof url !== 'string') return false;\n try {\n return isRoutableHsHostname(new URL(url).hostname);\n } catch {\n return false;\n }\n}\n\n/**\n * Validates that `hostname` is a routable `.anyone` hidden-service address.\n *\n * - `<host>.anyone` → returns the hostname unchanged.\n * - `<host>.anon` → throws, pointing at `.anyone` (anon does NOT route\n * `.anon`; it is treated as a clearnet address and fails `HostUnreachable`).\n * - `<host>.onion` → throws, naming the network mismatch: that is Tor, and\n * this client dials the Anyone Protocol.\n * - anything else → throws a generic format error.\n *\n * @throws {Error} if the hostname is not a routable `.anyone` HS address.\n */\nexport function assertRoutableHsHostname(hostname: unknown): string {\n if (typeof hostname === 'string' && /\\.anon$/.test(hostname)) {\n throw new Error(\n `\"${hostname}\" is not a routable hidden-service address; use the .anyone TLD ` +\n `(e.g. \"${hostname.replace(/\\.anon$/, '.anyone')}\"). ` +\n 'The anon daemon only resolves hidden services under .anyone — a .anon ' +\n 'name is treated as a clearnet address and fails (HostUnreachable).'\n );\n }\n if (typeof hostname === 'string' && /\\.onion$/.test(hostname)) {\n throw new Error(\n `\"${hostname}\" is a Tor hidden service, which this client does not dial. ` +\n 'Packets are routed through the Anyone Protocol `anon` daemon, whose ' +\n 'hidden services live under the .anyone TLD.'\n );\n }\n if (!isRoutableHsHostname(hostname)) {\n throw new Error(\n `Invalid hidden-service hostname: ${JSON.stringify(hostname)}. ` +\n `Expected a base32 .anyone address matching ${HS_HOSTNAME_REGEX}.`\n );\n }\n return hostname;\n}\n","/**\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: '0x1B4606218ceE5Bf02B546e416905F4D3FC8a0249',\n /** Devnet USDC: Circle FiatToken v2.2 (ERC-3009, EIP-2612), 6 decimals, minter-gated — fund via the faucet (connector#1337). */\n tokenAddress: '0x0C996d7c934c79a6255254875607Fe69df25C0E1',\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":";AA2BO,IAAM,oBAAoB;AAG1B,IAAM,yBAAyB;AAM/B,SAAS,qBAAqB,GAAyB;AAC5D,SACE,OAAO,MAAM,YACb,EAAE,UAAU,0BACZ,kBAAkB,KAAK,CAAC;AAE5B;AAUO,SAAS,mBAAmB,KAAuB;AACxD,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,MAAI;AACF,WAAO,qBAAqB,IAAI,IAAI,GAAG,EAAE,QAAQ;AAAA,EACnD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAcO,SAAS,yBAAyB,UAA2B;AAClE,MAAI,OAAO,aAAa,YAAY,UAAU,KAAK,QAAQ,GAAG;AAC5D,UAAM,IAAI;AAAA,MACR,IAAI,QAAQ,0EACA,SAAS,QAAQ,WAAW,SAAS,CAAC;AAAA,IAGpD;AAAA,EACF;AACA,MAAI,OA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;AAAA;AAAA,EAGR,KAAK;AAAA,IACH,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,sBAAsB;AAAA,IACtB,cAAc;AAAA;AAAA,IAEd,cAAc;AAAA,IACd,UAAU;AAAA,EACZ;AAAA;AAAA,EAGA,QAAQ;AAAA,IACN,QAAQ;AAAA;AAAA,IAER,WAAW;AAAA;AAAA,IAEX,cAAc;AAAA,IACd,UAAU;AAAA,EACZ;AACF;AAGO,SAAS,cAAc,OAAiC;AAC7D,SAAO,UAAU,QAAQ,OAAO,IAAI,SAAS,OAAO,OAAO;AAC7D;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/transport/hs-hostname.ts","../src/keys/KeyDerivation.ts","../src/utils/base58.ts","../src/presets.ts"],"sourcesContent":["/**\n * Hidden-service hostname validation for the Anyone Protocol network.\n *\n * The `anon` binary routes hidden-service hostnames under the **`.anyone`** TLD\n * ONLY. A `<host>.anon` name is NOT recognized as a hidden service — anon treats\n * it as a clearnet name and tries to exit-resolve it, which fails\n * (`resolve failed` / `HostUnreachable`). Only `<host>.anyone` triggers anon's\n * `parse_extended_hostname: Anyone dns address lookup` and is validated.\n *\n * Historically this client accepted BOTH `.anon` and `.anyone`, so a `.anon`\n * address was silently accepted and then failed deep in the transport with an\n * opaque error. This module makes `.anyone` the single accepted HS TLD and\n * rejects the near-misses up front with an actionable message.\n *\n * `.onion` is a near-miss too, and a more tempting one: it is a real hidden\n * service, just on a network this client does not dial. We route through `anon`,\n * not `tor`, so accepting a `.onion` address would repeat the exact mistake\n * `.anon` taught us — an address we cannot reach, failing late and cryptically.\n *\n * This is a pure, browser-safe helper (no Node built-ins) so it can be imported\n * from any path, including config validation.\n */\n\n/**\n * A `<host>.anyone` hidden-service hostname. The label is base32 (`a-z2-7`),\n * matching the on-wire onion-style address alphabet anon uses.\n */\nexport const HS_HOSTNAME_REGEX = /^[a-z2-7]+\\.anyone$/;\n\n/** Max length of an HS hostname (defensive bound against pathological input). */\nexport const HS_HOSTNAME_MAX_LENGTH = 80;\n\n/**\n * Returns true iff `s` is a routable `.anyone` hidden-service hostname.\n * Does NOT accept `.anon` or `.onion` (see {@link assertRoutableHsHostname}).\n */\nexport function isRoutableHsHostname(s: unknown): s is string {\n return (\n typeof s === 'string' &&\n s.length <= HS_HOSTNAME_MAX_LENGTH &&\n HS_HOSTNAME_REGEX.test(s)\n );\n}\n\n/**\n * Returns true iff `url` addresses a hidden service — i.e. its host is a\n * routable `.anyone` address.\n *\n * Takes a URL string rather than a hostname because that is what a caller\n * actually holds: a `connector` config value, an `httpEndpoint` off a\n * self-description. A string that is not a URL at all is not a hidden service.\n */\nexport function isHiddenServiceUrl(url: unknown): boolean {\n if (typeof url !== 'string') return false;\n try {\n return isRoutableHsHostname(new URL(url).hostname);\n } catch {\n return false;\n }\n}\n\n/**\n * Validates that `hostname` is a routable `.anyone` hidden-service address.\n *\n * - `<host>.anyone` → returns the hostname unchanged.\n * - `<host>.anon` → throws, pointing at `.anyone` (anon does NOT route\n * `.anon`; it is treated as a clearnet address and fails `HostUnreachable`).\n * - `<host>.onion` → throws, naming the network mismatch: that is Tor, and\n * this client dials the Anyone Protocol.\n * - anything else → throws a generic format error.\n *\n * @throws {Error} if the hostname is not a routable `.anyone` HS address.\n */\nexport function assertRoutableHsHostname(hostname: unknown): string {\n if (typeof hostname === 'string' && /\\.anon$/.test(hostname)) {\n throw new Error(\n `\"${hostname}\" is not a routable hidden-service address; use the .anyone TLD ` +\n `(e.g. \"${hostname.replace(/\\.anon$/, '.anyone')}\"). ` +\n 'The anon daemon only resolves hidden services under .anyone — a .anon ' +\n 'name is treated as a clearnet address and fails (HostUnreachable).'\n );\n }\n if (typeof hostname === 'string' && /\\.onion$/.test(hostname)) {\n throw new Error(\n `\"${hostname}\" is a Tor hidden service, which this client does not dial. ` +\n 'Packets are routed through the Anyone Protocol `anon` daemon, whose ' +\n 'hidden services live under the .anyone TLD.'\n );\n }\n if (!isRoutableHsHostname(hostname)) {\n throw new Error(\n `Invalid hidden-service hostname: ${JSON.stringify(hostname)}. ` +\n `Expected a base32 .anyone address matching ${HS_HOSTNAME_REGEX}.`\n );\n }\n return hostname;\n}\n","/**\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 `requiredTransport` in\n * `extensions.toon.info`.\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 /**\n * The Onboarder (toon-protocol/infra#23): a stock x402 facilitator on Base\n * Sepolia that submits a channel deposit and pays its gas, so a wallet\n * holding devnet USDC and no ETH can open a channel.\n */\n facilitator: 'https://onboard.devnet.toonprotocol.dev',\n\n /** Base Sepolia. */\n evm: {\n chainId: 84532,\n network: 'eip155:84532',\n rpcUrl: 'https://sepolia.base.org',\n /** Devnet USDC: Circle FiatToken v2.2 (ERC-3009, EIP-2612), 6 decimals, minter-gated — fund via the faucet (connector#1337). */\n tokenAddress: '0x0C996d7c934c79a6255254875607Fe69df25C0E1',\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 network: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1',\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\n/**\n * The facilitator a Base deposit goes through when a caller names none: the\n * devnet's own on Base Sepolia, and nothing elsewhere — a mainnet deposit\n * through a devnet service would be refused anyway, and silently picking a\n * third party to relay real money is not this package's decision to make.\n */\nexport function defaultFacilitatorFor(network: string): string | undefined {\n return network === DEVNET.evm.network ? DEVNET.facilitator : undefined;\n}\n"],"mappings":";AA2BO,IAAM,oBAAoB;AAG1B,IAAM,yBAAyB;AAM/B,SAAS,qBAAqB,GAAyB;AAC5D,SACE,OAAO,MAAM,YACb,EAAE,UAAU,0BACZ,kBAAkB,KAAK,CAAC;AAE5B;AAUO,SAAS,mBAAmB,KAAuB;AACxD,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,MAAI;AACF,WAAO,qBAAqB,IAAI,IAAI,GAAG,EAAE,QAAQ;AAAA,EACnD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAcO,SAAS,yBAAyB,UAA2B;AAClE,MAAI,OAAO,aAAa,YAAY,UAAU,KAAK,QA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B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,WAAW;AAAA,IACT,KAAK;AAAA,IACL,OAAO;AAAA,IACP,OAAO;AAAA,EACT;AAAA;AAAA,EAGA,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOR,aAAa;AAAA;AAAA,EAGb,KAAK;AAAA,IACH,SAAS;AAAA,IACT,SAAS;AAAA,IACT,QAAQ;AAAA;AAAA,IAER,cAAc;AAAA,IACd,UAAU;AAAA,EACZ;AAAA;AAAA,EAGA,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,SAAS;AAAA;AAAA,IAET,cAAc;AAAA,IACd,UAAU;AAAA,EACZ;AACF;AAGO,SAAS,cAAc,OAAiC;AAC7D,SAAO,UAAU,QAAQ,OAAO,IAAI,SAAS,OAAO,OAAO;AAC7D;AAQO,SAAS,sBAAsB,SAAqC;AACzE,SAAO,YAAY,OAAO,IAAI,UAAU,OAAO,cAAc;AAC/D;","names":[]}
|
package/dist/cli/main.js
CHANGED
|
@@ -3,14 +3,14 @@ import {
|
|
|
3
3
|
generateKeystore,
|
|
4
4
|
importKeystore,
|
|
5
5
|
openKeystore
|
|
6
|
-
} from "../chunk-
|
|
6
|
+
} from "../chunk-2DGVNDKA.js";
|
|
7
7
|
import {
|
|
8
8
|
DEVNET,
|
|
9
9
|
deriveFullIdentity,
|
|
10
10
|
evmDerivationPath,
|
|
11
11
|
generateRandomIdentity,
|
|
12
12
|
isHiddenServiceUrl
|
|
13
|
-
} from "../chunk-
|
|
13
|
+
} from "../chunk-WJKJ6Y4N.js";
|
|
14
14
|
|
|
15
15
|
// src/cli/main.ts
|
|
16
16
|
import { homedir as homedir3 } from "os";
|
|
@@ -80,6 +80,11 @@ var GLOBAL_OPTIONS = {
|
|
|
80
80
|
arg: "URL",
|
|
81
81
|
help: "SOCKS5h proxy for a .anyone connector, e.g. socks5h://127.0.0.1:9050. Env TOON_SOCKS. Default: start a managed anon daemon."
|
|
82
82
|
},
|
|
83
|
+
facilitator: {
|
|
84
|
+
type: "string",
|
|
85
|
+
arg: "URL",
|
|
86
|
+
help: "The x402 facilitator that relays a Base channel deposit and pays its gas. Env TOON_FACILITATOR. Default: the devnet Onboarder on Base Sepolia."
|
|
87
|
+
},
|
|
83
88
|
json: { type: "boolean", help: "Print one JSON document on stdout and nothing else." },
|
|
84
89
|
quiet: { type: "boolean", help: "Suppress progress and warnings on stderr." },
|
|
85
90
|
help: { type: "boolean", short: "h", help: "Show this help." },
|
|
@@ -95,11 +100,10 @@ var COMMAND_OPTIONS = {
|
|
|
95
100
|
type: "boolean",
|
|
96
101
|
help: "Show the addresses of every derivation scheme, not just the one in use."
|
|
97
102
|
},
|
|
98
|
-
deposit: {
|
|
99
|
-
"settlement-timeout": {
|
|
103
|
+
deposit: {
|
|
100
104
|
type: "string",
|
|
101
|
-
arg: "
|
|
102
|
-
help: "
|
|
105
|
+
arg: "BASE_UNITS",
|
|
106
|
+
help: "What a channel is opened with, in base units. Default 100000 (0.10 USDC)."
|
|
103
107
|
},
|
|
104
108
|
"connector-view": {
|
|
105
109
|
type: "boolean",
|
|
@@ -180,7 +184,7 @@ var COMMANDS = {
|
|
|
180
184
|
options: [],
|
|
181
185
|
minPositionals: 1,
|
|
182
186
|
maxPositionals: 1,
|
|
183
|
-
details: ["Needs
|
|
187
|
+
details: ["Needs a channel already paid on: a probe resends the last voucher, which spends nothing."]
|
|
184
188
|
},
|
|
185
189
|
send: {
|
|
186
190
|
summary: "Pay for one HTTP request and print the answer.",
|
|
@@ -199,12 +203,14 @@ var COMMANDS = {
|
|
|
199
203
|
channel: {
|
|
200
204
|
summary: "Open, fund, inspect, close and settle the payment channel.",
|
|
201
205
|
usage: "channel open|deposit <amount>|close|settle|status [--deposit BASE_UNITS] [--connector-view]",
|
|
202
|
-
options: ["deposit", "
|
|
206
|
+
options: ["deposit", "connector-view"],
|
|
203
207
|
minPositionals: 1,
|
|
204
208
|
maxPositionals: 2,
|
|
205
209
|
details: [
|
|
206
|
-
"
|
|
207
|
-
"
|
|
210
|
+
"Opening and depositing cost no gas: a facilitator relays the deposit on Base,",
|
|
211
|
+
"the connector sponsors the open on Solana. `close` and `settle` are your own",
|
|
212
|
+
"transactions, on your gas: `close` starts the exit window, and `settle` takes",
|
|
213
|
+
"the unspent deposit back once it has elapsed."
|
|
208
214
|
]
|
|
209
215
|
},
|
|
210
216
|
"claim-state": {
|
|
@@ -428,6 +434,7 @@ var CHAIN_ENV = "TOON_CHAIN";
|
|
|
428
434
|
var RPC_ENV = "TOON_RPC_URL";
|
|
429
435
|
var CHANNEL_STORE_ENV = "TOON_CHANNEL_STORE";
|
|
430
436
|
var SOCKS_ENV = "TOON_SOCKS";
|
|
437
|
+
var FACILITATOR_ENV = "TOON_FACILITATOR";
|
|
431
438
|
function defaultChannelStorePath(home = homedir2()) {
|
|
432
439
|
return join2(home, ".toon", "channels.json");
|
|
433
440
|
}
|
|
@@ -469,9 +476,13 @@ function resolveSettings(values, env, options = {}) {
|
|
|
469
476
|
const socksFlag = stringOption(values, "socks");
|
|
470
477
|
const socksEnv = env[SOCKS_ENV];
|
|
471
478
|
const socksProxy = socksFlag !== void 0 && socksFlag.length > 0 ? socksFlag : socksEnv !== void 0 && socksEnv.length > 0 ? socksEnv : void 0;
|
|
479
|
+
const facilitator = stringOption(values, "facilitator") ?? env[FACILITATOR_ENV];
|
|
480
|
+
const deposit = stringOption(values, "deposit");
|
|
472
481
|
const settings = {
|
|
473
482
|
connector,
|
|
474
483
|
connectorSource,
|
|
484
|
+
...facilitator !== void 0 && facilitator.length > 0 ? { facilitatorUrl: facilitator } : {},
|
|
485
|
+
...deposit !== void 0 ? { deposit } : {},
|
|
475
486
|
...chain !== void 0 ? { chain } : {},
|
|
476
487
|
...rpcUrl !== void 0 && rpcUrl.length > 0 ? { rpcUrl } : {},
|
|
477
488
|
channelStore,
|
|
@@ -529,7 +540,9 @@ function buildClientConfig(settings, keys) {
|
|
|
529
540
|
// See this module's docs: a command never opens a channel as a side effect.
|
|
530
541
|
autoOpenChannel: false,
|
|
531
542
|
...settings.chain !== void 0 ? { chain: settings.chain } : {},
|
|
532
|
-
...settings.rpcUrl !== void 0 ? { rpcUrl: settings.rpcUrl } : {}
|
|
543
|
+
...settings.rpcUrl !== void 0 ? { rpcUrl: settings.rpcUrl } : {},
|
|
544
|
+
...settings.facilitatorUrl !== void 0 ? { facilitatorUrl: settings.facilitatorUrl } : {},
|
|
545
|
+
...settings.deposit !== void 0 ? { deposit: settings.deposit } : {}
|
|
533
546
|
};
|
|
534
547
|
if (keys.kind === "mnemonic") {
|
|
535
548
|
return { ...base, mnemonic: keys.mnemonic, keyDerivation: keys.derivation };
|
|
@@ -542,7 +555,7 @@ function buildClientConfig(settings, keys) {
|
|
|
542
555
|
};
|
|
543
556
|
}
|
|
544
557
|
async function defaultCreateClient(config) {
|
|
545
|
-
const module = await import("../client-
|
|
558
|
+
const module = await import("../client-7YIJOR5K.js");
|
|
546
559
|
const factory = module.ToonClient;
|
|
547
560
|
if (factory === void 0) {
|
|
548
561
|
throw new Error(
|
|
@@ -612,20 +625,23 @@ async function defaultStartAnon(log) {
|
|
|
612
625
|
|
|
613
626
|
// src/cli/output.ts
|
|
614
627
|
import { formatUnits } from "viem";
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
628
|
+
var KNOWN_USDC = new Set(
|
|
629
|
+
[
|
|
630
|
+
DEVNET.evm.tokenAddress,
|
|
631
|
+
DEVNET.solana.tokenAddress,
|
|
632
|
+
"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
|
633
|
+
"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
|
|
634
|
+
].map((a) => a.startsWith("0x") ? a.toLowerCase() : a)
|
|
635
|
+
);
|
|
636
|
+
function known(asset) {
|
|
637
|
+
if (asset === void 0) return false;
|
|
638
|
+
return KNOWN_USDC.has(asset.startsWith("0x") ? asset.toLowerCase() : asset);
|
|
621
639
|
}
|
|
622
|
-
function
|
|
623
|
-
|
|
624
|
-
return { decimals: settlement.decimals, symbol: assetSymbol(settlement.tokenAddress) };
|
|
640
|
+
function assetInfo(asset) {
|
|
641
|
+
return known(asset) ? { decimals: 6, symbol: "USDC" } : {};
|
|
625
642
|
}
|
|
626
|
-
function
|
|
627
|
-
|
|
628
|
-
return { decimals: terms.decimals, symbol: assetSymbol(terms.token) };
|
|
643
|
+
function assetFromSettlement(terms) {
|
|
644
|
+
return assetInfo(terms?.asset);
|
|
629
645
|
}
|
|
630
646
|
function formatAmount(amount, asset = {}) {
|
|
631
647
|
const base = typeof amount === "bigint" ? amount : BigInt(amount);
|
|
@@ -750,21 +766,23 @@ async function run(ctx) {
|
|
|
750
766
|
// src/cli/commands/channel.ts
|
|
751
767
|
function stateRows(state, asset) {
|
|
752
768
|
const rows = [
|
|
753
|
-
["channel", state.channelId],
|
|
754
|
-
["
|
|
755
|
-
["counterparty", state.counterparty],
|
|
756
|
-
["status", state.status],
|
|
769
|
+
["channel", state.channel.channelId],
|
|
770
|
+
["network", state.channel.network],
|
|
757
771
|
["deposit", formatAmount(state.depositTotal, asset)],
|
|
758
|
-
["
|
|
759
|
-
[
|
|
760
|
-
|
|
772
|
+
["signed", formatAmount(state.signed, asset)],
|
|
773
|
+
[
|
|
774
|
+
"available",
|
|
775
|
+
formatAmount(
|
|
776
|
+
state.depositTotal > state.signed ? state.depositTotal - state.signed : 0n,
|
|
777
|
+
asset
|
|
778
|
+
)
|
|
779
|
+
]
|
|
761
780
|
];
|
|
762
|
-
if (state.
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
if (state.onChain?.settleableAt !== void 0) {
|
|
766
|
-
rows.push(["settleable at", `${state.onChain.settleableAt.toString()} (unix seconds)`]);
|
|
781
|
+
if (state.closedAt !== void 0) rows.push(["closed at", `${state.closedAt.toString()} (unix seconds)`]);
|
|
782
|
+
if (state.settleableAt !== void 0) {
|
|
783
|
+
rows.push(["settleable at", `${state.settleableAt.toString()} (unix seconds)`]);
|
|
767
784
|
}
|
|
785
|
+
if (state.settledAt !== void 0) rows.push(["settled at", `${state.settledAt.toString()} (unix seconds)`]);
|
|
768
786
|
return rows;
|
|
769
787
|
}
|
|
770
788
|
function connectorRows(entry, asset) {
|
|
@@ -772,39 +790,34 @@ function connectorRows(entry, asset) {
|
|
|
772
790
|
return [["connector", `cannot report this channel (${entry.error})`]];
|
|
773
791
|
}
|
|
774
792
|
return [
|
|
775
|
-
["connector nonce", String(entry.nonce)],
|
|
776
793
|
["connector claimed", formatAmount(entry.cumulativeClaimed, asset)],
|
|
777
|
-
[
|
|
778
|
-
|
|
779
|
-
entry.depositTotal === null ? "declared only" : formatAmount(entry.depositTotal, asset)
|
|
780
|
-
],
|
|
781
|
-
[
|
|
782
|
-
"connector available",
|
|
783
|
-
entry.available === null ? "unknown" : formatAmount(entry.available, asset)
|
|
784
|
-
]
|
|
794
|
+
["connector max", formatAmount(entry.maxCumulative, asset)],
|
|
795
|
+
["connector available", formatAmount(entry.available, asset)]
|
|
785
796
|
];
|
|
786
797
|
}
|
|
798
|
+
function exitRows(result) {
|
|
799
|
+
const rows = [["channel", result.channelId]];
|
|
800
|
+
if (result.transaction !== void 0) rows.push(["tx", result.transaction]);
|
|
801
|
+
if (result.settleableAt !== void 0) rows.push(["settleable at", result.settleableAt.toString()]);
|
|
802
|
+
if (result.error !== void 0) rows.push(["error", result.error]);
|
|
803
|
+
if (result.transaction === void 0 && result.error === void 0 && result.settleableAt === void 0) {
|
|
804
|
+
rows.push(["status", "nothing left to take back"]);
|
|
805
|
+
}
|
|
806
|
+
return rows;
|
|
807
|
+
}
|
|
787
808
|
async function run2(ctx) {
|
|
788
809
|
const sub = ctx.positionals[0];
|
|
789
810
|
if (sub === void 0 || !CHANNEL_SUBCOMMANDS.includes(sub)) {
|
|
790
|
-
throw new UsageError(
|
|
791
|
-
`channel needs one of: ${CHANNEL_SUBCOMMANDS.join(", ")}`,
|
|
792
|
-
"channel"
|
|
793
|
-
);
|
|
811
|
+
throw new UsageError(`channel needs one of: ${CHANNEL_SUBCOMMANDS.join(", ")}`, "channel");
|
|
794
812
|
}
|
|
795
813
|
const client = await ctx.client();
|
|
796
814
|
const channel = client.channel;
|
|
797
815
|
if (sub === "open") {
|
|
798
|
-
const
|
|
799
|
-
const
|
|
800
|
-
|
|
801
|
-
...deposit !== void 0 ? { deposit } : {},
|
|
802
|
-
...timeout !== void 0 ? { settlementTimeout: Number(timeout) } : {}
|
|
803
|
-
});
|
|
804
|
-
const asset2 = assetFromTerms(state2.domain);
|
|
805
|
-
ctx.out.render(state2, () => {
|
|
816
|
+
const state = await channel.open();
|
|
817
|
+
const asset = assetInfo(state.channel.config.token);
|
|
818
|
+
ctx.out.render(state, () => {
|
|
806
819
|
ctx.out.line("Channel open.");
|
|
807
|
-
ctx.out.rows(stateRows(
|
|
820
|
+
ctx.out.rows(stateRows(state, asset));
|
|
808
821
|
});
|
|
809
822
|
return 0;
|
|
810
823
|
}
|
|
@@ -813,48 +826,51 @@ async function run2(ctx) {
|
|
|
813
826
|
if (amount === void 0) {
|
|
814
827
|
throw new UsageError("channel deposit needs an amount in base units", "channel");
|
|
815
828
|
}
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
829
|
+
let value;
|
|
830
|
+
try {
|
|
831
|
+
value = BigInt(amount);
|
|
832
|
+
} catch {
|
|
833
|
+
throw new UsageError(`'${amount}' is not a whole number of base units`, "channel");
|
|
834
|
+
}
|
|
835
|
+
const state = await channel.deposit(value);
|
|
836
|
+
const asset = assetInfo(state.channel.config.token);
|
|
837
|
+
ctx.out.render(state, () => {
|
|
819
838
|
ctx.out.line("Deposit confirmed.");
|
|
820
|
-
ctx.out.rows(stateRows(
|
|
839
|
+
ctx.out.rows(stateRows(state, asset));
|
|
821
840
|
});
|
|
822
841
|
return 0;
|
|
823
842
|
}
|
|
824
|
-
if (sub === "close") {
|
|
825
|
-
const
|
|
826
|
-
ctx.out.render(
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
if (result.closedAt !== void 0) rows.push(["closed at", result.closedAt.toString()]);
|
|
831
|
-
if (result.settleableAt !== void 0) {
|
|
832
|
-
rows.push(["settleable at", result.settleableAt.toString()]);
|
|
843
|
+
if (sub === "close" || sub === "settle") {
|
|
844
|
+
const results = sub === "close" ? await channel.close() : await channel.settle();
|
|
845
|
+
ctx.out.render(results, () => {
|
|
846
|
+
if (results.length === 0) {
|
|
847
|
+
ctx.out.line("No channel is ready to settle yet.");
|
|
848
|
+
return;
|
|
833
849
|
}
|
|
834
|
-
ctx.out.
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
if (sub === "settle") {
|
|
839
|
-
const result = await channel.settle();
|
|
840
|
-
ctx.out.render(result, () => {
|
|
841
|
-
ctx.out.line("Channel settled; the collateral is released.");
|
|
842
|
-
if (result.txHash !== void 0) ctx.out.rows([["tx", result.txHash]]);
|
|
850
|
+
ctx.out.line(
|
|
851
|
+
sub === "close" ? "Leaving every open channel. Settle each once its window has elapsed." : "Unspent deposits returned where each window had elapsed."
|
|
852
|
+
);
|
|
853
|
+
for (const r of results) ctx.out.rows(exitRows(r));
|
|
843
854
|
});
|
|
844
|
-
return 0;
|
|
855
|
+
return results.some((r) => r.error !== void 0) ? 1 : 0;
|
|
845
856
|
}
|
|
846
|
-
const
|
|
847
|
-
const asset = assetFromTerms(state.domain);
|
|
857
|
+
const channels = channel.channels();
|
|
848
858
|
let connectorView;
|
|
849
|
-
if (boolOption(ctx.values, "connector-view")) {
|
|
850
|
-
|
|
851
|
-
connectorView = entries[0];
|
|
859
|
+
if (boolOption(ctx.values, "connector-view") && channels.length > 0) {
|
|
860
|
+
connectorView = await client.claimState(channels.map((c) => c.channel.channelId));
|
|
852
861
|
}
|
|
853
|
-
ctx.out.render(
|
|
854
|
-
|
|
855
|
-
|
|
862
|
+
ctx.out.render(connectorView === void 0 ? channels : { channels, connector: connectorView }, () => {
|
|
863
|
+
if (channels.length === 0) {
|
|
864
|
+
ctx.out.line("No channel with this node yet. Open one with 'toon channel open', or pay for a request.");
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
for (const state of channels) {
|
|
868
|
+
const asset = assetInfo(state.channel.config.token);
|
|
869
|
+
const rows = stateRows(state, asset);
|
|
870
|
+
const theirs = connectorView?.find((e) => e.channelId === state.channel.channelId);
|
|
871
|
+
if (theirs !== void 0) rows.push(...connectorRows(theirs, asset));
|
|
872
|
+
ctx.out.rows(rows);
|
|
856
873
|
ctx.out.line();
|
|
857
|
-
ctx.out.rows(connectorRows(connectorView, asset));
|
|
858
874
|
}
|
|
859
875
|
});
|
|
860
876
|
return 0;
|
|
@@ -865,15 +881,15 @@ async function run3(ctx) {
|
|
|
865
881
|
const client = await ctx.client();
|
|
866
882
|
const entries = await client.claimState();
|
|
867
883
|
const description = await client.describe();
|
|
868
|
-
const asset = assetFromSettlement(description.
|
|
884
|
+
const asset = assetFromSettlement(description.batchSettlements[0]);
|
|
869
885
|
ctx.out.render({ connector: client.connector, channels: entries }, () => {
|
|
870
886
|
if (entries.length === 0) {
|
|
871
887
|
ctx.out.line("This connector reports no channels for your account.");
|
|
872
|
-
ctx.out.line("Open one with 'toon channel open
|
|
888
|
+
ctx.out.line("Open one with 'toon channel open', or pay for a request.");
|
|
873
889
|
return;
|
|
874
890
|
}
|
|
875
891
|
for (const entry of entries) {
|
|
876
|
-
const id = entry.channelId ??
|
|
892
|
+
const id = entry.channelId ?? "(unnamed)";
|
|
877
893
|
if (!entry.ok) {
|
|
878
894
|
ctx.out.rows([
|
|
879
895
|
["channel", id],
|
|
@@ -886,13 +902,9 @@ async function run3(ctx) {
|
|
|
886
902
|
ctx.out.rows([
|
|
887
903
|
["channel", id],
|
|
888
904
|
["chain", entry.blockchain],
|
|
889
|
-
["nonce", String(entry.nonce)],
|
|
890
905
|
["claimed", formatAmount(entry.cumulativeClaimed, asset)],
|
|
891
|
-
[
|
|
892
|
-
|
|
893
|
-
entry.depositTotal === null ? "declared only" : formatAmount(entry.depositTotal, asset)
|
|
894
|
-
],
|
|
895
|
-
["available", entry.available === null ? "unknown" : formatAmount(entry.available, asset)],
|
|
906
|
+
["max cumulative", formatAmount(entry.maxCumulative, asset)],
|
|
907
|
+
["available", formatAmount(entry.available, asset)],
|
|
896
908
|
[
|
|
897
909
|
// Printed as the connector gave it, unconverted: the field is
|
|
898
910
|
// best-effort and non-durable, and `null` means "unknown", never
|
|
@@ -915,7 +927,7 @@ async function run4(ctx) {
|
|
|
915
927
|
...url !== void 0 ? { connector: url } : {}
|
|
916
928
|
});
|
|
917
929
|
const description = await client.describe();
|
|
918
|
-
const asset = assetFromSettlement(description.
|
|
930
|
+
const asset = assetFromSettlement(description.batchSettlements[0]);
|
|
919
931
|
const payload = {
|
|
920
932
|
connector: client.connector,
|
|
921
933
|
ilpAddresses: description.ilpAddresses,
|
|
@@ -923,7 +935,8 @@ async function run4(ctx) {
|
|
|
923
935
|
btpEndpoint: description.btpEndpoint,
|
|
924
936
|
peerCarriages: description.peerCarriages,
|
|
925
937
|
edgeIdentity: description.edgeIdentity,
|
|
926
|
-
|
|
938
|
+
batchSettlements: description.batchSettlements,
|
|
939
|
+
voucherSigners: description.voucherSigners,
|
|
927
940
|
routes: description.routes,
|
|
928
941
|
requiredTransport: description.requiredTransport,
|
|
929
942
|
supportedVersions: description.supportedVersions,
|
|
@@ -951,18 +964,19 @@ async function run4(ctx) {
|
|
|
951
964
|
]);
|
|
952
965
|
ctx.out.rows(head);
|
|
953
966
|
ctx.out.line();
|
|
954
|
-
if (description.
|
|
955
|
-
ctx.out.line("
|
|
967
|
+
if (description.batchSettlements.length === 0) {
|
|
968
|
+
ctx.out.line("Channels: none offered \u2014 this node cannot be paid.");
|
|
956
969
|
} else {
|
|
957
|
-
ctx.out.line("
|
|
970
|
+
ctx.out.line("Channels (x402 batch-settlement):");
|
|
958
971
|
ctx.out.rows(
|
|
959
|
-
description.
|
|
960
|
-
|
|
972
|
+
description.batchSettlements.map((t) => [
|
|
973
|
+
t.network,
|
|
961
974
|
[
|
|
962
|
-
`
|
|
963
|
-
`token ${
|
|
964
|
-
|
|
965
|
-
|
|
975
|
+
`payTo ${t.payTo}`,
|
|
976
|
+
`token ${t.asset}`,
|
|
977
|
+
`min delay ${String(t.extra.withdrawDelay)}s`,
|
|
978
|
+
t.chain === "solana" ? `sponsor ${t.extra.feePayer}` : ""
|
|
979
|
+
].filter((x) => x !== "").join(" ")
|
|
966
980
|
])
|
|
967
981
|
);
|
|
968
982
|
}
|
|
@@ -1143,7 +1157,7 @@ async function run8(ctx) {
|
|
|
1143
1157
|
});
|
|
1144
1158
|
const terms = await client.routePrice(destination);
|
|
1145
1159
|
const description = await client.describe();
|
|
1146
|
-
const asset = assetFromSettlement(description.
|
|
1160
|
+
const asset = assetFromSettlement(description.batchSettlements[0]);
|
|
1147
1161
|
const perKib = terms?.pricePerKib;
|
|
1148
1162
|
ctx.out.render(
|
|
1149
1163
|
{
|
|
@@ -1176,7 +1190,7 @@ async function run9(ctx) {
|
|
|
1176
1190
|
const client = await ctx.client();
|
|
1177
1191
|
const result = await client.probe(destination);
|
|
1178
1192
|
const description = await client.describe();
|
|
1179
|
-
const asset = assetFromSettlement(description.
|
|
1193
|
+
const asset = assetFromSettlement(description.batchSettlements[0]);
|
|
1180
1194
|
ctx.out.render({ destination, ...result }, () => {
|
|
1181
1195
|
ctx.out.rows([
|
|
1182
1196
|
["destination", destination],
|
|
@@ -1321,7 +1335,7 @@ function payloadFor(result) {
|
|
|
1321
1335
|
httpEndpoint: terms.httpEndpoint,
|
|
1322
1336
|
btpEndpoint: terms.btpEndpoint,
|
|
1323
1337
|
requiredTransport: terms.requiredTransport,
|
|
1324
|
-
|
|
1338
|
+
batchSettlements: terms.batchSettlements,
|
|
1325
1339
|
sessionLeaseTtlMs: terms.sessionLeaseTtlMs
|
|
1326
1340
|
}
|
|
1327
1341
|
} : {}
|
|
@@ -1344,20 +1358,20 @@ async function run10(ctx) {
|
|
|
1344
1358
|
amountFlag === void 0 ? void 0 : { amount: BigInt(amountFlag) }
|
|
1345
1359
|
);
|
|
1346
1360
|
const description = await client.describe();
|
|
1347
|
-
const asset = assetFromSettlement(description.
|
|
1361
|
+
const asset = assetFromSettlement(description.batchSettlements[0]);
|
|
1348
1362
|
ctx.out.render(payloadFor(result), () => {
|
|
1349
1363
|
if (result.fulfilled) {
|
|
1350
1364
|
ctx.out.line(`FULFILL ${String(result.status)} (${result.transport})`);
|
|
1351
1365
|
const claim = result.claim;
|
|
1352
1366
|
ctx.out.rows(
|
|
1353
1367
|
claim === void 0 ? (
|
|
1354
|
-
// A route priced at zero takes no
|
|
1355
|
-
//
|
|
1368
|
+
// A route priced at zero takes no voucher, so there is no channel
|
|
1369
|
+
// or amount to show. Saying so beats printing zeroes.
|
|
1356
1370
|
[["paid", "nothing \u2014 this route is free"]]
|
|
1357
1371
|
) : [
|
|
1358
1372
|
[
|
|
1359
1373
|
"paid",
|
|
1360
|
-
`${formatAmount(claim.amount, asset)} channel ${claim.channelId}
|
|
1374
|
+
`${formatAmount(claim.amount, asset)} channel ${claim.channelId}`
|
|
1361
1375
|
],
|
|
1362
1376
|
["cumulative", formatAmount(claim.cumulative, asset)]
|
|
1363
1377
|
]
|
|
@@ -1527,7 +1541,9 @@ var FUNDING_CODES = /* @__PURE__ */ new Set([
|
|
|
1527
1541
|
"CHANNEL_RESUME",
|
|
1528
1542
|
"CHANNEL_NOT_OPEN",
|
|
1529
1543
|
"INSUFFICIENT_BALANCE",
|
|
1530
|
-
"TRANSFER_NOT_DELIVERED"
|
|
1544
|
+
"TRANSFER_NOT_DELIVERED",
|
|
1545
|
+
"FACILITATOR",
|
|
1546
|
+
"SPONSOR_REFUSED"
|
|
1531
1547
|
]);
|
|
1532
1548
|
var NETWORK_CODES = /* @__PURE__ */ new Set(["NETWORK_ERROR", "CONNECTOR_ERROR", "STALE_RPC_READ"]);
|
|
1533
1549
|
var PAYMENT_CODES = /* @__PURE__ */ new Set([
|