@toon-protocol/relay 1.3.3 → 2.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/README.md +51 -93
- package/dist/chunk-745ADETR.js +1027 -0
- package/dist/chunk-745ADETR.js.map +1 -0
- package/dist/cli.js +38 -206
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +107 -977
- package/dist/index.js +6 -447
- package/dist/index.js.map +1 -1
- package/package.json +4 -9
- package/dist/chunk-ZKWFGHZ7.js +0 -2029
- package/dist/chunk-ZKWFGHZ7.js.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
import { NostrEvent } from 'nostr-tools/pure';
|
|
2
2
|
import { Filter } from 'nostr-tools/filter';
|
|
3
3
|
import { WebSocket } from 'ws';
|
|
4
|
-
import { EmbeddableConnectorLike, SkillDescriptor, BootstrapPhase, ChainPreset, IlpClient } from '@toon-protocol/core';
|
|
5
|
-
export { ToonDecodeError, ToonEncodeError, decodeEventFromToon, encodeEventToToon } from '@toon-protocol/core';
|
|
6
|
-
import { Hono, Context } from 'hono';
|
|
7
4
|
import { SimplePool } from 'nostr-tools/pool';
|
|
8
|
-
import {
|
|
9
|
-
|
|
10
|
-
|
|
5
|
+
import { Context } from 'hono';
|
|
6
|
+
|
|
7
|
+
/** Package version, surfaced on `GET /health`. */
|
|
8
|
+
declare const VERSION = "0.1.0";
|
|
11
9
|
|
|
12
10
|
/**
|
|
13
11
|
* Configuration options for the Nostr relay.
|
|
@@ -226,189 +224,31 @@ declare class NostrRelayServer {
|
|
|
226
224
|
}
|
|
227
225
|
|
|
228
226
|
/**
|
|
229
|
-
*
|
|
230
|
-
*/
|
|
231
|
-
interface PricingConfig {
|
|
232
|
-
/** Base price per byte for event storage */
|
|
233
|
-
basePricePerByte: bigint;
|
|
234
|
-
/** Optional price overrides by event kind */
|
|
235
|
-
kindOverrides?: Map<number, bigint>;
|
|
236
|
-
}
|
|
237
|
-
/**
|
|
238
|
-
* Error class for pricing-specific errors.
|
|
239
|
-
*/
|
|
240
|
-
declare class PricingError extends RelayError {
|
|
241
|
-
constructor(message: string, code?: string);
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
/**
|
|
245
|
-
* Service for calculating event storage prices with kind-based overrides.
|
|
246
|
-
*/
|
|
247
|
-
declare class PricingService {
|
|
248
|
-
private readonly basePricePerByte;
|
|
249
|
-
private readonly kindOverrides;
|
|
250
|
-
constructor(config: PricingConfig);
|
|
251
|
-
/**
|
|
252
|
-
* Calculate price for a Nostr event.
|
|
253
|
-
*
|
|
254
|
-
* @param event - The Nostr event to price
|
|
255
|
-
* @returns The calculated price as bigint
|
|
256
|
-
*/
|
|
257
|
-
calculatePrice(event: NostrEvent): bigint;
|
|
258
|
-
/**
|
|
259
|
-
* Calculate price from raw TOON bytes and event kind.
|
|
260
|
-
*
|
|
261
|
-
* @param bytes - The TOON-encoded event bytes
|
|
262
|
-
* @param kind - The event kind number
|
|
263
|
-
* @returns The calculated price as bigint
|
|
264
|
-
*/
|
|
265
|
-
calculatePriceFromBytes(bytes: Uint8Array, kind: number): bigint;
|
|
266
|
-
/**
|
|
267
|
-
* Get the effective price per byte for a given kind.
|
|
268
|
-
*
|
|
269
|
-
* @param kind - The event kind number
|
|
270
|
-
* @returns The price per byte (kind override if exists, otherwise base price)
|
|
271
|
-
*/
|
|
272
|
-
getPricePerByte(kind: number): bigint;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
/**
|
|
276
|
-
* Load pricing configuration from environment variables.
|
|
227
|
+
* TOON event codec.
|
|
277
228
|
*
|
|
278
|
-
*
|
|
279
|
-
* -
|
|
280
|
-
*
|
|
281
|
-
*
|
|
229
|
+
* Encodes/decodes Nostr events to and from the TOON wire format used on this
|
|
230
|
+
* relay's NIP-01 read surface. Vendored from `@toon-protocol/core` so the relay
|
|
231
|
+
* depends only on the lightweight `@toon-format/toon` encoder rather than core's
|
|
232
|
+
* full transitive tree (which pulls Arweave / web3 wallet stacks the relay does
|
|
233
|
+
* not use). Same MIT license / org.
|
|
282
234
|
*
|
|
283
|
-
* @
|
|
284
|
-
* @throws PricingError if env vars contain invalid values
|
|
285
|
-
*/
|
|
286
|
-
declare function loadPricingConfigFromEnv(): PricingConfig;
|
|
287
|
-
/**
|
|
288
|
-
* Load pricing configuration from a JSON file.
|
|
289
|
-
*
|
|
290
|
-
* File format:
|
|
291
|
-
* {
|
|
292
|
-
* "basePricePerByte": "10",
|
|
293
|
-
* "kindOverrides": {
|
|
294
|
-
* "0": "0",
|
|
295
|
-
* "1": "5",
|
|
296
|
-
* "30023": "100"
|
|
297
|
-
* }
|
|
298
|
-
* }
|
|
299
|
-
*
|
|
300
|
-
* @param path - Path to the JSON config file
|
|
301
|
-
* @returns PricingConfig loaded from file
|
|
302
|
-
* @throws PricingError if file cannot be read or contains invalid values
|
|
303
|
-
*/
|
|
304
|
-
declare function loadPricingConfigFromFile(path: string): PricingConfig;
|
|
305
|
-
|
|
306
|
-
/**
|
|
307
|
-
* Validate that a string is a valid Nostr pubkey format.
|
|
308
|
-
* @param pubkey - The pubkey to validate
|
|
309
|
-
* @returns true if valid 64-character lowercase hex string
|
|
310
|
-
*/
|
|
311
|
-
declare function isValidPubkey(pubkey: string): boolean;
|
|
312
|
-
/**
|
|
313
|
-
* Configuration for the Business Logic Server.
|
|
314
|
-
*/
|
|
315
|
-
interface BlsConfig {
|
|
316
|
-
/** Base price per byte for event storage (used for simple pricing) */
|
|
317
|
-
basePricePerByte: bigint;
|
|
318
|
-
/** Optional PricingService for kind-based pricing overrides */
|
|
319
|
-
pricingService?: PricingService;
|
|
320
|
-
/** Optional owner pubkey - events from this pubkey bypass payment */
|
|
321
|
-
ownerPubkey?: string;
|
|
322
|
-
}
|
|
323
|
-
/**
|
|
324
|
-
* Incoming packet request from ILP connector.
|
|
325
|
-
*/
|
|
326
|
-
interface HandlePacketRequest {
|
|
327
|
-
/** Payment amount as string (parsed to bigint) */
|
|
328
|
-
amount: string;
|
|
329
|
-
/** ILP destination address */
|
|
330
|
-
destination: string;
|
|
331
|
-
/** Base64-encoded TOON Nostr event */
|
|
332
|
-
data: string;
|
|
333
|
-
/** Source ILP address */
|
|
334
|
-
sourceAccount?: string;
|
|
335
|
-
}
|
|
336
|
-
/**
|
|
337
|
-
* Response for accepted packet.
|
|
338
|
-
*/
|
|
339
|
-
interface HandlePacketAcceptResponse {
|
|
340
|
-
accept: true;
|
|
341
|
-
metadata?: {
|
|
342
|
-
eventId: string;
|
|
343
|
-
storedAt: number;
|
|
344
|
-
};
|
|
345
|
-
}
|
|
346
|
-
/**
|
|
347
|
-
* Response for rejected packet.
|
|
348
|
-
*/
|
|
349
|
-
interface HandlePacketRejectResponse {
|
|
350
|
-
accept: false;
|
|
351
|
-
/** ILP error code (F00, F06, etc.) */
|
|
352
|
-
code: string;
|
|
353
|
-
/** Human-readable error message */
|
|
354
|
-
message: string;
|
|
355
|
-
metadata?: {
|
|
356
|
-
required?: string;
|
|
357
|
-
received?: string;
|
|
358
|
-
};
|
|
359
|
-
}
|
|
360
|
-
/**
|
|
361
|
-
* Union type for packet response.
|
|
362
|
-
*/
|
|
363
|
-
type HandlePacketResponse = HandlePacketAcceptResponse | HandlePacketRejectResponse;
|
|
364
|
-
/**
|
|
365
|
-
* ILP error code constants.
|
|
366
|
-
*/
|
|
367
|
-
declare const ILP_ERROR_CODES: {
|
|
368
|
-
readonly BAD_REQUEST: "F00";
|
|
369
|
-
readonly INSUFFICIENT_AMOUNT: "F06";
|
|
370
|
-
readonly INTERNAL_ERROR: "T00";
|
|
371
|
-
};
|
|
372
|
-
/**
|
|
373
|
-
* BLS-specific error class.
|
|
235
|
+
* @module
|
|
374
236
|
*/
|
|
375
|
-
declare class BlsError extends RelayError {
|
|
376
|
-
constructor(message: string, code?: string);
|
|
377
|
-
}
|
|
378
237
|
|
|
379
|
-
/**
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
*/
|
|
394
|
-
private setupRoutes;
|
|
395
|
-
/**
|
|
396
|
-
* Process a packet request.
|
|
397
|
-
*
|
|
398
|
-
* This method is public to support direct connector integration in embedded mode,
|
|
399
|
-
* where the connector calls this method directly via setPacketHandler() instead
|
|
400
|
-
* of making HTTP requests.
|
|
401
|
-
*/
|
|
402
|
-
handlePacket(request: HandlePacketRequest): HandlePacketAcceptResponse | HandlePacketRejectResponse;
|
|
403
|
-
/**
|
|
404
|
-
* Get the Hono app instance for testing or composition.
|
|
405
|
-
*/
|
|
406
|
-
getApp(): Hono;
|
|
407
|
-
/**
|
|
408
|
-
* Start the HTTP server on the specified port.
|
|
409
|
-
*/
|
|
410
|
-
start(port: number): void;
|
|
411
|
-
}
|
|
238
|
+
/** Thrown when a Nostr event cannot be encoded to TOON. */
|
|
239
|
+
declare class ToonEncodeError extends Error {
|
|
240
|
+
readonly code = "TOON_ENCODE_ERROR";
|
|
241
|
+
constructor(message: string, cause?: Error);
|
|
242
|
+
}
|
|
243
|
+
/** Thrown when TOON data cannot be decoded into a valid Nostr event. */
|
|
244
|
+
declare class ToonDecodeError extends Error {
|
|
245
|
+
readonly code = "TOON_DECODE_ERROR";
|
|
246
|
+
constructor(message: string, cause?: Error);
|
|
247
|
+
}
|
|
248
|
+
/** Encode a Nostr event to TOON bytes (UTF-8). */
|
|
249
|
+
declare function encodeEventToToon(event: NostrEvent): Uint8Array;
|
|
250
|
+
/** Decode TOON bytes into a validated Nostr event. */
|
|
251
|
+
declare function decodeEventFromToon(data: Uint8Array): NostrEvent;
|
|
412
252
|
|
|
413
253
|
/**
|
|
414
254
|
* Subscribe to upstream relays and propagate events into the local EventStore.
|
|
@@ -459,239 +299,70 @@ declare class RelaySubscriber {
|
|
|
459
299
|
/**
|
|
460
300
|
* startRelay() -- Programmatic API for starting a TOON relay node.
|
|
461
301
|
*
|
|
462
|
-
*
|
|
463
|
-
*
|
|
464
|
-
*
|
|
302
|
+
* The relay is a plain HTTP/WebSocket app. It does NOT speak ILP and contains
|
|
303
|
+
* no payment, connector, settlement, or pricing logic: payment is enforced
|
|
304
|
+
* entirely upstream by an external terminator (see the connector repo). By the
|
|
305
|
+
* time a write reaches this process it is already proven paid, so the relay
|
|
306
|
+
* simply stores the event and serves reads.
|
|
465
307
|
*
|
|
466
|
-
*
|
|
308
|
+
* Two surfaces:
|
|
467
309
|
*
|
|
468
|
-
*
|
|
469
|
-
*
|
|
470
|
-
*
|
|
310
|
+
* - `POST /write` (TOON_BLS_PORT, default 3100): accepts `{ event }` as JSON,
|
|
311
|
+
* trusts the injected `X-TOON-Payer`/`-Amount`/`-Chain` headers WITHOUT
|
|
312
|
+
* re-validating payment, verifies only the event's own signature for
|
|
313
|
+
* integrity, and stores it. `GET /health` lives on the same port.
|
|
314
|
+
* - Free NIP-01 WebSocket reads (TOON_RELAY_PORT, default 7100).
|
|
471
315
|
*
|
|
472
|
-
*
|
|
316
|
+
* `startRelay()` returns a `RelayInstance` with an explicit `.stop()` for
|
|
317
|
+
* lifecycle control (the CLI wraps this with process-signal handling).
|
|
473
318
|
*
|
|
474
|
-
*
|
|
475
|
-
* destined for its own ILP address can be routed locally (the connector and
|
|
476
|
-
* the BLS handler must share a process for the round-trip to work).
|
|
477
|
-
*
|
|
478
|
-
* - **Standalone embedded** (no `connectorUrl`): A self-routing embedded
|
|
479
|
-
* connector with no upstream peers. Useful for genesis nodes and tests.
|
|
480
|
-
* - **Embedded with parent** (`connectorUrl` set): The embedded connector
|
|
481
|
-
* is configured with `connectorUrl` as a parent BTP peer, plus a self-route
|
|
482
|
-
* for local delivery and a default-route to the parent for everything else.
|
|
483
|
-
* - **Pre-built embedded** (`connector`): Pass a fully constructed
|
|
484
|
-
* `EmbeddableConnectorLike`. The town does not modify it.
|
|
485
|
-
*
|
|
486
|
-
* `connector` and `connectorUrl` are mutually exclusive — provide at most one.
|
|
319
|
+
* @module
|
|
487
320
|
*/
|
|
488
321
|
|
|
489
322
|
/**
|
|
490
323
|
* Configuration for starting a TOON relay node via `startRelay()`.
|
|
491
324
|
*
|
|
492
|
-
* Exactly one of `mnemonic` or `secretKey` must be provided
|
|
493
|
-
*
|
|
494
|
-
*
|
|
495
|
-
* - When neither is provided, a standalone embedded `ConnectorNode` is built
|
|
496
|
-
* with only a self-route (no upstream peers).
|
|
497
|
-
* - When `connectorUrl` is set, the embedded connector is configured with
|
|
498
|
-
* that URL as a parent BTP peer plus a default-route to it. `ilpAddress`
|
|
499
|
-
* becomes REQUIRED in this mode and must fall under the parent's prefix
|
|
500
|
-
* (e.g. `g.townhouse.<self>`).
|
|
501
|
-
* - When `connector` is set, the caller-supplied `EmbeddableConnectorLike`
|
|
502
|
-
* is used as-is; town does not configure peers, routes, or settlement on it.
|
|
325
|
+
* Exactly one of `mnemonic` or `secretKey` must be provided -- it is the node's
|
|
326
|
+
* Nostr identity (surfaced on `/health`).
|
|
503
327
|
*/
|
|
504
328
|
interface RelayConfig {
|
|
505
|
-
/** 12-word or 24-word BIP-39 mnemonic phrase. */
|
|
329
|
+
/** 12-word or 24-word BIP-39 mnemonic phrase (NIP-06 derivation). */
|
|
506
330
|
mnemonic?: string;
|
|
507
331
|
/** 32-byte secp256k1 secret key. */
|
|
508
332
|
secretKey?: Uint8Array;
|
|
509
|
-
/**
|
|
510
|
-
* Pre-built embedded connector. Mutually exclusive with `connectorUrl`.
|
|
511
|
-
* When provided, town does not modify the connector — peers, routes, and
|
|
512
|
-
* settlement are the caller's responsibility.
|
|
513
|
-
*/
|
|
514
|
-
connector?: EmbeddableConnectorLike;
|
|
515
|
-
/**
|
|
516
|
-
* Parent connector BTP URL (e.g. `ws://apex.example:3001`). When set, the
|
|
517
|
-
* embedded connector is built with this URL as a parent peer and a default
|
|
518
|
-
* `g.` route to that peer; `ilpAddress` MUST also be set and fall under the
|
|
519
|
-
* parent's prefix. Mutually exclusive with `connector`.
|
|
520
|
-
*/
|
|
521
|
-
connectorUrl?: string;
|
|
522
|
-
/** BTP peer id to use for the parent connector (default: `'apex'`). */
|
|
523
|
-
parentPeerId?: string;
|
|
524
|
-
/** BTP auth token for the parent peer (default: empty string -- no-auth). */
|
|
525
|
-
parentAuthToken?: string;
|
|
526
|
-
/** Stable nodeId for the embedded connector (default: `toon-<pubkeyShort>`). */
|
|
527
|
-
nodeId?: string;
|
|
528
|
-
/** BTP server port for the embedded connector (default: 3000). */
|
|
529
|
-
btpServerPort?: number;
|
|
530
|
-
/**
|
|
531
|
-
* EVM private key for settlement infrastructure on the embedded connector.
|
|
532
|
-
* If not set, the identity's secp256k1 key is reused.
|
|
533
|
-
*/
|
|
534
|
-
settlementPrivateKey?: string;
|
|
535
|
-
/**
|
|
536
|
-
* EVM treasury address advertised to the parent connector for the
|
|
537
|
-
* embedded-with-parent peer entry. The apex's PerPacketClaimService uses
|
|
538
|
-
* this as the `peerAddress` when the apex opens a payment channel toward
|
|
539
|
-
* this child. Only meaningful when `connectorUrl` is set. When omitted,
|
|
540
|
-
* the parent peer entry has no `evmAddress` and the apex's channel-open
|
|
541
|
-
* call must supply `peerAddress` explicitly.
|
|
542
|
-
*/
|
|
543
|
-
parentEvmAddress?: string;
|
|
544
|
-
/** WebSocket relay port (default: 7100). */
|
|
333
|
+
/** WebSocket relay (read) port (default: 7100). */
|
|
545
334
|
relayPort?: number;
|
|
546
|
-
/**
|
|
335
|
+
/** HTTP write/health port (default: 3100). */
|
|
547
336
|
blsPort?: number;
|
|
548
337
|
/**
|
|
549
|
-
*
|
|
550
|
-
*
|
|
551
|
-
* field is REQUIRED and must fall under the parent's address prefix.
|
|
338
|
+
* WebSocket bind host (default: 0.0.0.0). Set to `127.0.0.1` to bind the read
|
|
339
|
+
* port to localhost only (e.g. when an upstream proxy handles inbound).
|
|
552
340
|
*/
|
|
553
|
-
|
|
554
|
-
/**
|
|
555
|
-
btpEndpoint?: string;
|
|
556
|
-
/** Base price per byte in ILP units (default: 10n). */
|
|
557
|
-
basePricePerByte?: bigint;
|
|
558
|
-
/** Routing buffer percentage for x402 multi-hop overhead (default: 10). */
|
|
559
|
-
routingBufferPercent?: number;
|
|
560
|
-
/** Enable x402 /publish endpoint (default: false). */
|
|
561
|
-
x402Enabled?: boolean;
|
|
562
|
-
/** Facilitator EVM address for x402 payments. Defaults to the node's EVM address. */
|
|
563
|
-
facilitatorAddress?: string;
|
|
564
|
-
/** Known peers to bootstrap with. */
|
|
565
|
-
knownPeers?: {
|
|
566
|
-
pubkey: string;
|
|
567
|
-
relayUrl: string;
|
|
568
|
-
btpEndpoint: string;
|
|
569
|
-
}[];
|
|
570
|
-
/** Chain preset name (default: 'anvil'). See resolveChainConfig(). */
|
|
571
|
-
chain?: string;
|
|
572
|
-
/** Chain ID -> RPC URL mapping (e.g., { 'evm:base:31337': 'http://localhost:8545' }). */
|
|
573
|
-
chainRpcUrls?: Record<string, string>;
|
|
574
|
-
/** Chain ID -> TokenNetwork contract address. */
|
|
575
|
-
tokenNetworks?: Record<string, string>;
|
|
576
|
-
/** Chain ID -> preferred token address. */
|
|
577
|
-
preferredTokens?: Record<string, string>;
|
|
578
|
-
/**
|
|
579
|
-
* Chain ID -> settlement (recipient) address advertised in kind:10032.
|
|
580
|
-
*
|
|
581
|
-
* By default every supported chain advertises the identity's EVM address.
|
|
582
|
-
* That is wrong for non-EVM chains (e.g. `solana:devnet`), whose settlement
|
|
583
|
-
* recipient must be a chain-native address (a base58 Solana pubkey). Provide
|
|
584
|
-
* a per-chain override here to advertise a chain-native recipient; chains
|
|
585
|
-
* absent from this map keep the EVM-address default.
|
|
586
|
-
*
|
|
587
|
-
* NOTE (Phase-2 Stage 2 gate): advertising a Solana recipient is necessary
|
|
588
|
-
* but NOT sufficient for a settleable Solana loop — the client must also open
|
|
589
|
-
* a real on-chain Solana payment-channel PDA and sign over that PDA. See the
|
|
590
|
-
* Stage-2 PR description / gate report.
|
|
591
|
-
*/
|
|
592
|
-
settlementAddresses?: Record<string, string>;
|
|
593
|
-
/** Data directory path (default: ./data). */
|
|
341
|
+
host?: string;
|
|
342
|
+
/** Data directory for the file-backed SQLite store (default: ./data). */
|
|
594
343
|
dataDir?: string;
|
|
595
|
-
/** Enable dev mode (skip verification). Default: false. */
|
|
596
|
-
devMode?: boolean;
|
|
597
|
-
/** Discovery mode: 'seed-list' for production, 'genesis' for dev (default: 'genesis'). */
|
|
598
|
-
discovery?: 'seed-list' | 'genesis';
|
|
599
|
-
/** Public Nostr relay URLs for seed relay discovery (used when discovery: 'seed-list'). */
|
|
600
|
-
seedRelays?: string[];
|
|
601
|
-
/** Whether to publish this node as a seed relay entry (default: false). */
|
|
602
|
-
publishSeedEntry?: boolean;
|
|
603
|
-
/** External WebSocket URL of this relay (required if publishSeedEntry is true). */
|
|
604
|
-
externalRelayUrl?: string;
|
|
605
344
|
/**
|
|
606
|
-
*
|
|
607
|
-
*
|
|
608
|
-
*
|
|
609
|
-
*
|
|
610
|
-
*
|
|
611
|
-
* - `enabled: false` (default): Relay binds to `0.0.0.0`, no privacy overlay.
|
|
612
|
-
* - `enabled: true`: Relay binds to `127.0.0.1`, publishes `anonAddress` for discovery.
|
|
345
|
+
* Pre-built EventStore. When provided, the relay uses it instead of building
|
|
346
|
+
* the default file-backed `SqliteEventStore` under `dataDir` (useful for
|
|
347
|
+
* tests via `InMemoryEventStore`, or to share a store when embedding). The
|
|
348
|
+
* caller owns its lifecycle when supplied.
|
|
613
349
|
*/
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
anonAddress?: string;
|
|
618
|
-
/** SOCKS5 proxy URL for outbound connections (default: "socks5h://127.0.0.1:9050"). */
|
|
619
|
-
socksProxy?: string;
|
|
620
|
-
};
|
|
621
|
-
/**
|
|
622
|
-
* Optional DVM skill descriptor to include in service discovery events.
|
|
623
|
-
* When provided, the service discovery event will include the `skill` field.
|
|
624
|
-
* Typically computed by `node.getSkillDescriptor()` from the SDK.
|
|
625
|
-
*/
|
|
626
|
-
skill?: SkillDescriptor;
|
|
627
|
-
/** Enable ArDrive peer lookup (default: false). */
|
|
628
|
-
ardriveEnabled?: boolean;
|
|
629
|
-
/** Public Nostr relay URLs for social discovery. */
|
|
630
|
-
relayUrls?: string[];
|
|
631
|
-
/** Asset code for ILP (default: 'USD'). */
|
|
632
|
-
assetCode?: string;
|
|
633
|
-
/** Asset scale for ILP (default: 6). */
|
|
634
|
-
assetScale?: number;
|
|
635
|
-
/**
|
|
636
|
-
* Fee per event in ILP units (overrides basePricePerByte when set).
|
|
637
|
-
* When provided, sets basePricePerByte to this value. Used by the
|
|
638
|
-
* Townhouse orchestrator via TOON_FEE_PER_EVENT env var.
|
|
639
|
-
*/
|
|
640
|
-
feePerEvent?: number;
|
|
641
|
-
/**
|
|
642
|
-
* NIP-40 time-to-live for this node's kind:10032 announcement, in seconds
|
|
643
|
-
* (default 3600). The node re-publishes its announcement at half this
|
|
644
|
-
* interval so a live apex stays fresh while an offline one expires, letting
|
|
645
|
-
* clients skip its unreachable BTP endpoint (issue #261). Set to 0 to disable
|
|
646
|
-
* the expiration tag and the heartbeat (non-expiring announcement). Override
|
|
647
|
-
* via the `TOON_ANNOUNCEMENT_TTL_SECONDS` env var.
|
|
648
|
-
*/
|
|
649
|
-
announcementTtlSeconds?: number;
|
|
350
|
+
eventStore?: EventStore;
|
|
351
|
+
/** Skip event-signature verification on `POST /write` (default: false). */
|
|
352
|
+
devMode?: boolean;
|
|
650
353
|
}
|
|
651
354
|
/**
|
|
652
|
-
* Resolved configuration with all defaults applied.
|
|
653
|
-
* (ports, pricing, paths have been filled in).
|
|
355
|
+
* Resolved configuration with all defaults applied.
|
|
654
356
|
*/
|
|
655
357
|
interface ResolvedRelayConfig {
|
|
656
358
|
relayPort: number;
|
|
657
359
|
blsPort: number;
|
|
658
|
-
|
|
659
|
-
btpEndpoint: string;
|
|
660
|
-
/** Stable nodeId of the embedded connector. */
|
|
661
|
-
nodeId: string;
|
|
662
|
-
/** Parent connector URL when peering with one (omitted otherwise). */
|
|
663
|
-
connectorUrl?: string;
|
|
664
|
-
/** Parent BTP peer id (only meaningful when connectorUrl is set). */
|
|
665
|
-
parentPeerId?: string;
|
|
666
|
-
basePricePerByte: bigint;
|
|
667
|
-
routingBufferPercent: number;
|
|
668
|
-
x402Enabled: boolean;
|
|
669
|
-
knownPeers: {
|
|
670
|
-
pubkey: string;
|
|
671
|
-
relayUrl: string;
|
|
672
|
-
btpEndpoint: string;
|
|
673
|
-
}[];
|
|
360
|
+
host: string;
|
|
674
361
|
dataDir: string;
|
|
675
362
|
devMode: boolean;
|
|
676
|
-
ardriveEnabled: boolean;
|
|
677
|
-
relayUrls: string[];
|
|
678
|
-
assetCode: string;
|
|
679
|
-
assetScale: number;
|
|
680
|
-
/** Discovery mode: 'seed-list' for production, 'genesis' for dev. */
|
|
681
|
-
discovery: 'seed-list' | 'genesis';
|
|
682
|
-
/** Public Nostr relay URLs for seed relay discovery. */
|
|
683
|
-
seedRelays: string[];
|
|
684
|
-
/** Whether to publish this node as a seed relay entry. */
|
|
685
|
-
publishSeedEntry: boolean;
|
|
686
|
-
/** External WebSocket URL of this relay (for seed entry publishing). */
|
|
687
|
-
externalRelayUrl?: string;
|
|
688
|
-
/** Chain preset name (e.g., 'anvil', 'arbitrum-one'). */
|
|
689
|
-
chain: string;
|
|
690
363
|
}
|
|
691
364
|
/**
|
|
692
365
|
* A running TOON relay node instance returned by `startRelay()`.
|
|
693
|
-
*
|
|
694
|
-
* Provides lifecycle control (stop), identity info, and bootstrap results.
|
|
695
366
|
*/
|
|
696
367
|
interface RelayInstance {
|
|
697
368
|
/** Whether the relay is currently running. */
|
|
@@ -699,28 +370,19 @@ interface RelayInstance {
|
|
|
699
370
|
/** Gracefully stop the relay and release all resources. */
|
|
700
371
|
stop(): Promise<void>;
|
|
701
372
|
/**
|
|
702
|
-
* Subscribe to a remote Nostr relay. Received events are stored in
|
|
703
|
-
*
|
|
373
|
+
* Subscribe to a remote Nostr relay. Received events are stored in this
|
|
374
|
+
* node's EventStore. Returns a handle for lifecycle management.
|
|
704
375
|
*
|
|
705
376
|
* @param relayUrl - WebSocket URL of the relay to subscribe to.
|
|
706
377
|
* @param filter - Nostr filter (kinds, authors, etc.).
|
|
707
378
|
* @returns A RelaySubscription handle.
|
|
708
|
-
* @throws If the
|
|
379
|
+
* @throws If the relay is not running.
|
|
709
380
|
*/
|
|
710
381
|
subscribe(relayUrl: string, filter: Filter): RelaySubscription;
|
|
711
382
|
/** The node's Nostr x-only public key (64-char hex). */
|
|
712
383
|
pubkey: string;
|
|
713
|
-
/** The node's EVM address (0x-prefixed). */
|
|
714
|
-
evmAddress: string;
|
|
715
384
|
/** The resolved configuration with all defaults applied. */
|
|
716
385
|
config: ResolvedRelayConfig;
|
|
717
|
-
/** Bootstrap results from the startup phase. */
|
|
718
|
-
bootstrapResult: {
|
|
719
|
-
peerCount: number;
|
|
720
|
-
channelCount: number;
|
|
721
|
-
};
|
|
722
|
-
/** Discovery mode used by this instance. */
|
|
723
|
-
discoveryMode: 'seed-list' | 'genesis';
|
|
724
386
|
}
|
|
725
387
|
/**
|
|
726
388
|
* Handle for managing an outbound subscription to a remote Nostr relay.
|
|
@@ -737,636 +399,104 @@ interface RelaySubscription {
|
|
|
737
399
|
/**
|
|
738
400
|
* Start a TOON relay node with the given configuration.
|
|
739
401
|
*
|
|
740
|
-
*
|
|
741
|
-
*
|
|
742
|
-
* and relay monitor. Returns a `RelayInstance` for lifecycle management.
|
|
743
|
-
*
|
|
744
|
-
* The town node ALWAYS runs an embedded `ConnectorNode`. Three configurations
|
|
745
|
-
* are supported:
|
|
746
|
-
* - No connector args: standalone embedded connector with self-route only.
|
|
747
|
-
* - `connectorUrl`: embedded connector configured with that URL as a parent
|
|
748
|
-
* BTP peer plus a default `g.` route to it. `ilpAddress` is REQUIRED here.
|
|
749
|
-
* - `connector`: pass a pre-built `EmbeddableConnectorLike`; town does not
|
|
750
|
-
* modify it.
|
|
402
|
+
* Wires the event store, the HTTP write/health server, and the NIP-01
|
|
403
|
+
* WebSocket read server, then returns a `RelayInstance` for lifecycle control.
|
|
751
404
|
*
|
|
752
|
-
* @param config - Node configuration. One of `mnemonic`/`secretKey` is required
|
|
753
|
-
* `connector` and `connectorUrl` are mutually exclusive.
|
|
405
|
+
* @param config - Node configuration. One of `mnemonic`/`secretKey` is required.
|
|
754
406
|
* @returns A running RelayInstance.
|
|
755
407
|
* @throws If both or neither of mnemonic/secretKey are provided.
|
|
756
|
-
* @throws If both connector and connectorUrl are provided.
|
|
757
|
-
* @throws If connectorUrl is set without an explicit ilpAddress.
|
|
758
408
|
*
|
|
759
409
|
* @example
|
|
760
410
|
* ```typescript
|
|
761
|
-
*
|
|
762
|
-
*
|
|
763
|
-
*
|
|
764
|
-
* // Embedded with parent
|
|
765
|
-
* const town = await startRelay({
|
|
766
|
-
* mnemonic: 'abandon ...',
|
|
767
|
-
* connectorUrl: 'ws://apex.example:3001',
|
|
768
|
-
* parentPeerId: 'apex',
|
|
769
|
-
* parentAuthToken: '',
|
|
770
|
-
* ilpAddress: 'g.townhouse.alice',
|
|
771
|
-
* });
|
|
411
|
+
* const relay = await startRelay({ secretKey });
|
|
412
|
+
* // ... POST /write on 3100, read NIP-01 on 7100 ...
|
|
413
|
+
* await relay.stop();
|
|
772
414
|
* ```
|
|
773
415
|
*/
|
|
774
416
|
declare function startRelay(config: RelayConfig): Promise<RelayInstance>;
|
|
775
|
-
/**
|
|
776
|
-
* @deprecated Use {@link startRelay} instead. Retained for backwards
|
|
777
|
-
* compatibility after the town → relay package merge.
|
|
778
|
-
*/
|
|
779
|
-
declare const startTown: typeof startRelay;
|
|
780
|
-
/**
|
|
781
|
-
* @deprecated Use {@link RelayConfig} instead.
|
|
782
|
-
*/
|
|
783
|
-
type TownConfig = RelayConfig;
|
|
784
|
-
/**
|
|
785
|
-
* @deprecated Use {@link RelayInstance} instead.
|
|
786
|
-
*/
|
|
787
|
-
type TownInstance = RelayInstance;
|
|
788
|
-
/**
|
|
789
|
-
* @deprecated Use {@link ResolvedRelayConfig} instead.
|
|
790
|
-
*/
|
|
791
|
-
type ResolvedTownConfig = ResolvedRelayConfig;
|
|
792
|
-
/**
|
|
793
|
-
* @deprecated Use {@link RelaySubscription} instead.
|
|
794
|
-
*/
|
|
795
|
-
type TownSubscription = RelaySubscription;
|
|
796
417
|
|
|
797
418
|
/**
|
|
798
|
-
*
|
|
799
|
-
*
|
|
800
|
-
* Provides a pure function `createHealthResponse()` that builds a comprehensive
|
|
801
|
-
* health JSON object combining static configuration (pricing, chain, version,
|
|
802
|
-
* capabilities) with live runtime state (phase, peerCount, channelCount).
|
|
419
|
+
* Health response for the relay's HTTP server.
|
|
803
420
|
*
|
|
804
|
-
* The
|
|
805
|
-
*
|
|
421
|
+
* The relay is a plain read/write app (no payment, connector, or settlement
|
|
422
|
+
* layer), so the health response is deliberately minimal: liveness plus the
|
|
423
|
+
* node's identity and version. It is served from `GET /health` on the write
|
|
424
|
+
* port and is the target of the container healthcheck.
|
|
806
425
|
*
|
|
807
426
|
* @module
|
|
808
427
|
*/
|
|
809
|
-
|
|
810
|
-
/** TEE attestation state for the health response (enforcement guideline 12). */
|
|
811
|
-
interface TeeHealthInfo {
|
|
812
|
-
/** Whether a valid attestation has been published. */
|
|
813
|
-
attested: boolean;
|
|
814
|
-
/** Enclave type identifier (e.g., 'aws-nitro', 'marlin-oyster'). */
|
|
815
|
-
enclaveType: string;
|
|
816
|
-
/** Unix timestamp of the last attestation event. */
|
|
817
|
-
lastAttestation: number;
|
|
818
|
-
/** Platform Configuration Register 0 (SHA-384 hex, 96 chars). */
|
|
819
|
-
pcr0: string;
|
|
820
|
-
/** Attestation validity state. */
|
|
821
|
-
state: 'valid' | 'stale' | 'unattested';
|
|
822
|
-
}
|
|
823
428
|
/** Configuration for building a health response. */
|
|
824
429
|
interface HealthConfig {
|
|
825
|
-
/** Current bootstrap phase. */
|
|
826
|
-
phase: BootstrapPhase;
|
|
827
430
|
/** Node's Nostr pubkey (64-char hex). */
|
|
828
431
|
pubkey: string;
|
|
829
|
-
/** Node's ILP address. */
|
|
830
|
-
ilpAddress: string;
|
|
831
|
-
/** Number of registered peers. */
|
|
832
|
-
peerCount: number;
|
|
833
|
-
/** Number of discovered (not yet registered) peers. */
|
|
834
|
-
discoveredPeerCount: number;
|
|
835
|
-
/** Number of open payment channels. */
|
|
836
|
-
channelCount: number;
|
|
837
|
-
/**
|
|
838
|
-
* Base price per byte (bigint from config, converted to number via Number()).
|
|
839
|
-
* Values exceeding Number.MAX_SAFE_INTEGER (2^53 - 1) will lose precision.
|
|
840
|
-
*/
|
|
841
|
-
basePricePerByte: bigint;
|
|
842
|
-
/** Whether x402 is enabled. */
|
|
843
|
-
x402Enabled: boolean;
|
|
844
|
-
/** Chain preset name. */
|
|
845
|
-
chain: string;
|
|
846
|
-
/**
|
|
847
|
-
* TEE attestation info.
|
|
848
|
-
* Omit entirely when not running in a TEE (enforcement guideline 12).
|
|
849
|
-
*/
|
|
850
|
-
tee?: TeeHealthInfo;
|
|
851
432
|
}
|
|
852
|
-
/** The
|
|
433
|
+
/** The health response shape. */
|
|
853
434
|
interface HealthResponse {
|
|
854
435
|
status: 'healthy';
|
|
855
|
-
phase: BootstrapPhase;
|
|
856
436
|
pubkey: string;
|
|
857
|
-
ilpAddress: string;
|
|
858
|
-
peerCount: number;
|
|
859
|
-
discoveredPeerCount: number;
|
|
860
|
-
channelCount: number;
|
|
861
|
-
pricing: {
|
|
862
|
-
basePricePerByte: number;
|
|
863
|
-
currency: 'USDC';
|
|
864
|
-
};
|
|
865
|
-
x402?: {
|
|
866
|
-
enabled: true;
|
|
867
|
-
endpoint: string;
|
|
868
|
-
};
|
|
869
|
-
/**
|
|
870
|
-
* TEE attestation info. Only present when running in a TEE enclave.
|
|
871
|
-
* Entirely absent when not in TEE (enforcement guideline 12 --
|
|
872
|
-
* never `{ attested: false }`, simply omit the field).
|
|
873
|
-
*/
|
|
874
|
-
tee?: TeeHealthInfo;
|
|
875
437
|
capabilities: string[];
|
|
876
|
-
chain: string;
|
|
877
438
|
version: string;
|
|
878
|
-
sdk: true;
|
|
879
439
|
timestamp: number;
|
|
880
440
|
}
|
|
881
441
|
/**
|
|
882
|
-
* Build
|
|
883
|
-
*
|
|
884
|
-
* This is a pure function -- it takes a config object and returns a response
|
|
885
|
-
* object. No Hono context or HTTP request is needed, making it easy to unit
|
|
886
|
-
* test and reuse across entrypoints.
|
|
442
|
+
* Build a health response for the relay.
|
|
887
443
|
*
|
|
888
|
-
*
|
|
889
|
-
*
|
|
444
|
+
* Pure function: takes a config and returns the response object, so it is
|
|
445
|
+
* trivially unit-testable and reusable.
|
|
890
446
|
*
|
|
891
|
-
* @param config - Health configuration
|
|
892
|
-
* @returns The
|
|
447
|
+
* @param config - Health configuration (the node's pubkey).
|
|
448
|
+
* @returns The health response object.
|
|
893
449
|
*/
|
|
894
450
|
declare function createHealthResponse(config: HealthConfig): HealthResponse;
|
|
895
451
|
|
|
896
452
|
/**
|
|
897
|
-
*
|
|
898
|
-
*
|
|
899
|
-
* Stores incoming Nostr events in the EventStore after decoding from TOON.
|
|
900
|
-
* This is the "default" handler for the relay -- it processes all event kinds
|
|
901
|
-
* except those handled by kind-specific handlers.
|
|
902
|
-
*
|
|
903
|
-
* The handler is intentionally simple (~15 lines of logic). The SDK pipeline
|
|
904
|
-
* handles signature verification, pricing validation, and self-write bypass
|
|
905
|
-
* before the handler is invoked. The handler only needs to:
|
|
906
|
-
* 1. ctx.decode() -- lazy-decode the TOON payload into a NostrEvent
|
|
907
|
-
* 2. eventStore.store(event) -- persist the event
|
|
908
|
-
* 3. ctx.accept({ eventId, storedAt }) -- accept the ILP packet
|
|
909
|
-
*/
|
|
910
|
-
|
|
911
|
-
/**
|
|
912
|
-
* Configuration for the event storage handler.
|
|
913
|
-
*
|
|
914
|
-
* Minimal by design -- the handler's only job is decode + store + accept.
|
|
915
|
-
* Pricing, verification, and self-write bypass are SDK pipeline concerns.
|
|
916
|
-
*/
|
|
917
|
-
interface EventStorageHandlerConfig {
|
|
918
|
-
/** Event store backend (e.g., SqliteEventStore from @toon-protocol/relay). */
|
|
919
|
-
eventStore: EventStore;
|
|
920
|
-
}
|
|
921
|
-
/**
|
|
922
|
-
* Creates an event storage handler that decodes TOON payloads and stores
|
|
923
|
-
* Nostr events in the configured EventStore.
|
|
924
|
-
*
|
|
925
|
-
* Errors from `ctx.decode()` or `eventStore.store()` are not caught here --
|
|
926
|
-
* they propagate to the SDK's dispatch error boundary, which converts
|
|
927
|
-
* unhandled exceptions to `{ accept: false, code: 'T00', message: 'Internal error' }`.
|
|
928
|
-
*
|
|
929
|
-
* @param config - Handler configuration with the event store backend.
|
|
930
|
-
* @returns A handler function compatible with `node.onDefault(handler)`.
|
|
931
|
-
*/
|
|
932
|
-
declare function createEventStorageHandler(config: EventStorageHandlerConfig): Handler;
|
|
933
|
-
|
|
934
|
-
/**
|
|
935
|
-
* EIP-3009 types and constants for the x402 publish endpoint.
|
|
453
|
+
* Write handler for @toon-protocol/relay.
|
|
936
454
|
*
|
|
937
|
-
*
|
|
938
|
-
*
|
|
939
|
-
*
|
|
940
|
-
* USDC transfer amount.
|
|
455
|
+
* Exposes a plain-HTTP write surface that accepts an event-as-JSON, trusts
|
|
456
|
+
* (but does NOT validate) injected payment headers, verifies ONLY the event
|
|
457
|
+
* signature for integrity, and stores the event.
|
|
941
458
|
*
|
|
942
|
-
*
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
*
|
|
947
|
-
*
|
|
948
|
-
* The user signs this off-chain (EIP-712 typed data). The facilitator
|
|
949
|
-
* submits the signature on-chain to execute the USDC transfer.
|
|
950
|
-
*/
|
|
951
|
-
interface Eip3009Authorization {
|
|
952
|
-
/** Sender's EVM address ('0x...'). */
|
|
953
|
-
from: string;
|
|
954
|
-
/** Recipient's EVM address ('0x...' -- facilitator). */
|
|
955
|
-
to: string;
|
|
956
|
-
/** USDC amount in micro-units (bigint). */
|
|
957
|
-
value: bigint;
|
|
958
|
-
/** Unix timestamp: authorization valid after this time. */
|
|
959
|
-
validAfter: number;
|
|
960
|
-
/** Unix timestamp: authorization expires at this time. */
|
|
961
|
-
validBefore: number;
|
|
962
|
-
/** 32-byte nonce ('0x...' hex string). */
|
|
963
|
-
nonce: string;
|
|
964
|
-
/** ECDSA recovery id (27 or 28). */
|
|
965
|
-
v: number;
|
|
966
|
-
/** ECDSA r component ('0x...' 32 bytes). */
|
|
967
|
-
r: string;
|
|
968
|
-
/** ECDSA s component ('0x...' 32 bytes). */
|
|
969
|
-
s: string;
|
|
970
|
-
}
|
|
971
|
-
/**
|
|
972
|
-
* EIP-712 typed data structure for `transferWithAuthorization`.
|
|
973
|
-
*
|
|
974
|
-
* This is the type definition used for off-chain signature verification
|
|
975
|
-
* and on-chain contract calls.
|
|
976
|
-
*
|
|
977
|
-
* NOTE: The EIP-712 domain for USDC's `transferWithAuthorization` is
|
|
978
|
-
* different from the EIP-712 domain for TokenNetwork's balance proofs.
|
|
979
|
-
* The x402 handler must use the USDC contract's domain.
|
|
980
|
-
*/
|
|
981
|
-
declare const EIP_3009_TYPES: {
|
|
982
|
-
readonly TransferWithAuthorization: readonly [{
|
|
983
|
-
readonly name: "from";
|
|
984
|
-
readonly type: "address";
|
|
985
|
-
}, {
|
|
986
|
-
readonly name: "to";
|
|
987
|
-
readonly type: "address";
|
|
988
|
-
}, {
|
|
989
|
-
readonly name: "value";
|
|
990
|
-
readonly type: "uint256";
|
|
991
|
-
}, {
|
|
992
|
-
readonly name: "validAfter";
|
|
993
|
-
readonly type: "uint256";
|
|
994
|
-
}, {
|
|
995
|
-
readonly name: "validBefore";
|
|
996
|
-
readonly type: "uint256";
|
|
997
|
-
}, {
|
|
998
|
-
readonly name: "nonce";
|
|
999
|
-
readonly type: "bytes32";
|
|
1000
|
-
}];
|
|
1001
|
-
};
|
|
1002
|
-
/**
|
|
1003
|
-
* EIP-712 domain separator for USDC's `transferWithAuthorization`.
|
|
1004
|
-
*
|
|
1005
|
-
* Uses the USDC contract's name and version, NOT the TokenNetwork's.
|
|
1006
|
-
*/
|
|
1007
|
-
declare const USDC_EIP712_DOMAIN: {
|
|
1008
|
-
readonly name: "USD Coin";
|
|
1009
|
-
readonly version: "2";
|
|
1010
|
-
};
|
|
1011
|
-
/**
|
|
1012
|
-
* Minimal EventStore interface for destination reachability checks.
|
|
1013
|
-
* Uses structural typing to avoid importing @toon-protocol/relay directly.
|
|
1014
|
-
* The query method accepts Filter[] (array) per the relay's EventStore interface.
|
|
1015
|
-
*/
|
|
1016
|
-
interface EventStoreLike {
|
|
1017
|
-
query(filters: {
|
|
1018
|
-
kinds?: number[];
|
|
1019
|
-
authors?: string[];
|
|
1020
|
-
}[]): unknown[];
|
|
1021
|
-
}
|
|
1022
|
-
/**
|
|
1023
|
-
* Request body for the x402 `/publish` endpoint.
|
|
1024
|
-
*
|
|
1025
|
-
* The client sends a signed Nostr event and a destination ILP address.
|
|
1026
|
-
* The handler TOON-encodes the event before routing.
|
|
1027
|
-
*/
|
|
1028
|
-
interface X402PublishRequest {
|
|
1029
|
-
/** Signed Nostr event. */
|
|
1030
|
-
event: NostrEvent;
|
|
1031
|
-
/** Target ILP address (e.g., "g.toon.target-relay"). */
|
|
1032
|
-
destination: string;
|
|
1033
|
-
}
|
|
1034
|
-
/**
|
|
1035
|
-
* Response body for a successful x402 `/publish` request (HTTP 200).
|
|
1036
|
-
*/
|
|
1037
|
-
interface X402PublishResponse {
|
|
1038
|
-
/** Nostr event ID (64-char hex). */
|
|
1039
|
-
eventId: string;
|
|
1040
|
-
/** On-chain settlement transaction hash. */
|
|
1041
|
-
settlementTxHash: string;
|
|
1042
|
-
/** Whether the ILP PREPARE was fulfilled or rejected by the destination. */
|
|
1043
|
-
deliveryStatus: 'fulfilled' | 'rejected';
|
|
1044
|
-
/** Always false -- no refunds on REJECT per protocol design. */
|
|
1045
|
-
refundInitiated: false;
|
|
1046
|
-
}
|
|
1047
|
-
/**
|
|
1048
|
-
* Response body for the 402 pricing negotiation.
|
|
1049
|
-
*/
|
|
1050
|
-
interface X402PricingResponse {
|
|
1051
|
-
/** Price in USDC micro-units (as string for BigInt serialization). */
|
|
1052
|
-
amount: string;
|
|
1053
|
-
/** Node operator's EVM address that will receive the USDC. */
|
|
1054
|
-
facilitatorAddress: string;
|
|
1055
|
-
/** Payment network identifier. */
|
|
1056
|
-
paymentNetwork: 'eip-3009';
|
|
1057
|
-
/** EVM chain ID. */
|
|
1058
|
-
chainId: number;
|
|
1059
|
-
/** USDC contract address on this chain. */
|
|
1060
|
-
usdcAddress: string;
|
|
1061
|
-
}
|
|
1062
|
-
/**
|
|
1063
|
-
* Minimal USDC ABI for EIP-3009 operations.
|
|
1064
|
-
*
|
|
1065
|
-
* Includes only the functions needed by the x402 handler:
|
|
1066
|
-
* - `balanceOf`: Read sender's USDC balance (pre-flight check #2)
|
|
1067
|
-
* - `authorizationState`: Check nonce freshness (pre-flight check #3)
|
|
1068
|
-
* - `transferWithAuthorization`: Execute gasless USDC transfer (settlement)
|
|
1069
|
-
*/
|
|
1070
|
-
declare const USDC_ABI: readonly [{
|
|
1071
|
-
readonly name: "balanceOf";
|
|
1072
|
-
readonly type: "function";
|
|
1073
|
-
readonly stateMutability: "view";
|
|
1074
|
-
readonly inputs: readonly [{
|
|
1075
|
-
readonly name: "account";
|
|
1076
|
-
readonly type: "address";
|
|
1077
|
-
}];
|
|
1078
|
-
readonly outputs: readonly [{
|
|
1079
|
-
readonly name: "";
|
|
1080
|
-
readonly type: "uint256";
|
|
1081
|
-
}];
|
|
1082
|
-
}, {
|
|
1083
|
-
readonly name: "authorizationState";
|
|
1084
|
-
readonly type: "function";
|
|
1085
|
-
readonly stateMutability: "view";
|
|
1086
|
-
readonly inputs: readonly [{
|
|
1087
|
-
readonly name: "authorizer";
|
|
1088
|
-
readonly type: "address";
|
|
1089
|
-
}, {
|
|
1090
|
-
readonly name: "nonce";
|
|
1091
|
-
readonly type: "bytes32";
|
|
1092
|
-
}];
|
|
1093
|
-
readonly outputs: readonly [{
|
|
1094
|
-
readonly name: "";
|
|
1095
|
-
readonly type: "bool";
|
|
1096
|
-
}];
|
|
1097
|
-
}, {
|
|
1098
|
-
readonly name: "transferWithAuthorization";
|
|
1099
|
-
readonly type: "function";
|
|
1100
|
-
readonly stateMutability: "nonpayable";
|
|
1101
|
-
readonly inputs: readonly [{
|
|
1102
|
-
readonly name: "from";
|
|
1103
|
-
readonly type: "address";
|
|
1104
|
-
}, {
|
|
1105
|
-
readonly name: "to";
|
|
1106
|
-
readonly type: "address";
|
|
1107
|
-
}, {
|
|
1108
|
-
readonly name: "value";
|
|
1109
|
-
readonly type: "uint256";
|
|
1110
|
-
}, {
|
|
1111
|
-
readonly name: "validAfter";
|
|
1112
|
-
readonly type: "uint256";
|
|
1113
|
-
}, {
|
|
1114
|
-
readonly name: "validBefore";
|
|
1115
|
-
readonly type: "uint256";
|
|
1116
|
-
}, {
|
|
1117
|
-
readonly name: "nonce";
|
|
1118
|
-
readonly type: "bytes32";
|
|
1119
|
-
}, {
|
|
1120
|
-
readonly name: "v";
|
|
1121
|
-
readonly type: "uint8";
|
|
1122
|
-
}, {
|
|
1123
|
-
readonly name: "r";
|
|
1124
|
-
readonly type: "bytes32";
|
|
1125
|
-
}, {
|
|
1126
|
-
readonly name: "s";
|
|
1127
|
-
readonly type: "bytes32";
|
|
1128
|
-
}];
|
|
1129
|
-
readonly outputs: readonly [];
|
|
1130
|
-
}];
|
|
1131
|
-
|
|
1132
|
-
/**
|
|
1133
|
-
* Pre-flight validation pipeline for the x402 publish endpoint.
|
|
1134
|
-
*
|
|
1135
|
-
* Implements 6 free checks that run before any on-chain transaction,
|
|
1136
|
-
* preventing gas griefing (E3-R008). All checks are either pure
|
|
1137
|
-
* cryptography or read-only RPC calls (no gas cost).
|
|
1138
|
-
*
|
|
1139
|
-
* Check order (cheapest to most expensive):
|
|
1140
|
-
* 1. EIP-3009 signature verification (off-chain, ~1ms)
|
|
1141
|
-
* 2. USDC balance check (eth_call, ~50ms)
|
|
1142
|
-
* 3. Nonce freshness check (eth_call, ~50ms)
|
|
1143
|
-
* 4. TOON shallow parse (pure computation, ~0.1ms)
|
|
1144
|
-
* 5. Schnorr signature verification (pure crypto, ~2ms)
|
|
1145
|
-
* 6. Destination reachability check (local lookup, ~0.1ms)
|
|
1146
|
-
*
|
|
1147
|
-
* @module
|
|
1148
|
-
*/
|
|
1149
|
-
|
|
1150
|
-
/**
|
|
1151
|
-
* Result of running the pre-flight validation pipeline.
|
|
1152
|
-
*/
|
|
1153
|
-
interface PreflightResult {
|
|
1154
|
-
/** Whether all checks passed. */
|
|
1155
|
-
passed: boolean;
|
|
1156
|
-
/** Which check failed (only set if passed is false). */
|
|
1157
|
-
failedCheck?: string;
|
|
1158
|
-
/** List of check names that were executed. */
|
|
1159
|
-
checksPerformed: string[];
|
|
1160
|
-
}
|
|
1161
|
-
/**
|
|
1162
|
-
* Callback for Schnorr signature verification.
|
|
1163
|
-
* Returns true if the signature is valid.
|
|
1164
|
-
*/
|
|
1165
|
-
type SchnorrVerifyFn = (meta: ToonRoutingMeta) => Promise<boolean>;
|
|
1166
|
-
/**
|
|
1167
|
-
* Configuration for the pre-flight validation pipeline.
|
|
1168
|
-
*/
|
|
1169
|
-
interface PreflightConfig {
|
|
1170
|
-
/** Resolved chain configuration. */
|
|
1171
|
-
chainConfig: ChainPreset;
|
|
1172
|
-
/** Base price per byte for pricing validation. */
|
|
1173
|
-
basePricePerByte: bigint;
|
|
1174
|
-
/** This node's Nostr public key. */
|
|
1175
|
-
ownPubkey: string;
|
|
1176
|
-
/** Whether dev mode is enabled (skips Schnorr verification). */
|
|
1177
|
-
devMode: boolean;
|
|
1178
|
-
/** viem public client for read-only contract calls (optional, for testing). */
|
|
1179
|
-
publicClient?: PublicClient;
|
|
1180
|
-
/** EventStore for destination reachability check (optional). */
|
|
1181
|
-
eventStore?: EventStoreLike;
|
|
1182
|
-
/** Schnorr verification callback (optional, uses SDK verification pipeline). */
|
|
1183
|
-
schnorrVerify?: SchnorrVerifyFn;
|
|
1184
|
-
}
|
|
1185
|
-
/**
|
|
1186
|
-
* Run the 6-stage pre-flight validation pipeline.
|
|
1187
|
-
*
|
|
1188
|
-
* All checks are free (no gas cost). If any check fails, execution
|
|
1189
|
-
* stops immediately and no on-chain transaction is attempted.
|
|
1190
|
-
*
|
|
1191
|
-
* @param authorization - EIP-3009 signed authorization from the client.
|
|
1192
|
-
* @param toonData - Base64-encoded TOON payload.
|
|
1193
|
-
* @param destination - Target ILP address.
|
|
1194
|
-
* @param config - Pre-flight configuration.
|
|
1195
|
-
* @returns PreflightResult indicating success or which check failed.
|
|
1196
|
-
*/
|
|
1197
|
-
declare function runPreflight(authorization: Eip3009Authorization, toonData: string, destination: string, config: PreflightConfig): Promise<PreflightResult>;
|
|
1198
|
-
|
|
1199
|
-
/**
|
|
1200
|
-
* EIP-3009 on-chain settlement module for the x402 publish endpoint.
|
|
1201
|
-
*
|
|
1202
|
-
* Executes `transferWithAuthorization` on the USDC contract to settle
|
|
1203
|
-
* the gasless USDC transfer from the client to the facilitator (node
|
|
1204
|
-
* operator). The facilitator pays gas; the client pays only USDC.
|
|
1205
|
-
*
|
|
1206
|
-
* Settlement atomicity (E3-R006):
|
|
1207
|
-
* - If settlement fails (revert), no ILP PREPARE is constructed.
|
|
1208
|
-
* - If settlement succeeds but ILP PREPARE is rejected, no refund.
|
|
1209
|
-
*
|
|
1210
|
-
* @module
|
|
1211
|
-
*/
|
|
1212
|
-
|
|
1213
|
-
/**
|
|
1214
|
-
* Result of an EIP-3009 settlement attempt.
|
|
1215
|
-
*/
|
|
1216
|
-
interface X402SettlementResult {
|
|
1217
|
-
/** Whether the on-chain transaction succeeded. */
|
|
1218
|
-
success: boolean;
|
|
1219
|
-
/** Transaction hash (only set on success). */
|
|
1220
|
-
txHash?: string;
|
|
1221
|
-
/** Error message (only set on failure). */
|
|
1222
|
-
error?: string;
|
|
1223
|
-
}
|
|
1224
|
-
/**
|
|
1225
|
-
* @deprecated Use X402SettlementResult instead.
|
|
1226
|
-
*/
|
|
1227
|
-
type SettlementResult = X402SettlementResult;
|
|
1228
|
-
/**
|
|
1229
|
-
* Configuration for the settlement module.
|
|
1230
|
-
*
|
|
1231
|
-
* Named `X402SettlementConfig` to avoid collision with
|
|
1232
|
-
* `SettlementConfig` from `@toon-protocol/core` (bootstrap).
|
|
1233
|
-
*/
|
|
1234
|
-
interface X402SettlementConfig {
|
|
1235
|
-
/** Resolved chain configuration. */
|
|
1236
|
-
chainConfig: ChainPreset;
|
|
1237
|
-
/** viem wallet client for the facilitator (submits the tx, pays gas). */
|
|
1238
|
-
walletClient: WalletClient;
|
|
1239
|
-
/** viem public client for waiting on transaction receipts. */
|
|
1240
|
-
publicClient?: PublicClient;
|
|
1241
|
-
}
|
|
1242
|
-
/**
|
|
1243
|
-
* Settle an EIP-3009 `transferWithAuthorization` on-chain.
|
|
1244
|
-
*
|
|
1245
|
-
* Submits the client's signed authorization to the USDC contract.
|
|
1246
|
-
* The facilitator (node operator) pays gas for the transaction.
|
|
1247
|
-
*
|
|
1248
|
-
* @param authorization - Signed EIP-3009 authorization from the client.
|
|
1249
|
-
* @param config - Settlement configuration with wallet client.
|
|
1250
|
-
* @returns SettlementResult indicating success/failure.
|
|
1251
|
-
*/
|
|
1252
|
-
/**
|
|
1253
|
-
* @deprecated Use X402SettlementConfig instead.
|
|
1254
|
-
*/
|
|
1255
|
-
type SettlementConfig = X402SettlementConfig;
|
|
1256
|
-
declare function settleEip3009(authorization: Eip3009Authorization, config: X402SettlementConfig): Promise<X402SettlementResult>;
|
|
1257
|
-
|
|
1258
|
-
/**
|
|
1259
|
-
* x402 publish handler for the TOON protocol.
|
|
1260
|
-
*
|
|
1261
|
-
* Implements the HTTP-native payment on-ramp via the x402 protocol pattern.
|
|
1262
|
-
* Allows any HTTP client (AI agents, browsers, CLI tools) to publish Nostr
|
|
1263
|
-
* events to the network by paying USDC, without understanding ILP or
|
|
1264
|
-
* running an ILP client.
|
|
459
|
+
* This handler is intentionally decoupled from any payment layer: it contains
|
|
460
|
+
* no claim/settlement/ILP logic and imports none of it. Payment validation is
|
|
461
|
+
* the upstream terminator's concern; by the time a request reaches this surface
|
|
462
|
+
* the trusted `X-TOON-*` headers are assumed already proven. The handler
|
|
463
|
+
* captures them purely for the response echo and a log line.
|
|
1265
464
|
*
|
|
1266
465
|
* Flow:
|
|
1267
|
-
* 1.
|
|
1268
|
-
* 2.
|
|
1269
|
-
* 3.
|
|
1270
|
-
* 4.
|
|
1271
|
-
* 5.
|
|
1272
|
-
* 6.
|
|
1273
|
-
* 7. Handler returns 200 with event ID and tx hash
|
|
466
|
+
* 1. Parse JSON body `{ event }` -> 400 on malformed/missing event
|
|
467
|
+
* 2. Capture trusted X-TOON-Payer / X-TOON-Amount / X-TOON-Chain headers
|
|
468
|
+
* 3. Verify the event signature (skipped in devMode) -> 422 on invalid sig
|
|
469
|
+
* 4. Store the event in the EventStore
|
|
470
|
+
* 5. Fire the optional onStored callback
|
|
471
|
+
* 6. Respond 200 with the event id, storedAt timestamp, and echoed headers
|
|
1274
472
|
*
|
|
1275
473
|
* @module
|
|
1276
474
|
*/
|
|
1277
475
|
|
|
1278
476
|
/**
|
|
1279
|
-
* Configuration for the
|
|
477
|
+
* Configuration for the write handler.
|
|
1280
478
|
*/
|
|
1281
|
-
interface
|
|
1282
|
-
/**
|
|
1283
|
-
|
|
1284
|
-
/**
|
|
1285
|
-
chainConfig: ChainPreset;
|
|
1286
|
-
/** Base price per byte in USDC micro-units. */
|
|
1287
|
-
basePricePerByte: bigint;
|
|
1288
|
-
/** Routing buffer percentage for multi-hop overhead (default: 10). */
|
|
1289
|
-
routingBufferPercent: number;
|
|
1290
|
-
/** Facilitator's EVM address (receives USDC payments). */
|
|
1291
|
-
facilitatorAddress: string;
|
|
1292
|
-
/** This node's Nostr public key. */
|
|
1293
|
-
ownPubkey: string;
|
|
1294
|
-
/** Whether dev mode is enabled (skips Schnorr verification). */
|
|
479
|
+
interface WriteHandlerConfig {
|
|
480
|
+
/** Event store backend used to persist accepted events. */
|
|
481
|
+
eventStore: EventStore;
|
|
482
|
+
/** Whether dev mode is enabled (skips Schnorr signature verification). */
|
|
1295
483
|
devMode: boolean;
|
|
1296
|
-
/**
|
|
1297
|
-
|
|
1298
|
-
/** Event store for destination reachability check. */
|
|
1299
|
-
eventStore?: EventStoreLike;
|
|
1300
|
-
/** TOON encoder function (defaults to core's encodeEventToToon). */
|
|
1301
|
-
toonEncoder?: (event: NostrEvent) => Uint8Array;
|
|
1302
|
-
/** viem wallet client for on-chain settlement (facilitator pays gas). */
|
|
1303
|
-
walletClient?: WalletClient;
|
|
1304
|
-
/** viem public client for read-only contract calls. */
|
|
1305
|
-
publicClient?: PublicClient;
|
|
1306
|
-
/** Override settle function (for testing). */
|
|
1307
|
-
settle?: (auth: Eip3009Authorization, config: X402SettlementConfig) => Promise<X402SettlementResult>;
|
|
1308
|
-
/** Override pre-flight function (for testing). */
|
|
1309
|
-
runPreflightFn?: typeof runPreflight;
|
|
484
|
+
/** Optional callback fired after an event is successfully stored. */
|
|
485
|
+
onStored?: (event: NostrEvent) => void;
|
|
1310
486
|
}
|
|
1311
487
|
/**
|
|
1312
|
-
*
|
|
488
|
+
* Write handler instance.
|
|
1313
489
|
*/
|
|
1314
|
-
interface
|
|
1315
|
-
/** Handle a
|
|
1316
|
-
|
|
490
|
+
interface WriteHandler {
|
|
491
|
+
/** Handle a plain-HTTP write request. */
|
|
492
|
+
handleWrite(c: Context): Promise<Response>;
|
|
1317
493
|
}
|
|
1318
494
|
/**
|
|
1319
|
-
* Create
|
|
1320
|
-
*
|
|
1321
|
-
* Returns a handler that processes both the 402 pricing negotiation
|
|
1322
|
-
* (no X-PAYMENT header) and the paid publish flow (with X-PAYMENT header).
|
|
495
|
+
* Create a write handler.
|
|
1323
496
|
*
|
|
1324
497
|
* @param config - Handler configuration.
|
|
1325
|
-
* @returns
|
|
498
|
+
* @returns A WriteHandler with a handleWrite method.
|
|
1326
499
|
*/
|
|
1327
|
-
declare function
|
|
1328
|
-
|
|
1329
|
-
/**
|
|
1330
|
-
* x402 pricing calculator with multi-hop routing buffer.
|
|
1331
|
-
*
|
|
1332
|
-
* Computes the all-in USDC price for publishing a Nostr event via the
|
|
1333
|
-
* x402 HTTP on-ramp. The price includes a configurable routing buffer
|
|
1334
|
-
* (default 10%) to cover multi-hop overhead -- intermediate relays charge
|
|
1335
|
-
* their own per-byte fees.
|
|
1336
|
-
*
|
|
1337
|
-
* @module
|
|
1338
|
-
*/
|
|
1339
|
-
/**
|
|
1340
|
-
* Configuration for the x402 pricing calculator.
|
|
1341
|
-
*/
|
|
1342
|
-
interface X402PricingConfig {
|
|
1343
|
-
/** Base price per byte in ILP/USDC micro-units (e.g., 10n). */
|
|
1344
|
-
basePricePerByte: bigint;
|
|
1345
|
-
/** Routing buffer percentage (default: 10, meaning 10%). */
|
|
1346
|
-
routingBufferPercent: number;
|
|
1347
|
-
}
|
|
1348
|
-
/**
|
|
1349
|
-
* Calculate the all-in x402 price for a TOON payload.
|
|
1350
|
-
*
|
|
1351
|
-
* Formula:
|
|
1352
|
-
* basePrice = basePricePerByte * toonLength
|
|
1353
|
-
* buffer = basePrice * routingBufferPercent / 100
|
|
1354
|
-
* total = basePrice + buffer
|
|
1355
|
-
*
|
|
1356
|
-
* The routing buffer covers multi-hop overhead. 10% default is a
|
|
1357
|
-
* conservative estimate per Party Mode Decision 8.
|
|
1358
|
-
*
|
|
1359
|
-
* @param config - Pricing configuration with base price and buffer percent.
|
|
1360
|
-
* @param toonLength - Length of the TOON-encoded payload in bytes.
|
|
1361
|
-
* @returns Total price in USDC micro-units.
|
|
1362
|
-
*/
|
|
1363
|
-
declare function calculateX402Price(config: X402PricingConfig, toonLength: number): bigint;
|
|
1364
|
-
|
|
1365
|
-
/**
|
|
1366
|
-
* @toon-protocol/relay
|
|
1367
|
-
*
|
|
1368
|
-
* ILP-gated Nostr relay with Business Logic Server.
|
|
1369
|
-
*/
|
|
1370
|
-
declare const VERSION = "0.1.0";
|
|
500
|
+
declare function createWriteHandler(config: WriteHandlerConfig): WriteHandler;
|
|
1371
501
|
|
|
1372
|
-
export {
|
|
502
|
+
export { ConnectionHandler, DEFAULT_RELAY_CONFIG, type EventStore, type HealthConfig, type HealthResponse, InMemoryEventStore, NostrRelayServer, type RelayConfig, RelayError, type RelayInstance, type RelayServerConfig, RelaySubscriber, type RelaySubscriberConfig, type RelaySubscription, type ResolvedRelayConfig, SqliteEventStore, type Subscription, ToonDecodeError, ToonEncodeError, VERSION, type WriteHandler, type WriteHandlerConfig, createHealthResponse, createWriteHandler, decodeEventFromToon, encodeEventToToon, matchFilter, startRelay };
|