@toon-protocol/client 0.25.1 → 0.26.1
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 +113 -0
- package/dist/index.d.ts +2164 -1019
- package/dist/index.js +2183 -210
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,250 +1,916 @@
|
|
|
1
1
|
import * as _toon_protocol_core from '@toon-protocol/core';
|
|
2
2
|
import { IlpPeerInfo, IlpSendResult, IlpClient, SwapPair, NetworkFamilyStatus, ConnectorAdminClient, ConnectorChannelClient, OpenChannelParams, OpenChannelResult, ChannelState } from '@toon-protocol/core';
|
|
3
3
|
export { UI_RENDERER_KIND, UI_TAG, UiCoordinate, buildUiCoordinate, getUiCoordinate, parseUiCoordinate, selectLatestAddressable } from '@toon-protocol/core';
|
|
4
|
-
import { NostrEvent, EventTemplate } from 'nostr-tools/pure';
|
|
4
|
+
import { UnsignedEvent, NostrEvent, EventTemplate } from 'nostr-tools/pure';
|
|
5
|
+
import { PrivateKeyAccount } from 'viem/accounts';
|
|
5
6
|
import { MinaSignerClientLike, SettlementBundle } from '@toon-protocol/sdk';
|
|
6
7
|
import { AccumulatedClaim } from '@toon-protocol/sdk/swap';
|
|
7
|
-
import { PrivateKeyAccount, Hex, Address } from 'viem';
|
|
8
|
-
import { PrivateKeyAccount as PrivateKeyAccount$1 } from 'viem/accounts';
|
|
8
|
+
import { PrivateKeyAccount as PrivateKeyAccount$1, Hex, Address } from 'viem';
|
|
9
9
|
export { A2uiDecision, ConsentDecision, ConsentRequest, DispatchGuardInfo, DispatchInput, GenerateContext, GeneratedRenderer, GenerativeDecision, GenerativeFallbackOptions, GenerativeFallbackRenderer, GenerativeFallbackResult, GuardedDispatchInput, IntentClassification, KindRegistry, MIME_A2UI, MIME_MCP_APP, McpUiDecision, NativeDecision, PublishBackOptions, RenderBranch, RenderDecision, RenderTrust, RendererGenerator, RendererPin, RendererPinStore, RendererPublisher, RendererSigner, ResolvedCoordinate, SwapApproval, SwapDecision, SwapRejection, SwapRejectionReason, UiResource, VerifyRendererInput, WidgetIntent, buildConsentRequest, buildRendererEventTemplate, classifyIntent, deterministicGenerator, extractUiResource, guardedRenderDispatch, isTrustDowngrade, publishBackCoordinate, renderDeterministicHtml, renderDispatch, resolveRendererMime, resolveUiCoordinate, resolveUiRenderer, verifyRendererTrust } from './render/index.js';
|
|
10
10
|
|
|
11
|
-
/**
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
asset?: string;
|
|
18
|
-
/** Token decimals, when resolved. */
|
|
19
|
-
assetScale?: number;
|
|
11
|
+
/**
|
|
12
|
+
* Base error class for all TOON client errors.
|
|
13
|
+
*/
|
|
14
|
+
declare class ToonClientError extends Error {
|
|
15
|
+
readonly code: string;
|
|
16
|
+
constructor(message: string, code: string, cause?: Error);
|
|
20
17
|
}
|
|
21
18
|
/**
|
|
22
|
-
*
|
|
23
|
-
*
|
|
19
|
+
* Network error for connection failures (ECONNREFUSED, ETIMEDOUT).
|
|
20
|
+
* These errors trigger retry logic with exponential backoff.
|
|
24
21
|
*/
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
symbol?: string;
|
|
28
|
-
/** Base-unit integer, decimal string. */
|
|
29
|
-
amount: string;
|
|
30
|
-
/** Decimals for formatting (ETH 18, SOL 9, MINA 9, USDC 6). */
|
|
31
|
-
decimals?: number;
|
|
32
|
-
/** Token contract / SPL mint address. Absent for the native coin. */
|
|
33
|
-
address?: string;
|
|
22
|
+
declare class NetworkError extends ToonClientError {
|
|
23
|
+
constructor(message: string, cause?: Error);
|
|
34
24
|
}
|
|
35
25
|
/**
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
* `'evm:31337'`). `unreadable` marks a chain whose RPC could not be reached at
|
|
39
|
-
* all — the caller renders a per-chain notice rather than crashing.
|
|
26
|
+
* Connector error for 5xx server errors.
|
|
27
|
+
* These errors indicate the connector is unavailable or malfunctioning.
|
|
40
28
|
*/
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
/** Full chain key, e.g. `'evm:31337'`, `'solana'`, `'mina'`. */
|
|
44
|
-
chainKey: string;
|
|
45
|
-
address: string;
|
|
46
|
-
/** Native-coin balance, when readable. */
|
|
47
|
-
native?: WalletTokenAmount;
|
|
48
|
-
/** Configured token balances (e.g. USDC), each best-effort. */
|
|
49
|
-
tokens: WalletTokenAmount[];
|
|
50
|
-
/** True when nothing on this chain could be read (RPC unreachable). */
|
|
51
|
-
unreadable?: boolean;
|
|
52
|
-
/** First read error, when any read failed (for diagnostics). */
|
|
53
|
-
error?: string;
|
|
29
|
+
declare class ConnectorError extends ToonClientError {
|
|
30
|
+
constructor(message: string, cause?: Error);
|
|
54
31
|
}
|
|
55
|
-
/** Read an ERC-20 token balance (balance + decimals + symbol) for `owner`. */
|
|
56
|
-
declare function readEvmTokenBalance(opts: {
|
|
57
|
-
rpcUrl: string;
|
|
58
|
-
chainKey: string;
|
|
59
|
-
tokenAddress: string;
|
|
60
|
-
owner: string;
|
|
61
|
-
}): Promise<WalletBalance>;
|
|
62
|
-
/** Read the native ETH balance (wei) for `owner` via `eth_getBalance`. */
|
|
63
|
-
declare function readEvmNativeBalance(opts: {
|
|
64
|
-
rpcUrl: string;
|
|
65
|
-
chainKey: string;
|
|
66
|
-
owner: string;
|
|
67
|
-
}): Promise<WalletTokenAmount>;
|
|
68
|
-
/** Read the native SOL balance (lamports) for `owner` via the `getBalance` RPC. */
|
|
69
|
-
declare function readSolanaNativeBalance(opts: {
|
|
70
|
-
rpcUrl: string;
|
|
71
|
-
owner: string;
|
|
72
|
-
fetchImpl?: typeof fetch;
|
|
73
|
-
}): Promise<WalletTokenAmount>;
|
|
74
|
-
/** Read the SPL-token balance for `owner`'s token account(s) of `mint`. */
|
|
75
|
-
declare function readSolanaTokenBalance(opts: {
|
|
76
|
-
rpcUrl: string;
|
|
77
|
-
mint: string;
|
|
78
|
-
owner: string;
|
|
79
|
-
fetchImpl?: typeof fetch;
|
|
80
|
-
}): Promise<WalletBalance>;
|
|
81
|
-
/** Read the native MINA balance (nanomina) for `owner` via the Mina GraphQL API. */
|
|
82
|
-
declare function readMinaBalance(opts: {
|
|
83
|
-
graphqlUrl: string;
|
|
84
|
-
owner: string;
|
|
85
|
-
fetchImpl?: typeof fetch;
|
|
86
|
-
}): Promise<WalletBalance>;
|
|
87
32
|
/**
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
* the caller from the network topology / presets, never hardcoded here. A chain
|
|
91
|
-
* key absent from the object is simply not read.
|
|
33
|
+
* Validation error for invalid input parameters.
|
|
34
|
+
* These errors are thrown before making any HTTP requests.
|
|
92
35
|
*/
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
chainKey: string;
|
|
96
|
-
rpcUrl: string;
|
|
97
|
-
owner: string;
|
|
98
|
-
tokenAddress?: string;
|
|
99
|
-
};
|
|
100
|
-
solana?: {
|
|
101
|
-
chainKey?: string;
|
|
102
|
-
rpcUrl: string;
|
|
103
|
-
owner: string;
|
|
104
|
-
tokenMint?: string;
|
|
105
|
-
};
|
|
106
|
-
mina?: {
|
|
107
|
-
chainKey?: string;
|
|
108
|
-
graphqlUrl: string;
|
|
109
|
-
owner: string;
|
|
110
|
-
/** Settlement-token Field id (decimal). Reads the token balance when set. */
|
|
111
|
-
tokenId?: string;
|
|
112
|
-
};
|
|
113
|
-
/** Injectable fetch (Solana/Mina JSON-RPC & GraphQL) for tests. */
|
|
114
|
-
fetchImpl?: typeof fetch;
|
|
36
|
+
declare class ValidationError extends ToonClientError {
|
|
37
|
+
constructor(message: string, cause?: Error);
|
|
115
38
|
}
|
|
116
39
|
/**
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
*
|
|
120
|
-
*
|
|
121
|
-
*
|
|
122
|
-
*
|
|
40
|
+
* Thrown when the one-time on-chain payment-channel OPEN reverts because the
|
|
41
|
+
* local settlement wallet has no native gas to pay for its own
|
|
42
|
+
* approve/openChannel/setTotalDeposit transactions. This is the channel OPEN
|
|
43
|
+
* only — per-write settlement rides ILP-over-HTTP and never spends gas. We
|
|
44
|
+
* remap ONLY this case so callers get an actionable message (fund the wallet)
|
|
45
|
+
* instead of the raw viem "...exceeds the balance of the account" string
|
|
46
|
+
* (toon-meta#65). Retryable once the wallet is funded; the underlying viem/RPC
|
|
47
|
+
* error is preserved as `cause`.
|
|
123
48
|
*/
|
|
124
|
-
declare
|
|
125
|
-
|
|
49
|
+
declare class ChannelFundingError extends ToonClientError {
|
|
50
|
+
readonly retryable = true;
|
|
51
|
+
constructor(message: string, cause?: Error);
|
|
52
|
+
}
|
|
126
53
|
/**
|
|
127
|
-
*
|
|
128
|
-
*
|
|
129
|
-
* packet already uses rather than as HTTP text.
|
|
130
|
-
*
|
|
131
|
-
* A faithful port of `connector_domain::envelope`
|
|
132
|
-
* (`crates/connector-domain/src/envelope.rs`) — a method, target, ordered
|
|
133
|
-
* headers and body going in; a two-byte big-endian status, headers and body
|
|
134
|
-
* coming back. `vectors/wire-vectors.json` is the contract this is checked
|
|
135
|
-
* against, and `wire-vectors.test.ts` is where that check happens; the prose
|
|
136
|
-
* here describes the same thing but the bytes decide.
|
|
137
|
-
*
|
|
138
|
-
* ─── Why not HTTP text ─────────────────────────────────────────────────────
|
|
139
|
-
* `utils/store-envelope.ts` builds latin1 HTTP/1.1 request text and
|
|
140
|
-
* `utils/fulfill-http.ts` hand-parses a status line and scans for `\r\n\r\n`,
|
|
141
|
-
* which is how they acquired leniencies nobody chose: a missing header/body
|
|
142
|
-
* separator yielding an empty body, blank header lines skipped, spaces
|
|
143
|
-
* tolerated inside the target. A structured encoding has exactly one
|
|
144
|
-
* representation per message and nothing to smuggle. This module lands BESIDE
|
|
145
|
-
* those two rather than replacing them — the swap is a later child — so it can
|
|
146
|
-
* be reviewed against the vectors in isolation.
|
|
147
|
-
*
|
|
148
|
-
* ─── Headers are a list, not a map ─────────────────────────────────────────
|
|
149
|
-
* A count prefix then `(name, value)` pairs in order. Both header ORDER and
|
|
150
|
-
* DUPLICATE NAMES are meaningful on this wire and both survive a round trip; a
|
|
151
|
-
* `Record<string, string>` would silently destroy each.
|
|
54
|
+
* Thrown when a persisted peer→channel binding names a channel whose CLAIM
|
|
55
|
+
* WATERMARK (nonce + cumulative amount) is missing from the channel store.
|
|
152
56
|
*
|
|
153
|
-
*
|
|
57
|
+
* Resuming it anyway would re-track the live channel at nonce 0, and the
|
|
58
|
+
* connector rejects every claim below the nonce it has already seen — the F01
|
|
59
|
+
* failure from the live measurement runs. Opening a fresh channel instead would
|
|
60
|
+
* silently strand the collateral in the existing one. Neither is safe to do
|
|
61
|
+
* quietly, so this is a hard error: the operator decides (settle the old
|
|
62
|
+
* channel, or restore the watermark file). Never delete a channel store for a
|
|
63
|
+
* live channel.
|
|
154
64
|
*/
|
|
65
|
+
declare class ChannelResumeError extends ToonClientError {
|
|
66
|
+
constructor(message: string, cause?: Error);
|
|
67
|
+
}
|
|
155
68
|
/**
|
|
156
|
-
*
|
|
157
|
-
* the
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
*
|
|
161
|
-
* There is deliberately no catch-all: a decoder with an `Invalid` bucket is a
|
|
162
|
-
* decoder that can be lenient without anyone noticing.
|
|
69
|
+
* Thrown by {@link ../transfer.js!sendTransfer} when the sender cannot cover
|
|
70
|
+
* the requested amount (plus, where applicable, the chain's own transaction
|
|
71
|
+
* fee) on the source chain. A PREFLIGHT failure — thrown before any
|
|
72
|
+
* transaction is built or submitted, so it never costs gas/fees.
|
|
163
73
|
*/
|
|
164
|
-
declare
|
|
165
|
-
|
|
166
|
-
BufferUnderflow = "buffer_underflow",
|
|
167
|
-
/** A length determinant that is not the minimal encoding of its value. */
|
|
168
|
-
NonCanonicalLength = "non_canonical_length",
|
|
169
|
-
/** A length determinant wider than eight bytes. */
|
|
170
|
-
LengthDeterminantOverflow = "length_determinant_overflow",
|
|
171
|
-
/** The type byte is not the one the requested direction requires. */
|
|
172
|
-
InvalidType = "invalid_type",
|
|
173
|
-
/** A field that must be UTF-8 is not. */
|
|
174
|
-
InvalidUtf8 = "invalid_utf8",
|
|
175
|
-
/** Bytes remain after a fully decoded envelope. */
|
|
176
|
-
TrailingBytes = "trailing_bytes"
|
|
74
|
+
declare class InsufficientBalanceError extends ToonClientError {
|
|
75
|
+
constructor(message: string, cause?: Error);
|
|
177
76
|
}
|
|
178
77
|
/**
|
|
179
|
-
*
|
|
180
|
-
* the
|
|
181
|
-
*
|
|
78
|
+
* Thrown when an EVM RPC never converges on a just-confirmed channel open —
|
|
79
|
+
* the read-after-write hole behind `sepolia.base.org`'s load balancer, whose
|
|
80
|
+
* replicas can serve a state that predates the `openChannel` receipt, making
|
|
81
|
+
* the follow-up `setTotalDeposit` revert `InvalidChannelState()` (#489).
|
|
182
82
|
*/
|
|
183
|
-
declare class
|
|
184
|
-
readonly
|
|
185
|
-
|
|
186
|
-
constructor(kind: EnvelopeErrorKind, field?: string | undefined);
|
|
83
|
+
declare class StaleRpcReadError extends ToonClientError {
|
|
84
|
+
readonly retryable = true;
|
|
85
|
+
constructor(message: string, cause?: Error);
|
|
187
86
|
}
|
|
188
|
-
/**
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
87
|
+
/**
|
|
88
|
+
* Thrown by {@link ../transfer.js!sendTransfer} when `chain` is not one this
|
|
89
|
+
* client can send on — either an unrecognized chain identifier, or a
|
|
90
|
+
* recognized chain the client instance has no configuration for (no
|
|
91
|
+
* `chainRpcUrls` entry, no `solanaChannel`, no `minaChannel`). Distinct from
|
|
92
|
+
* {@link InvalidAddressError} (the chain is fine, the destination isn't) and
|
|
93
|
+
* from a plain unsupported chain/asset combination (see the transfer module
|
|
94
|
+
* for chain-specific gaps, e.g. the Mina settlement token).
|
|
95
|
+
*/
|
|
96
|
+
declare class UnknownChainError extends ToonClientError {
|
|
97
|
+
constructor(message: string, cause?: Error);
|
|
196
98
|
}
|
|
197
|
-
/**
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
99
|
+
/**
|
|
100
|
+
* Thrown by {@link ../transfer.js!sendTransfer} when the destination address
|
|
101
|
+
* is malformed for the target chain (wrong format, wrong length, invalid
|
|
102
|
+
* charset) — checked BEFORE any transaction is built, so a typo never costs
|
|
103
|
+
* gas/fees or risks sending funds into a black hole.
|
|
104
|
+
*/
|
|
105
|
+
declare class InvalidAddressError extends ToonClientError {
|
|
106
|
+
constructor(message: string, cause?: Error);
|
|
203
107
|
}
|
|
204
|
-
/** Either direction, tagged — the shape the vector file's `decoded` carries. */
|
|
205
|
-
type Envelope = ({
|
|
206
|
-
direction: 'request';
|
|
207
|
-
} & EnvelopeRequest) | ({
|
|
208
|
-
direction: 'response';
|
|
209
|
-
} & EnvelopeResponse);
|
|
210
|
-
/** Encode a request envelope. The inverse of {@link decodeEnvelopeRequest}. */
|
|
211
|
-
declare function encodeEnvelopeRequest(request: EnvelopeRequest): Uint8Array;
|
|
212
108
|
/**
|
|
213
|
-
*
|
|
214
|
-
*
|
|
215
|
-
*
|
|
109
|
+
* Thrown by {@link ../transfer.js!sendTransfer} when a send was ACCEPTED by
|
|
110
|
+
* the chain (a landed, non-reverted transaction / a node-accepted payment)
|
|
111
|
+
* but the destination's observed balance never rose by the sent amount
|
|
112
|
+
* within the bounded wait. This is the failure {@link sendTransfer} exists to
|
|
113
|
+
* catch: the devnet faucet's Solana leg has been observed returning success
|
|
114
|
+
* with a real transaction signature while delivering 0 lamports
|
|
115
|
+
* (toon-protocol/connector#691) — trusting the send call's return value alone
|
|
116
|
+
* would report a funded destination that in fact holds nothing.
|
|
216
117
|
*/
|
|
217
|
-
declare
|
|
218
|
-
|
|
219
|
-
|
|
118
|
+
declare class TransferNotDeliveredError extends ToonClientError {
|
|
119
|
+
constructor(message: string, cause?: Error);
|
|
120
|
+
}
|
|
220
121
|
/**
|
|
221
|
-
*
|
|
222
|
-
*
|
|
223
|
-
*
|
|
122
|
+
* Thrown by {@link ../transfer.js!sendTransfer} for a chain/asset combination
|
|
123
|
+
* that is not implemented yet — e.g. the Mina settlement token (a custom
|
|
124
|
+
* token transfer needs an o1js zkApp-approval path this client doesn't build
|
|
125
|
+
* yet; native MINA is unaffected). Mirrors the documented Mina
|
|
126
|
+
* deposit/close/settle gaps in {@link ../channel/OnChainChannelClient.js!OnChainChannelClient}.
|
|
224
127
|
*/
|
|
225
|
-
declare
|
|
226
|
-
|
|
227
|
-
|
|
128
|
+
declare class TransferUnsupportedError extends ToonClientError {
|
|
129
|
+
constructor(message: string, cause?: Error);
|
|
130
|
+
}
|
|
228
131
|
/**
|
|
229
|
-
*
|
|
230
|
-
*
|
|
231
|
-
*
|
|
132
|
+
* True when `err` (or any error in its nested `cause` chain) is an
|
|
133
|
+
* insufficient-native-gas revert. viem wraps the node error one or more levels
|
|
134
|
+
* deep, so the whole chain is flattened and scanned.
|
|
232
135
|
*/
|
|
233
|
-
declare function
|
|
136
|
+
declare function isInsufficientGasError(err: unknown): boolean;
|
|
234
137
|
|
|
235
138
|
/**
|
|
236
|
-
*
|
|
139
|
+
* Ask a terminating connector who it is and what it charges — the step that
|
|
140
|
+
* has to happen BEFORE a packet can be formed at all.
|
|
237
141
|
*
|
|
238
|
-
*
|
|
239
|
-
*
|
|
240
|
-
*
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
142
|
+
* ADR 0018 makes holding the terminating connector's public key a
|
|
143
|
+
* precondition of forming a packet: `Prepare.data` is sealed to that key, and
|
|
144
|
+
* sealing to the wrong one is a confidentiality failure, not a delivery
|
|
145
|
+
* failure. ADR 0022 says the connector *answers* — it never announces — so
|
|
146
|
+
* both facts are fetched from the connector's own client edge, on the same
|
|
147
|
+
* origin this client already POSTs `/ilp` to
|
|
148
|
+
* (`docs/protocol/client-edge-spec.md` §1.7):
|
|
149
|
+
*
|
|
150
|
+
* - `GET /ilp/identity` → `{ "keyId": "...", "publicKey": "0x04..." }` — the
|
|
151
|
+
* uncompressed secp256k1 key, 65 bytes, `0x`-prefixed hex.
|
|
152
|
+
* - `GET /ilp/routes/price?destination=<ILP address>` →
|
|
153
|
+
* `{ "destination": "...", "price": 100 }`, or `404` when no
|
|
154
|
+
* locally-terminated route matches.
|
|
155
|
+
*
|
|
156
|
+
* Both are unauthenticated and neither changes state.
|
|
157
|
+
*
|
|
158
|
+
* ─── What this module refuses to do ────────────────────────────────────────
|
|
159
|
+
* Unlike the 402-challenge parser next door (which degrades gracefully so an
|
|
160
|
+
* unrecognised connector shape falls back to the vanilla 402), an identity is
|
|
161
|
+
* parsed STRICTLY. A key that is the wrong length, not `0x04`-prefixed, or not
|
|
162
|
+
* valid hex is refused with a distinguishable error rather than carried
|
|
163
|
+
* forward: a half-understood key would be sealed to, and the failure would be
|
|
164
|
+
* silent. There is no "best effort" reading of a public key.
|
|
165
|
+
*
|
|
166
|
+
* Pure transport + parsing: no keys are held, nothing is signed, and the only
|
|
167
|
+
* state is the identity cache.
|
|
168
|
+
*/
|
|
169
|
+
|
|
170
|
+
/** The terminating connector's own identity, as reported by `GET /ilp/identity`. */
|
|
171
|
+
interface ConnectorIdentity {
|
|
172
|
+
/** The key id identifying the key (opaque to this client). */
|
|
173
|
+
keyId: string;
|
|
174
|
+
/** The uncompressed secp256k1 public key — exactly 65 raw bytes, leading `0x04`. */
|
|
175
|
+
publicKey: Uint8Array;
|
|
176
|
+
/** The key exactly as reported, `0x`-prefixed lowercase hex (65 bytes → 132 chars). */
|
|
177
|
+
publicKeyHex: string;
|
|
178
|
+
/** The normalized client-edge base URL this identity was read from. */
|
|
179
|
+
endpoint: string;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* The channel-opening facts a settling connector carries in its x402
|
|
183
|
+
* greeting (connector #617): everything a buyer needs to OPEN a channel
|
|
184
|
+
* with the node, learned by ASKING (ADR 0022) rather than from a
|
|
185
|
+
* kind:10032 announce the Rust fleet never makes.
|
|
186
|
+
*/
|
|
187
|
+
interface ConnectorSettlementTerms {
|
|
188
|
+
/** `evm:<chainId>` — the chain the node's settlement backend runs on. */
|
|
189
|
+
chain: string;
|
|
190
|
+
/** The on-chain counterparty a buyer opens a channel WITH. */
|
|
191
|
+
settlementAddress: string;
|
|
192
|
+
/** The stable TokenNetworkRegistry factory address. */
|
|
193
|
+
tokenNetworkRegistry: string;
|
|
194
|
+
/** The resolved TokenNetwork — the EIP-712 verifyingContract. */
|
|
195
|
+
tokenNetwork: string;
|
|
196
|
+
tokenAddress: string;
|
|
197
|
+
/** Informational; claims are already in base units. */
|
|
198
|
+
decimals: number;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* The Solana twin of {@link ConnectorSettlementTerms} (connector #632): what
|
|
202
|
+
* an unaffiliated buyer needs to open a channel against a Solana settlement
|
|
203
|
+
* backend's deployed `payment-channel` program instance.
|
|
204
|
+
*/
|
|
205
|
+
interface ConnectorSolanaSettlementTerms {
|
|
206
|
+
/** Always `'solana'` — unlike EVM there is no chain id to append. */
|
|
207
|
+
chain: string;
|
|
208
|
+
/** The on-chain counterparty a buyer opens a channel WITH, base58. */
|
|
209
|
+
settlementAddress: string;
|
|
210
|
+
/** The deployed `payment-channel` program instance, base58. */
|
|
211
|
+
programId: string;
|
|
212
|
+
/** The SPL mint every channel this backend opens settles in, base58. */
|
|
213
|
+
tokenAddress: string;
|
|
214
|
+
/** Informational; claims are already in base units. */
|
|
215
|
+
decimals: number;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* One chain's entry in the x402 greeting's per-chain `settlements` list
|
|
219
|
+
* (connector #632). `kind` is added by this parser, not present on the wire
|
|
220
|
+
* — the wire is untagged, disambiguated structurally (`tokenNetworkRegistry`
|
|
221
|
+
* names EVM, `programId` names Solana).
|
|
222
|
+
*/
|
|
223
|
+
type ConnectorChainSettlementTerms = ({
|
|
224
|
+
kind: 'evm';
|
|
225
|
+
} & ConnectorSettlementTerms) | ({
|
|
226
|
+
kind: 'solana';
|
|
227
|
+
} & ConnectorSolanaSettlementTerms);
|
|
228
|
+
/**
|
|
229
|
+
* A route's terms as the x402 greeting states them: the price, plus (from a
|
|
230
|
+
* settling node) the channel-opening facts. `settlement` is absent exactly
|
|
231
|
+
* when the node has no settlement backend — the wire's own shape. `settlements`
|
|
232
|
+
* is the additive per-chain list (connector #632): one entry per chain the
|
|
233
|
+
* node settles on, including the same EVM entry `settlement` already carries.
|
|
234
|
+
* Absent — not an empty array — on a node with no settlement backend, or one
|
|
235
|
+
* still answering the pre-#632 greeting shape.
|
|
236
|
+
*/
|
|
237
|
+
interface ConnectorRouteTerms {
|
|
238
|
+
destination: string;
|
|
239
|
+
price: string;
|
|
240
|
+
settlement?: ConnectorSettlementTerms;
|
|
241
|
+
settlements?: ConnectorChainSettlementTerms[];
|
|
242
|
+
}
|
|
243
|
+
/** What a locally-terminated route costs, as reported by `GET /ilp/routes/price`. */
|
|
244
|
+
interface ConnectorRoutePrice {
|
|
245
|
+
/** The ILP destination that was asked about (echoed by the connector). */
|
|
246
|
+
destination: string;
|
|
247
|
+
/** The price in ILP base units of the route `destination` matched. */
|
|
248
|
+
price: bigint;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* One `POST /ilp/claim-state` request entry: proof of ownership of a channel
|
|
252
|
+
* this client controls, via a signature over a challenge distinct from a
|
|
253
|
+
* real claim's balance-proof (never reusable as one). `signature` is
|
|
254
|
+
* `EvmSigner.signClaimStateChallenge`'s `0x`-prefixed 65-byte hex for `evm`,
|
|
255
|
+
* `SolanaSigner.signClaimStateChallenge`'s base64 64-byte Ed25519 for
|
|
256
|
+
* `solana`.
|
|
257
|
+
*/
|
|
258
|
+
type ClaimStateRequestEntry = {
|
|
259
|
+
blockchain: 'evm';
|
|
260
|
+
channelId: string;
|
|
261
|
+
expires: number;
|
|
262
|
+
signature: string;
|
|
263
|
+
} | {
|
|
264
|
+
blockchain: 'solana';
|
|
265
|
+
channelAccount: string;
|
|
266
|
+
expires: number;
|
|
267
|
+
signature: string;
|
|
268
|
+
};
|
|
269
|
+
/**
|
|
270
|
+
* The credited/spendable position of one channel this client asked about —
|
|
271
|
+
* the runway source of truth (toon-meta#261/#262 decision 9). Money fields
|
|
272
|
+
* are decimal strings (never a bare JS number, which cannot represent a
|
|
273
|
+
* value past 2^53 exactly).
|
|
274
|
+
*/
|
|
275
|
+
interface ClaimStateOk {
|
|
276
|
+
blockchain: 'evm' | 'solana';
|
|
277
|
+
channelId?: string;
|
|
278
|
+
channelAccount?: string;
|
|
279
|
+
ok: true;
|
|
280
|
+
/** On-chain deposit, or `null` for a channel this connector only DECLARED. */
|
|
281
|
+
depositTotal: string | null;
|
|
282
|
+
/** The channel's watermark; `"0"` if this connector has never accepted a claim. */
|
|
283
|
+
cumulativeClaimed: string;
|
|
284
|
+
/** `depositTotal - cumulativeClaimed`; `null` exactly when `depositTotal` is. */
|
|
285
|
+
available: string | null;
|
|
286
|
+
nonce: number;
|
|
287
|
+
/**
|
|
288
|
+
* Best-effort and non-durable (unlike every other field here): `null`
|
|
289
|
+
* means "unknown", NEVER "never claimed" — see client-edge-spec.md §1.10.
|
|
290
|
+
*/
|
|
291
|
+
lastClaimTime: number | null;
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* A failed claim-state entry. `error` is deliberately collapsed to two
|
|
295
|
+
* causes (unlike a claim's own refusal taxonomy) so a caller learns nothing
|
|
296
|
+
* about a channel it does not control: `"unverified"` covers "no such
|
|
297
|
+
* channel" and "bad signature" identically.
|
|
298
|
+
*/
|
|
299
|
+
interface ClaimStateFailed {
|
|
300
|
+
blockchain: 'evm' | 'solana';
|
|
301
|
+
channelId?: string;
|
|
302
|
+
channelAccount?: string;
|
|
303
|
+
ok: false;
|
|
304
|
+
error: 'expired' | 'unverified';
|
|
305
|
+
}
|
|
306
|
+
type ClaimStateResult = ClaimStateOk | ClaimStateFailed;
|
|
307
|
+
/**
|
|
308
|
+
* Every distinguishable way asking a connector for its identity or terms can
|
|
309
|
+
* fail. Each code names exactly one cause; there is no catch-all, because the
|
|
310
|
+
* caller's next move differs per cause (retry a transport failure; never
|
|
311
|
+
* retry a malformed key).
|
|
312
|
+
*/
|
|
313
|
+
type ConnectorEdgeErrorCode =
|
|
314
|
+
/** Non-2xx from `GET /ilp/identity`. */
|
|
315
|
+
'IDENTITY_HTTP_STATUS'
|
|
316
|
+
/** `GET /ilp/identity` answered 2xx with a body that is not the documented object. */
|
|
317
|
+
| 'IDENTITY_MALFORMED'
|
|
318
|
+
/** `publicKey` is present but is not `0x`-prefixed even-length hex. */
|
|
319
|
+
| 'IDENTITY_KEY_NOT_HEX'
|
|
320
|
+
/** `publicKey` decodes, but not to exactly 65 bytes. */
|
|
321
|
+
| 'IDENTITY_KEY_LENGTH'
|
|
322
|
+
/** `publicKey` is 65 bytes but does not start with the SEC1 uncompressed tag `0x04`. */
|
|
323
|
+
| 'IDENTITY_KEY_NOT_UNCOMPRESSED'
|
|
324
|
+
/** Non-2xx, non-404 from `GET /ilp/routes/price` (404 is not an error — see below). */
|
|
325
|
+
| 'ROUTE_PRICE_HTTP_STATUS'
|
|
326
|
+
/** `GET /ilp/routes/price` answered 2xx with a body that is not the documented object. */
|
|
327
|
+
| 'ROUTE_PRICE_MALFORMED'
|
|
328
|
+
/** A destination that cannot be put in a query string was asked about. */
|
|
329
|
+
| 'INVALID_DESTINATION'
|
|
330
|
+
/** A 402 greeting whose body is not the documented x402 shape (or whose
|
|
331
|
+
* optional `settlement` facts are present but malformed — refused rather
|
|
332
|
+
* than silently dropped, since they would be opened AGAINST). */
|
|
333
|
+
| 'TERMS_MALFORMED'
|
|
334
|
+
/** Non-2xx from `POST /ilp/claim-state`. */
|
|
335
|
+
| 'CLAIM_STATE_HTTP_STATUS'
|
|
336
|
+
/** `POST /ilp/claim-state` answered 2xx with a body that is not the documented shape. */
|
|
337
|
+
| 'CLAIM_STATE_MALFORMED';
|
|
338
|
+
/**
|
|
339
|
+
* A refusal to carry a connector's answer forward. Distinct from
|
|
340
|
+
* {@link NetworkError} (which this module throws for a transport failure), so
|
|
341
|
+
* "the connector is unreachable" and "the connector answered something I will
|
|
342
|
+
* not seal to" are never confused.
|
|
343
|
+
*/
|
|
344
|
+
declare class ConnectorEdgeError extends ToonClientError {
|
|
345
|
+
/** Narrowed from `ToonClientError`'s `string`; type-only, no runtime field. */
|
|
346
|
+
readonly code: ConnectorEdgeErrorCode;
|
|
347
|
+
constructor(message: string, code: ConnectorEdgeErrorCode, cause?: Error);
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Normalize any client-edge URL a caller already holds into the base the
|
|
351
|
+
* `/ilp/*` routes hang off.
|
|
352
|
+
*
|
|
353
|
+
* Callers reach this module holding whatever the x402 offer or their config
|
|
354
|
+
* gave them — `https://apex.example`, `https://apex.example/`, or the
|
|
355
|
+
* `POST /ilp` endpoint `https://apex.example/ilp` itself. All three name the
|
|
356
|
+
* same client edge, so all three normalize to `https://apex.example`.
|
|
357
|
+
*/
|
|
358
|
+
declare function connectorEdgeBaseUrl(endpoint: string): string;
|
|
359
|
+
/**
|
|
360
|
+
* Decode a `0x`-prefixed hex public key into its 65 raw bytes, refusing
|
|
361
|
+
* anything that is not exactly one uncompressed secp256k1 key.
|
|
362
|
+
*/
|
|
363
|
+
declare function decodeConnectorPublicKey(publicKeyHex: string): Uint8Array;
|
|
364
|
+
/**
|
|
365
|
+
* Parse an already-decoded `GET /ilp/identity` body. Exported so the shape the
|
|
366
|
+
* connector actually emits can be pinned without standing up a server.
|
|
367
|
+
*/
|
|
368
|
+
declare function parseConnectorIdentity(body: unknown, endpoint: string): ConnectorIdentity;
|
|
369
|
+
/** Parse an already-decoded `GET /ilp/routes/price` 200 body. */
|
|
370
|
+
declare function parseConnectorRoutePrice(body: unknown): ConnectorRoutePrice;
|
|
371
|
+
/**
|
|
372
|
+
* Parse an already-decoded `POST /ilp/claim-state` body. Exported so the wire
|
|
373
|
+
* shape is testable without a server. Refuses a body that is not the
|
|
374
|
+
* documented `{ channels: [...] }` object, or any entry within it that is
|
|
375
|
+
* not the documented ok/failed shape — a half-understood credited balance
|
|
376
|
+
* would misreport an agent's runway, which is the one thing this endpoint
|
|
377
|
+
* exists to get right (toon-meta#262 decision 9).
|
|
378
|
+
*/
|
|
379
|
+
declare function parseClaimStateResponse(body: unknown): ClaimStateResult[];
|
|
380
|
+
interface ConnectorEdgeClientConfig {
|
|
381
|
+
/** HTTP fetch implementation. Default: global `fetch`. Injectable for tests. */
|
|
382
|
+
fetch?: typeof fetch;
|
|
383
|
+
/** Per-request timeout in milliseconds. Default 10_000. */
|
|
384
|
+
timeout?: number;
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Asks connectors for their identity and their terms, caching each identity
|
|
388
|
+
* per client-edge endpoint and each route price per (endpoint, destination).
|
|
389
|
+
*
|
|
390
|
+
* The cache is per endpoint rather than per client instance because a sender
|
|
391
|
+
* routinely speaks to several connectors, and re-fetching a key per packet
|
|
392
|
+
* would put a network round trip in front of every send. Nothing here expires
|
|
393
|
+
* on a timer: an operator key rotation, or a route being repriced, is a
|
|
394
|
+
* deliberate event, so {@link invalidateIdentity} / {@link invalidateRoutePrice}
|
|
395
|
+
* are how a stale answer is dropped.
|
|
396
|
+
*
|
|
397
|
+
* A price is cached the same way and for the same reason (toon-client#452):
|
|
398
|
+
* under ADR 0020 a route's price is FLAT — one handler, one price — so it does
|
|
399
|
+
* not vary with what is being sent, and asking again per packet would buy
|
|
400
|
+
* nothing but latency.
|
|
401
|
+
*/
|
|
402
|
+
declare class ConnectorEdgeClient {
|
|
403
|
+
private readonly fetchImpl;
|
|
404
|
+
private readonly timeout;
|
|
405
|
+
private readonly identities;
|
|
406
|
+
private readonly prices;
|
|
407
|
+
constructor(config?: ConnectorEdgeClientConfig);
|
|
408
|
+
/**
|
|
409
|
+
* The terminating connector's public key, fetched once per endpoint.
|
|
410
|
+
*
|
|
411
|
+
* @param endpoint any client-edge URL (`https://apex`, `https://apex/ilp`).
|
|
412
|
+
* @param options `forceRefresh` bypasses (and replaces) the cache entry.
|
|
413
|
+
*/
|
|
414
|
+
getIdentity(endpoint: string, options?: {
|
|
415
|
+
forceRefresh?: boolean;
|
|
416
|
+
}): Promise<ConnectorIdentity>;
|
|
417
|
+
/**
|
|
418
|
+
* Drop a cached identity — one endpoint's, or every endpoint's when
|
|
419
|
+
* `endpoint` is omitted. The way to react to a key rotation.
|
|
420
|
+
*/
|
|
421
|
+
invalidateIdentity(endpoint?: string): void;
|
|
422
|
+
/** Whether an identity for `endpoint` is already held (no request is made). */
|
|
423
|
+
hasCachedIdentity(endpoint: string): boolean;
|
|
424
|
+
/**
|
|
425
|
+
* What `destination` costs at this connector, or `null` when the connector
|
|
426
|
+
* answers `404` — no locally-terminated route matches it.
|
|
427
|
+
*
|
|
428
|
+
* `null` is the answer to "you do not terminate this", which is information;
|
|
429
|
+
* a transport failure throws {@link NetworkError} instead, so a caller can
|
|
430
|
+
* always tell "not mine" from "could not ask".
|
|
431
|
+
*
|
|
432
|
+
* Fetched once per (endpoint, destination) and reused. ADR 0020 makes a
|
|
433
|
+
* price flat per handler, so it does not vary with the packet — a route
|
|
434
|
+
* being repriced is an operator event, and {@link invalidateRoutePrice} is
|
|
435
|
+
* how a caller reacts to one.
|
|
436
|
+
*
|
|
437
|
+
* @param options `forceRefresh` bypasses (and replaces) the cache entry.
|
|
438
|
+
*/
|
|
439
|
+
getRoutePrice(endpoint: string, destination: string, options?: {
|
|
440
|
+
forceRefresh?: boolean;
|
|
441
|
+
}): Promise<ConnectorRoutePrice | null>;
|
|
442
|
+
/**
|
|
443
|
+
* Ask a route for its full x402 terms — the greeting a claimless PREPARE
|
|
444
|
+
* is answered with (client-edge-spec.md §1.4) — including, from a settling
|
|
445
|
+
* node, the channel-opening facts (connector #617).
|
|
446
|
+
*
|
|
447
|
+
* This is a real `POST /ilp` carrying a minimal PREPARE with no claim
|
|
448
|
+
* header. It is free by the wire's own contract: an unpaid request to a
|
|
449
|
+
* priced route is answered with terms instead of performed, and nothing
|
|
450
|
+
* is charged for asking. `null` when the connector does not price the
|
|
451
|
+
* destination (the request would be routed or refused, not greeted) —
|
|
452
|
+
* mapped from anything other than a 402 answer.
|
|
453
|
+
*/
|
|
454
|
+
getRouteTerms(endpoint: string, destination: string): Promise<ConnectorRouteTerms | null>;
|
|
455
|
+
/**
|
|
456
|
+
* The credited/spendable position of one or more channels this client
|
|
457
|
+
* controls (`POST /ilp/claim-state`, client-edge-spec.md §1.10) — the
|
|
458
|
+
* runway source of truth (toon-meta#261/#262 decision 9): earnings net
|
|
459
|
+
* off-chain on the same channel a client spends from, so this is also
|
|
460
|
+
* where a credited balance is read. Never cached: unlike identity/price,
|
|
461
|
+
* a claim watermark changes on every accepted claim, on EITHER side.
|
|
462
|
+
*
|
|
463
|
+
* Each entry is independently authenticated (own signature, own
|
|
464
|
+
* blockchain) — a request MAY mix EVM and Solana channels. Returns `[]`
|
|
465
|
+
* without a request when `channels` is empty.
|
|
466
|
+
*
|
|
467
|
+
* @throws {NetworkError} the connector could not be reached.
|
|
468
|
+
* @throws {ConnectorEdgeError} a non-2xx status, or a body that is not the
|
|
469
|
+
* documented shape.
|
|
470
|
+
*/
|
|
471
|
+
getClaimState(endpoint: string, channels: ClaimStateRequestEntry[]): Promise<ClaimStateResult[]>;
|
|
472
|
+
/**
|
|
473
|
+
* Drop a cached route price — one (endpoint, destination)'s, every
|
|
474
|
+
* destination's at one endpoint when `destination` is omitted, or all of
|
|
475
|
+
* them when both are. The way to react to a route being repriced.
|
|
476
|
+
*/
|
|
477
|
+
invalidateRoutePrice(endpoint?: string, destination?: string): void;
|
|
478
|
+
/**
|
|
479
|
+
* Whether a price for `(endpoint, destination)` is already held (no request
|
|
480
|
+
* is made).
|
|
481
|
+
*/
|
|
482
|
+
hasCachedRoutePrice(endpoint: string, destination: string): boolean;
|
|
483
|
+
private fetchRoutePrice;
|
|
484
|
+
private fetchIdentity;
|
|
485
|
+
private readJson;
|
|
486
|
+
/** GET with a timeout, mapping any transport failure onto {@link NetworkError}. */
|
|
487
|
+
private get;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* NIP-59 gift-wrap UNWRAP, receiver side only. Backs the daemon's
|
|
492
|
+
* `POST /nip59-unwrap` control-API endpoint (toon-meta#256): an external
|
|
493
|
+
* agent process (buzz#19's agent-members) hands the daemon a kind:1059 event
|
|
494
|
+
* addressed to the daemon's own Nostr identity, and gets back the decrypted
|
|
495
|
+
* inner event — without the daemon's secret key ever leaving this process,
|
|
496
|
+
* let alone the caller's.
|
|
497
|
+
*
|
|
498
|
+
* There is deliberately no `wrap` (sender) side here yet — nothing in this
|
|
499
|
+
* client originates gift wraps today (the swap rumor path builds its own via
|
|
500
|
+
* the sdk). Add one only when a sender use case actually needs it.
|
|
501
|
+
*
|
|
502
|
+
* Uses `nostr-tools/nip44` for both decrypt layers and `nostr-tools/pure`'s
|
|
503
|
+
* `verifyEvent` for the seal signature check — no hand-rolled crypto.
|
|
504
|
+
*
|
|
505
|
+
* ─── Why a bespoke unwrap instead of `nostr-tools/nip59`'s `unwrapEvent` ────
|
|
506
|
+
* `unwrapEvent` throws away the seal once it has decrypted through it, so it
|
|
507
|
+
* can never tell a caller who actually signed the rumor — only the wrap's
|
|
508
|
+
* ephemeral, throwaway `pubkey` is visible from outside. NIP-59 is explicit
|
|
509
|
+
* that authorship must be read off the SEAL, never the wrap, so this module
|
|
510
|
+
* decrypts the two layers by hand (still via `nip44.getConversationKey` /
|
|
511
|
+
* `nip44.decrypt`, the same primitives `unwrapEvent` uses internally) in
|
|
512
|
+
* order to surface `seal.pubkey` — verified against the seal's own
|
|
513
|
+
* signature, not merely trusted as a decrypted field.
|
|
514
|
+
*/
|
|
515
|
+
|
|
516
|
+
/** `kind:1059` — the outer gift wrap. */
|
|
517
|
+
declare const GIFT_WRAP_KIND = 1059;
|
|
518
|
+
/** `kind:13` — the inner seal, signed by the real author. */
|
|
519
|
+
declare const SEAL_KIND = 13;
|
|
520
|
+
/**
|
|
521
|
+
* The wrap was structurally invalid, not a gift wrap, or not addressed to
|
|
522
|
+
* the identity attempting to unwrap it. None of these required decrypting
|
|
523
|
+
* anything — they're rejectable from the event's plaintext envelope alone.
|
|
524
|
+
* Maps to HTTP 400 at the control-API boundary.
|
|
525
|
+
*/
|
|
526
|
+
declare class GiftWrapAddressError extends Error {
|
|
527
|
+
constructor(message: string);
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* The wrap looked addressable but a cryptographic step failed: a NIP-44
|
|
531
|
+
* layer didn't decrypt, the decrypted payload wasn't the expected event
|
|
532
|
+
* shape, or the seal's signature didn't verify against its own `pubkey`.
|
|
533
|
+
* Maps to HTTP 422 at the control-API boundary.
|
|
534
|
+
*/
|
|
535
|
+
declare class GiftWrapDecryptError extends Error {
|
|
536
|
+
constructor(message: string);
|
|
537
|
+
}
|
|
538
|
+
/** Result of a successful unwrap. */
|
|
539
|
+
interface UnwrappedGiftWrap {
|
|
540
|
+
/** The decrypted inner event (NIP-59 calls it the "rumor") — unsigned. */
|
|
541
|
+
rumor: UnsignedEvent & {
|
|
542
|
+
id?: string;
|
|
543
|
+
};
|
|
544
|
+
/**
|
|
545
|
+
* The hex pubkey that signed the kind:13 seal, VERIFIED against the seal's
|
|
546
|
+
* own signature. This — never `wrap.pubkey`, which NIP-59 mints fresh and
|
|
547
|
+
* throws away per wrap — is the real author.
|
|
548
|
+
*/
|
|
549
|
+
sealPubkey: string;
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* Unwrap a NIP-59 gift wrap addressed to `recipientPubkey`, decrypting both
|
|
553
|
+
* layers with `recipientSecretKey`. Pure function (no I/O, no client state)
|
|
554
|
+
* so it can be unit-tested directly against real `nostr-tools/nip59` fixtures
|
|
555
|
+
* — see `nip59.test.ts`. {@link ToonClient.unwrapGiftWrap} is a thin
|
|
556
|
+
* passthrough that supplies the client's own identity key.
|
|
557
|
+
*
|
|
558
|
+
* @throws {GiftWrapAddressError} malformed input, wrong kind, or not
|
|
559
|
+
* addressed to `recipientPubkey`.
|
|
560
|
+
* @throws {GiftWrapDecryptError} a NIP-44 layer failed to decrypt, decrypted
|
|
561
|
+
* to the wrong shape, or the seal's signature didn't verify.
|
|
562
|
+
*/
|
|
563
|
+
declare function unwrapGiftWrapWithKey(recipientSecretKey: Uint8Array, recipientPubkey: string, wrap: NostrEvent): UnwrappedGiftWrap;
|
|
564
|
+
|
|
565
|
+
/** One on-chain wallet token balance. `amount` is base-unit integer, decimal. */
|
|
566
|
+
interface WalletBalance {
|
|
567
|
+
chain: 'evm' | 'solana' | 'mina';
|
|
568
|
+
address: string;
|
|
569
|
+
amount: string;
|
|
570
|
+
/** Token symbol, when resolved (e.g. `'USDC'`, `'MINA'`). */
|
|
571
|
+
asset?: string;
|
|
572
|
+
/** Token decimals, when resolved. */
|
|
573
|
+
assetScale?: number;
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* One asset amount within a chain's wallet view — the native coin or one token.
|
|
577
|
+
* `amount` is a base-unit integer, decimal string.
|
|
578
|
+
*/
|
|
579
|
+
interface WalletTokenAmount {
|
|
580
|
+
/** Asset symbol (e.g. `'ETH'`, `'SOL'`, `'MINA'`, `'USDC'`), when known. */
|
|
581
|
+
symbol?: string;
|
|
582
|
+
/** Base-unit integer, decimal string. */
|
|
583
|
+
amount: string;
|
|
584
|
+
/** Decimals for formatting (ETH 18, SOL 9, MINA 9, USDC 6). */
|
|
585
|
+
decimals?: number;
|
|
586
|
+
/** Token contract / SPL mint address. Absent for the native coin. */
|
|
587
|
+
address?: string;
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
* The full wallet view for ONE chain the identity is configured for: the native
|
|
591
|
+
* coin plus every configured token, keyed by the chain's full key (e.g.
|
|
592
|
+
* `'evm:31337'`). `unreadable` marks a chain whose RPC could not be reached at
|
|
593
|
+
* all — the caller renders a per-chain notice rather than crashing.
|
|
594
|
+
*/
|
|
595
|
+
interface WalletChainBalances {
|
|
596
|
+
chain: 'evm' | 'solana' | 'mina';
|
|
597
|
+
/** Full chain key, e.g. `'evm:31337'`, `'solana'`, `'mina'`. */
|
|
598
|
+
chainKey: string;
|
|
599
|
+
address: string;
|
|
600
|
+
/** Native-coin balance, when readable. */
|
|
601
|
+
native?: WalletTokenAmount;
|
|
602
|
+
/** Configured token balances (e.g. USDC), each best-effort. */
|
|
603
|
+
tokens: WalletTokenAmount[];
|
|
604
|
+
/** True when nothing on this chain could be read (RPC unreachable). */
|
|
605
|
+
unreadable?: boolean;
|
|
606
|
+
/** First read error, when any read failed (for diagnostics). */
|
|
607
|
+
error?: string;
|
|
608
|
+
}
|
|
609
|
+
/** Read an ERC-20 token balance (balance + decimals + symbol) for `owner`. */
|
|
610
|
+
declare function readEvmTokenBalance(opts: {
|
|
611
|
+
rpcUrl: string;
|
|
612
|
+
chainKey: string;
|
|
613
|
+
tokenAddress: string;
|
|
614
|
+
owner: string;
|
|
615
|
+
}): Promise<WalletBalance>;
|
|
616
|
+
/** Read the native ETH balance (wei) for `owner` via `eth_getBalance`. */
|
|
617
|
+
declare function readEvmNativeBalance(opts: {
|
|
618
|
+
rpcUrl: string;
|
|
619
|
+
chainKey: string;
|
|
620
|
+
owner: string;
|
|
621
|
+
}): Promise<WalletTokenAmount>;
|
|
622
|
+
/** Read the native SOL balance (lamports) for `owner` via the `getBalance` RPC. */
|
|
623
|
+
declare function readSolanaNativeBalance(opts: {
|
|
624
|
+
rpcUrl: string;
|
|
625
|
+
owner: string;
|
|
626
|
+
fetchImpl?: typeof fetch;
|
|
627
|
+
}): Promise<WalletTokenAmount>;
|
|
628
|
+
/** Read the SPL-token balance for `owner`'s token account(s) of `mint`. */
|
|
629
|
+
declare function readSolanaTokenBalance(opts: {
|
|
630
|
+
rpcUrl: string;
|
|
631
|
+
mint: string;
|
|
632
|
+
owner: string;
|
|
633
|
+
fetchImpl?: typeof fetch;
|
|
634
|
+
}): Promise<WalletBalance>;
|
|
635
|
+
/** Read the native MINA balance (nanomina) for `owner` via the Mina GraphQL API. */
|
|
636
|
+
declare function readMinaBalance(opts: {
|
|
637
|
+
graphqlUrl: string;
|
|
638
|
+
owner: string;
|
|
639
|
+
fetchImpl?: typeof fetch;
|
|
640
|
+
}): Promise<WalletBalance>;
|
|
641
|
+
/**
|
|
642
|
+
* Per-chain inputs for {@link readWalletBalances}: the resolved RPC URL, the
|
|
643
|
+
* identity's address on that chain, and the configured token (USDC) — sourced by
|
|
644
|
+
* the caller from the network topology / presets, never hardcoded here. A chain
|
|
645
|
+
* key absent from the object is simply not read.
|
|
646
|
+
*/
|
|
647
|
+
interface WalletBalanceSources {
|
|
648
|
+
evm?: {
|
|
649
|
+
chainKey: string;
|
|
650
|
+
rpcUrl: string;
|
|
651
|
+
owner: string;
|
|
652
|
+
tokenAddress?: string;
|
|
653
|
+
};
|
|
654
|
+
solana?: {
|
|
655
|
+
chainKey?: string;
|
|
656
|
+
rpcUrl: string;
|
|
657
|
+
owner: string;
|
|
658
|
+
tokenMint?: string;
|
|
659
|
+
};
|
|
660
|
+
mina?: {
|
|
661
|
+
chainKey?: string;
|
|
662
|
+
graphqlUrl: string;
|
|
663
|
+
owner: string;
|
|
664
|
+
/** Settlement-token Field id (decimal). Reads the token balance when set. */
|
|
665
|
+
tokenId?: string;
|
|
666
|
+
};
|
|
667
|
+
/** Injectable fetch (Solana/Mina JSON-RPC & GraphQL) for tests. */
|
|
668
|
+
fetchImpl?: typeof fetch;
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* Read the full wallet view — native coin + configured tokens — for every chain
|
|
672
|
+
* in `sources`, keyed per chain. FREE: read-only RPC, no signing. Each chain is
|
|
673
|
+
* read independently and in parallel; a chain whose RPC is unreachable degrades
|
|
674
|
+
* to `{ unreadable: true, error }` instead of failing the others. Within a chain
|
|
675
|
+
* the native and token reads are independent, so a native read can succeed even
|
|
676
|
+
* if the token read fails (and vice versa).
|
|
677
|
+
*/
|
|
678
|
+
declare function readWalletBalances(sources: WalletBalanceSources): Promise<WalletChainBalances[]>;
|
|
679
|
+
|
|
680
|
+
/**
|
|
681
|
+
* The structured envelope (ADR 0018): what a packet carries between a
|
|
682
|
+
* connector and the app behind it, encoded with the same OER primitives an ILP
|
|
683
|
+
* packet already uses rather than as HTTP text.
|
|
684
|
+
*
|
|
685
|
+
* A faithful port of `connector_domain::envelope`
|
|
686
|
+
* (`crates/connector-domain/src/envelope.rs`) — a method, target, ordered
|
|
687
|
+
* headers and body going in; a two-byte big-endian status, headers and body
|
|
688
|
+
* coming back. `vectors/wire-vectors.json` is the contract this is checked
|
|
689
|
+
* against, and `wire-vectors.test.ts` is where that check happens; the prose
|
|
690
|
+
* here describes the same thing but the bytes decide.
|
|
691
|
+
*
|
|
692
|
+
* ─── Why not HTTP text ─────────────────────────────────────────────────────
|
|
693
|
+
* `utils/store-envelope.ts` builds latin1 HTTP/1.1 request text and
|
|
694
|
+
* `utils/fulfill-http.ts` hand-parses a status line and scans for `\r\n\r\n`,
|
|
695
|
+
* which is how they acquired leniencies nobody chose: a missing header/body
|
|
696
|
+
* separator yielding an empty body, blank header lines skipped, spaces
|
|
697
|
+
* tolerated inside the target. A structured encoding has exactly one
|
|
698
|
+
* representation per message and nothing to smuggle. This module lands BESIDE
|
|
699
|
+
* those two rather than replacing them — the swap is a later child — so it can
|
|
700
|
+
* be reviewed against the vectors in isolation.
|
|
701
|
+
*
|
|
702
|
+
* ─── Headers are a list, not a map ─────────────────────────────────────────
|
|
703
|
+
* A count prefix then `(name, value)` pairs in order. Both header ORDER and
|
|
704
|
+
* DUPLICATE NAMES are meaningful on this wire and both survive a round trip; a
|
|
705
|
+
* `Record<string, string>` would silently destroy each.
|
|
706
|
+
*
|
|
707
|
+
* Pure: no keys, no I/O, no clock. `@noble/*` is not involved.
|
|
708
|
+
*/
|
|
709
|
+
/**
|
|
710
|
+
* Every distinguishable way an envelope can fail to decode. These strings are
|
|
711
|
+
* the vector file's `expected_error` values verbatim — the same names
|
|
712
|
+
* `EnvelopeError` uses in `connector-domain` — so a replay compares reasons,
|
|
713
|
+
* not just "it threw".
|
|
714
|
+
*
|
|
715
|
+
* There is deliberately no catch-all: a decoder with an `Invalid` bucket is a
|
|
716
|
+
* decoder that can be lenient without anyone noticing.
|
|
717
|
+
*/
|
|
718
|
+
declare enum EnvelopeErrorKind {
|
|
719
|
+
/** The buffer ends before the envelope does. */
|
|
720
|
+
BufferUnderflow = "buffer_underflow",
|
|
721
|
+
/** A length determinant that is not the minimal encoding of its value. */
|
|
722
|
+
NonCanonicalLength = "non_canonical_length",
|
|
723
|
+
/** A length determinant wider than eight bytes. */
|
|
724
|
+
LengthDeterminantOverflow = "length_determinant_overflow",
|
|
725
|
+
/** The type byte is not the one the requested direction requires. */
|
|
726
|
+
InvalidType = "invalid_type",
|
|
727
|
+
/** A field that must be UTF-8 is not. */
|
|
728
|
+
InvalidUtf8 = "invalid_utf8",
|
|
729
|
+
/** Bytes remain after a fully decoded envelope. */
|
|
730
|
+
TrailingBytes = "trailing_bytes"
|
|
731
|
+
}
|
|
732
|
+
/**
|
|
733
|
+
* A refusal to decode. `kind` is the machine-readable reason; `field` names
|
|
734
|
+
* the offending field for {@link EnvelopeErrorKind.InvalidUtf8}, matching
|
|
735
|
+
* `EnvelopeError::InvalidUtf8(&'static str)` on the Rust side.
|
|
736
|
+
*/
|
|
737
|
+
declare class EnvelopeError extends Error {
|
|
738
|
+
readonly kind: EnvelopeErrorKind;
|
|
739
|
+
readonly field?: string | undefined;
|
|
740
|
+
constructor(kind: EnvelopeErrorKind, field?: string | undefined);
|
|
741
|
+
}
|
|
742
|
+
/** One `(name, value)` header, in wire order. Duplicates are legal. */
|
|
743
|
+
type EnvelopeHeader = readonly [name: string, value: string];
|
|
744
|
+
/** The request a connector is to make of the app behind a terminated route. */
|
|
745
|
+
interface EnvelopeRequest {
|
|
746
|
+
method: string;
|
|
747
|
+
target: string;
|
|
748
|
+
headers: readonly EnvelopeHeader[];
|
|
749
|
+
body: Uint8Array;
|
|
750
|
+
}
|
|
751
|
+
/** The app's response back to the connector. */
|
|
752
|
+
interface EnvelopeResponse {
|
|
753
|
+
/** HTTP status, two bytes big-endian on the wire (`0..=65535`). */
|
|
754
|
+
status: number;
|
|
755
|
+
headers: readonly EnvelopeHeader[];
|
|
756
|
+
body: Uint8Array;
|
|
757
|
+
}
|
|
758
|
+
/** Either direction, tagged — the shape the vector file's `decoded` carries. */
|
|
759
|
+
type Envelope = ({
|
|
760
|
+
direction: 'request';
|
|
761
|
+
} & EnvelopeRequest) | ({
|
|
762
|
+
direction: 'response';
|
|
763
|
+
} & EnvelopeResponse);
|
|
764
|
+
/** Encode a request envelope. The inverse of {@link decodeEnvelopeRequest}. */
|
|
765
|
+
declare function encodeEnvelopeRequest(request: EnvelopeRequest): Uint8Array;
|
|
766
|
+
/**
|
|
767
|
+
* Decode a request envelope, consuming the WHOLE buffer.
|
|
768
|
+
*
|
|
769
|
+
* @throws {EnvelopeError} and nothing else, for any input whatsoever.
|
|
770
|
+
*/
|
|
771
|
+
declare function decodeEnvelopeRequest(buf: Uint8Array): EnvelopeRequest;
|
|
772
|
+
/** Encode a response envelope. The inverse of {@link decodeEnvelopeResponse}. */
|
|
773
|
+
declare function encodeEnvelopeResponse(response: EnvelopeResponse): Uint8Array;
|
|
774
|
+
/**
|
|
775
|
+
* Decode a response envelope, consuming the WHOLE buffer.
|
|
776
|
+
*
|
|
777
|
+
* @throws {EnvelopeError} and nothing else, for any input whatsoever.
|
|
778
|
+
*/
|
|
779
|
+
declare function decodeEnvelopeResponse(buf: Uint8Array): EnvelopeResponse;
|
|
780
|
+
/** Encode either direction from its tagged form. */
|
|
781
|
+
declare function encodeEnvelope(envelope: Envelope): Uint8Array;
|
|
782
|
+
/**
|
|
783
|
+
* Decode as the named direction. The direction is an INPUT, never guessed from
|
|
784
|
+
* the type byte: a caller that asked for a request and got a response has been
|
|
785
|
+
* handed the wrong bytes, and `invalid_type` is the honest answer.
|
|
786
|
+
*/
|
|
787
|
+
declare function decodeEnvelope(buf: Uint8Array, direction: 'request' | 'response'): Envelope;
|
|
788
|
+
|
|
789
|
+
interface BTPProtocolData {
|
|
790
|
+
protocolName: string;
|
|
791
|
+
contentType: number;
|
|
792
|
+
data: Uint8Array;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/**
|
|
796
|
+
* Isomorphic BTP client — works in both browser and Node.js.
|
|
797
|
+
* Uses native WebSocket (browser) or globalThis.WebSocket (Node 21+).
|
|
798
|
+
* No dependency on `ws`, `events`, or `Buffer`.
|
|
799
|
+
*
|
|
800
|
+
* Replaces the @toon-protocol/connector BTPClient for the client SDK.
|
|
801
|
+
*/
|
|
802
|
+
|
|
803
|
+
/** A server-originated MESSAGE (RFC-0023 symmetric grammar, toon-client#493). */
|
|
804
|
+
interface InboundBtpMessage {
|
|
805
|
+
requestId: number;
|
|
806
|
+
protocolData: BTPProtocolData[];
|
|
807
|
+
ilpPacket?: Uint8Array;
|
|
808
|
+
}
|
|
809
|
+
/** A server-originated TRANSFER — settlement value, never an ILP packet. */
|
|
810
|
+
interface InboundBtpTransfer {
|
|
811
|
+
requestId: number;
|
|
812
|
+
amount: bigint;
|
|
813
|
+
protocolData: BTPProtocolData[];
|
|
814
|
+
}
|
|
815
|
+
/** What an inbound handler answers with — becomes the RESPONSE frame's body. */
|
|
816
|
+
interface BtpHandlerResponse {
|
|
817
|
+
protocolData?: BTPProtocolData[];
|
|
818
|
+
ilpPacket?: Uint8Array;
|
|
819
|
+
}
|
|
820
|
+
type BtpMessageHandler = (message: InboundBtpMessage) => Promise<BtpHandlerResponse> | BtpHandlerResponse;
|
|
821
|
+
type BtpTransferHandler = (transfer: InboundBtpTransfer) => Promise<BtpHandlerResponse> | BtpHandlerResponse;
|
|
822
|
+
|
|
823
|
+
/**
|
|
824
|
+
* Serve-side job handling (toon-client#494, toon-meta#262 "agents earning").
|
|
825
|
+
*
|
|
826
|
+
* The connector originates a server-originated BTP MESSAGE carrying a PREPARE
|
|
827
|
+
* for this client's registered ILP address (RFC-0023 symmetric grammar,
|
|
828
|
+
* toon-client#493) — the earning half of the wire that `sendSwapPacket` /
|
|
829
|
+
* `publishEvent` already use to PAY. {@link createJobMessageHandler} plugs a
|
|
830
|
+
* caller-supplied {@link JobHandler} into `BtpRuntimeClientConfig.onMessage`
|
|
831
|
+
* so a provider writes a handler, never a payments integration
|
|
832
|
+
* (`connector-runtime/src/app_client.rs`'s payment-oblivious app contract,
|
|
833
|
+
* carried over to the BTP-served case this ticket adds).
|
|
834
|
+
*
|
|
835
|
+
* Delivery is hashlock (toon-meta#262 decision 5, `hashlock-delivery.ts`
|
|
836
|
+
* toon-client#495): the handler returns the fulfillment preimage it already
|
|
837
|
+
* minted at quote time via {@link encryptArtifact}/{@link fulfillIncrement} —
|
|
838
|
+
* this module never derives a condition/preimage relationship itself, only
|
|
839
|
+
* verifies the handler's answer against the PREPARE's own condition before
|
|
840
|
+
* it goes on the wire.
|
|
841
|
+
*
|
|
842
|
+
* Error policy (ADR 0020 "you pay for an answer, not the answer you
|
|
843
|
+
* wanted", RFC-0027 F99 "Application Error — the terminating app declined
|
|
844
|
+
* the delivery, or supplied no fulfilment matching the execution
|
|
845
|
+
* condition"): a handler that throws, or whose returned fulfillment does not
|
|
846
|
+
* satisfy the PREPARE's condition, answers F99 — the two cases RFC-0027's
|
|
847
|
+
* own F99 gloss already names together. An already-expired PREPARE is
|
|
848
|
+
* refused R00 without ever invoking the handler, so a provider is never
|
|
849
|
+
* asked to do paid work for a packet that can no longer be honored. An
|
|
850
|
+
* undecodable PREPARE is refused F00. None of these paths ever throw back
|
|
851
|
+
* into the BTP transport — every outcome is an answer (a RESPONSE frame
|
|
852
|
+
* carrying FULFILL or REJECT), matching the symmetric grammar's "every
|
|
853
|
+
* request gets an answer" contract.
|
|
854
|
+
*/
|
|
855
|
+
|
|
856
|
+
/** One connector-originated job PREPARE, decoded and ready for a handler. */
|
|
857
|
+
interface JobRequest {
|
|
858
|
+
/** The packet's paid amount (base units) — informational only; see ADR 0020. */
|
|
859
|
+
amount: bigint;
|
|
860
|
+
/** The ILP address the PREPARE addressed (this client's own, per §1.9). */
|
|
861
|
+
destination: string;
|
|
862
|
+
/** The hashlock condition the handler's fulfillment must satisfy. */
|
|
863
|
+
executionCondition: Uint8Array;
|
|
864
|
+
/** When this PREPARE can no longer be honored. */
|
|
865
|
+
expiresAt: Date;
|
|
866
|
+
/** Opaque application payload — passed through unexamined (ADR 0018). */
|
|
867
|
+
data: Uint8Array;
|
|
868
|
+
}
|
|
869
|
+
/** What a {@link JobHandler} answers a job with. */
|
|
870
|
+
interface JobAnswer {
|
|
871
|
+
/**
|
|
872
|
+
* The fulfillment preimage — reveals the hashlock key (toon-meta#262
|
|
873
|
+
* decision 5). MUST satisfy `sha256(fulfillment) === executionCondition`;
|
|
874
|
+
* see {@link fulfillIncrement} in `hashlock-delivery.ts` for the one call
|
|
875
|
+
* site that should ever produce this value.
|
|
876
|
+
*/
|
|
877
|
+
fulfillment: Uint8Array;
|
|
878
|
+
/** Answer payload returned in the FULFILL's `data` field. Defaults to empty. */
|
|
879
|
+
data?: Uint8Array;
|
|
880
|
+
}
|
|
881
|
+
/**
|
|
882
|
+
* A provider's job handler: receives a job and returns an answer. Amount,
|
|
883
|
+
* payer and chain never arrive as parameters here (ADR 0020's payment-
|
|
884
|
+
* oblivious app contract) — the handler is never something that must verify
|
|
885
|
+
* a payment, only produce a fulfillment for one already validated by the
|
|
886
|
+
* claim gate before this MESSAGE was ever originated.
|
|
887
|
+
*/
|
|
888
|
+
type JobHandler = (job: JobRequest) => Promise<JobAnswer> | JobAnswer;
|
|
889
|
+
/**
|
|
890
|
+
* Wraps a {@link JobHandler} as a `BtpRuntimeClientConfig`/`IsomorphicBtpClientConfig`
|
|
891
|
+
* `onMessage` handler: decodes an inbound job PREPARE, invokes `handler`, and
|
|
892
|
+
* answers with a RESPONSE carrying FULFILL or REJECT — see this module's own
|
|
893
|
+
* doc for the exact error-code policy.
|
|
894
|
+
*
|
|
895
|
+
* A server-originated MESSAGE that carries no PREPARE at all (§1.9 step 1's
|
|
896
|
+
* auth MESSAGE, or a claim-only standalone MESSAGE) is not a job; it is
|
|
897
|
+
* answered with an empty RESPONSE, unchanged from the pre-#494 default.
|
|
898
|
+
*/
|
|
899
|
+
declare function createJobMessageHandler(handler: JobHandler): BtpMessageHandler;
|
|
900
|
+
|
|
901
|
+
/**
|
|
902
|
+
* Solana payment-channel parameters supplied via `ToonClientConfig.solanaChannel`.
|
|
903
|
+
*
|
|
904
|
+
* Mirrors the `SolanaChannelConfig` consumed by `OnChainChannelClient`, minus
|
|
905
|
+
* the Ed25519 keypair (derived from the client's `mnemonic`, see
|
|
906
|
+
* `ToonClientConfig.solanaChannel`).
|
|
907
|
+
*/
|
|
908
|
+
interface SolanaChannelClientOptions {
|
|
909
|
+
/** Solana JSON-RPC URL used to open the channel + read PDA state. */
|
|
910
|
+
rpcUrl: string;
|
|
911
|
+
/** Deployed payment-channel program id (base58). */
|
|
912
|
+
programId: string;
|
|
913
|
+
/**
|
|
248
914
|
* Default SPL token mint (base58) for PDA derivation. The per-channel
|
|
249
915
|
* negotiated token (the peer's preferred token) takes precedence when present.
|
|
250
916
|
*/
|
|
@@ -460,6 +1126,17 @@ interface ToonClientConfig {
|
|
|
460
1126
|
network?: 'mainnet' | 'testnet' | 'devnet' | 'custom';
|
|
461
1127
|
/** Supported settlement chain identifiers (e.g., ["evm:anvil:31337"]) */
|
|
462
1128
|
supportedChains?: string[];
|
|
1129
|
+
/**
|
|
1130
|
+
* Explicitly-configured settlement chain FAMILY (e.g. from the daemon's
|
|
1131
|
+
* `TOON_CLIENT_CHAIN` env var / `chain` config field, #485). When set,
|
|
1132
|
+
* default-chain resolution (`getDefaultChainContext`, the lightweight
|
|
1133
|
+
* bootstrap-fallback chain match) MUST pick the `supportedChains` entry
|
|
1134
|
+
* whose family (the part before the first `:`) matches this value —
|
|
1135
|
+
* throwing a clear error instead of silently substituting a different
|
|
1136
|
+
* chain when none matches. Leave unset to keep the pre-#485 behavior of
|
|
1137
|
+
* defaulting to `supportedChains[0]`.
|
|
1138
|
+
*/
|
|
1139
|
+
preferredChain?: 'evm' | 'solana' | 'mina';
|
|
463
1140
|
/** Maps chain identifier to EVM settlement address */
|
|
464
1141
|
settlementAddresses?: Record<string, string>;
|
|
465
1142
|
/** Maps chain identifier to preferred token contract address */
|
|
@@ -517,6 +1194,39 @@ interface ToonClientConfig {
|
|
|
517
1194
|
* false (no upgrade) when omitted.
|
|
518
1195
|
*/
|
|
519
1196
|
connectorSupportsUpgrade?: boolean;
|
|
1197
|
+
/**
|
|
1198
|
+
* Prefer the persistent, strictly-ordered {@link BtpPaidWriteTransport} for
|
|
1199
|
+
* paid writes (`publishEvent`/`sendSwapPacket`/`sendPayment`) over the
|
|
1200
|
+
* default stateless HTTP one-shot transport, when a `btpUrl` is configured.
|
|
1201
|
+
*
|
|
1202
|
+
* The BTP client-facing websocket ingress processes claims on one session
|
|
1203
|
+
* strictly in arrival order (client-edge-spec.md §1.9), which is what a
|
|
1204
|
+
* burst of concurrent paid writes on one channel needs to avoid racing
|
|
1205
|
+
* itself into `F01 NonceNotAdvancing` — a failure mode possible on the
|
|
1206
|
+
* default stateless HTTP transport, where each write is an independent
|
|
1207
|
+
* request. Set this when the consumer sends many paid writes on one
|
|
1208
|
+
* channel in quick succession (e.g. relay-native huddle audio frames);
|
|
1209
|
+
* leave it unset for ordinary publish-and-forget usage.
|
|
1210
|
+
*
|
|
1211
|
+
* Default: `false` — paid writes keep going through the existing HTTP
|
|
1212
|
+
* transport unchanged (toon-client#482 productizes BTP as an opt-in
|
|
1213
|
+
* upgrade, not a default-behavior change). When `true` and no `btpUrl`
|
|
1214
|
+
* (directly or derived) resolves, this has no effect — the existing
|
|
1215
|
+
* transport selection is unchanged.
|
|
1216
|
+
*/
|
|
1217
|
+
preferBtpForPaidWrites?: boolean;
|
|
1218
|
+
/**
|
|
1219
|
+
* Serve-side registration (toon-client#494, toon-meta#262 "agents
|
|
1220
|
+
* earning"): a handler for connector-originated jobs addressed to this
|
|
1221
|
+
* client's own ILP address. When set, a server-originated BTP MESSAGE
|
|
1222
|
+
* carrying a PREPARE (RFC-0023 symmetric grammar, toon-client#493) is
|
|
1223
|
+
* decoded, handed to this function, and answered with the FULFILL/REJECT
|
|
1224
|
+
* it produces — see `serve-job.ts` for the exact error-code policy. Only
|
|
1225
|
+
* takes effect when a `btpUrl` is configured (job serving rides the same
|
|
1226
|
+
* persistent BTP session paid writes use); unset means this client never
|
|
1227
|
+
* answers a connector-originated job, unchanged from the pre-#494 default.
|
|
1228
|
+
*/
|
|
1229
|
+
jobHandler?: JobHandler;
|
|
520
1230
|
/**
|
|
521
1231
|
* ILP destination address for event publishing.
|
|
522
1232
|
* Defaults to the connector's local address (derived from connectorUrl host).
|
|
@@ -586,7 +1296,16 @@ interface ToonClientConfig {
|
|
|
586
1296
|
r: string;
|
|
587
1297
|
s: string;
|
|
588
1298
|
}>;
|
|
589
|
-
/**
|
|
1299
|
+
/**
|
|
1300
|
+
* File path for persisting payment channel nonce/amount state across restarts.
|
|
1301
|
+
*
|
|
1302
|
+
* Also enables CHANNEL RESUME (#489): a sibling file (`channels.json` →
|
|
1303
|
+
* `channels.peers.json`) records which on-chain channel this identity holds
|
|
1304
|
+
* with each peer, so a restarted client re-attaches to it — with its claim
|
|
1305
|
+
* watermark — instead of opening a second channel and locking a second lot of
|
|
1306
|
+
* collateral. Never delete these files for a live channel: the collateral
|
|
1307
|
+
* stays locked on-chain and the watermark is unrecoverable.
|
|
1308
|
+
*/
|
|
590
1309
|
channelStorePath?: string;
|
|
591
1310
|
/** Nostr relay URL for peer discovery. Default: 'wss://relay-ws.devnet.toonprotocol.dev' */
|
|
592
1311
|
relayUrl?: string;
|
|
@@ -832,598 +1551,603 @@ declare function requestBlobStorage(client: ToonClient, secretKey: Uint8Array, p
|
|
|
832
1551
|
declare function extractArweaveTxId(response: EnvelopeResponse): string;
|
|
833
1552
|
|
|
834
1553
|
/**
|
|
835
|
-
*
|
|
836
|
-
* (toon-client#350; contract: connector `docs/local-delivery-fulfillment-contract.md`,
|
|
837
|
-
* connector#309; spec: toon-meta `docs/rolling-swap.md` §3).
|
|
838
|
-
*
|
|
839
|
-
* Both ILP transports (HTTP `POST /ilp` and BTP) take the SAME extended send
|
|
840
|
-
* params and map FULFILL/REJECT responses through the SAME verifier so the
|
|
841
|
-
* two paths cannot drift:
|
|
842
|
-
*
|
|
843
|
-
* - absent/all-zero `executionCondition` → legacy class: today's behavior,
|
|
844
|
-
* byte-for-byte (zero condition on the wire, no FULFILL verification);
|
|
845
|
-
* - non-zero `executionCondition` → sender-chosen: the condition goes on
|
|
846
|
-
* the PREPARE verbatim and the FULFILL's 32-byte fulfillment MUST hash
|
|
847
|
-
* back to it — a missing/malformed/mismatching preimage is surfaced as a
|
|
848
|
-
* FAILED result (never a silent accept, never retried).
|
|
1554
|
+
* Chain-specific metadata (discriminated union).
|
|
849
1555
|
*/
|
|
850
|
-
|
|
1556
|
+
type ChainMetadata = {
|
|
1557
|
+
chainType: 'evm';
|
|
1558
|
+
chainId: number;
|
|
1559
|
+
tokenNetworkAddress: string;
|
|
1560
|
+
tokenAddress?: string;
|
|
1561
|
+
} | {
|
|
1562
|
+
chainType: 'solana';
|
|
1563
|
+
programId: string;
|
|
1564
|
+
tokenMint?: string;
|
|
1565
|
+
} | {
|
|
1566
|
+
chainType: 'mina';
|
|
1567
|
+
zkAppAddress: string;
|
|
1568
|
+
tokenId?: string;
|
|
1569
|
+
};
|
|
851
1570
|
/**
|
|
852
|
-
*
|
|
853
|
-
* `@toon-protocol/core` `IlpClient` param shape with the sender-chosen
|
|
854
|
-
* condition and an explicit expiry — plain `IlpClient` callers keep working
|
|
855
|
-
* unchanged (both extras are optional; omitting them is the legacy path).
|
|
1571
|
+
* Chain-agnostic signing interface for balance proofs.
|
|
856
1572
|
*/
|
|
857
|
-
interface
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
1573
|
+
interface ChainSigner {
|
|
1574
|
+
readonly chainType: 'evm' | 'solana' | 'mina';
|
|
1575
|
+
readonly signerIdentifier: string;
|
|
1576
|
+
signBalanceProof(params: {
|
|
1577
|
+
channelId: string;
|
|
1578
|
+
nonce: number;
|
|
1579
|
+
transferredAmount: bigint;
|
|
1580
|
+
lockedAmount: bigint;
|
|
1581
|
+
locksRoot: string;
|
|
1582
|
+
/**
|
|
1583
|
+
* Counterparty settlement address the proof is bound to. Required for
|
|
1584
|
+
* Solana/Mina (folded into the canonical balance-proof message); the EVM
|
|
1585
|
+
* adapter ignores it (EIP-712 has no recipient term).
|
|
1586
|
+
*/
|
|
1587
|
+
recipient: string;
|
|
1588
|
+
metadata: ChainMetadata;
|
|
1589
|
+
/**
|
|
1590
|
+
* On-chain channel `depositTotal` (base units). When supplied (>0), a Mina
|
|
1591
|
+
* signer binds the conserved `balanceB = depositTotal − balanceA` commitment
|
|
1592
|
+
* required to settle on a funded zkApp (connector#133); EVM/Solana signers
|
|
1593
|
+
* ignore it. When omitted, a Mina signer self-resolves it from chain if it
|
|
1594
|
+
* was configured with a GraphQL URL (#223), else falls back to the legacy
|
|
1595
|
+
* `balanceB = 0` form.
|
|
1596
|
+
*/
|
|
1597
|
+
depositTotal?: bigint;
|
|
1598
|
+
}): Promise<SignedBalanceProof>;
|
|
1599
|
+
buildClaimMessage(proof: SignedBalanceProof, senderId: string): ClaimMessage;
|
|
876
1600
|
}
|
|
1601
|
+
type ClaimMessage = EVMClaimMessage | SolanaClaimMessage | MinaClaimMessage;
|
|
877
1602
|
/**
|
|
878
|
-
*
|
|
879
|
-
*
|
|
880
|
-
*
|
|
1603
|
+
* Solana payment-channel claim — wire-compatible with the connector's
|
|
1604
|
+
* `SolanaClaimMessage` (`@toon-protocol/connector` `btp/btp-claim-types.ts`).
|
|
1605
|
+
* Field names match the connector's `validateSolanaClaim` exactly:
|
|
1606
|
+
* `channelAccount` (base58 PDA), `signerPublicKey` (base58), base64 `signature`.
|
|
881
1607
|
*/
|
|
882
|
-
interface
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
/**
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
/**
|
|
896
|
-
|
|
897
|
-
/**
|
|
898
|
-
|
|
899
|
-
/** Custom WebSocket constructor (for testing / custom transports). */
|
|
900
|
-
createWebSocket?: (url: string) => WebSocket;
|
|
1608
|
+
interface SolanaClaimMessage {
|
|
1609
|
+
version: '1.0';
|
|
1610
|
+
blockchain: 'solana';
|
|
1611
|
+
messageId: string;
|
|
1612
|
+
timestamp: string;
|
|
1613
|
+
senderId: string;
|
|
1614
|
+
/** On-chain PDA account address for the payment channel (base58). */
|
|
1615
|
+
channelAccount: string;
|
|
1616
|
+
nonce: number;
|
|
1617
|
+
/** Cumulative transferred amount (string for bigint precision). */
|
|
1618
|
+
transferredAmount: string;
|
|
1619
|
+
/** Ed25519 signature over the 48-byte balance-proof message (base64). */
|
|
1620
|
+
signature: string;
|
|
1621
|
+
/** Base58-encoded Ed25519 public key of the signer. */
|
|
1622
|
+
signerPublicKey: string;
|
|
1623
|
+
/** Solana program id for the payment-channel program (base58). */
|
|
1624
|
+
programId: string;
|
|
901
1625
|
}
|
|
902
1626
|
/**
|
|
903
|
-
*
|
|
904
|
-
*
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
/**
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
/**
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
* path, unchanged. With a non-zero condition the FULFILL preimage is
|
|
931
|
-
* verified (`sha256(fulfillment) == condition`) and a mismatch is surfaced
|
|
932
|
-
* as a failed result — see `mapIlpResponse`.
|
|
933
|
-
*/
|
|
934
|
-
sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult>;
|
|
1627
|
+
* Mina payment-channel claim — wire-compatible with the connector's
|
|
1628
|
+
* `MinaClaimMessage` (`@toon-protocol/connector` `btp/btp-claim-types.ts`).
|
|
1629
|
+
* Field names + types match `validateMinaClaim` exactly: `zkAppAddress`
|
|
1630
|
+
* (B62-prefixed 55-char base58, the channel id), `tokenId`, `balanceCommitment`
|
|
1631
|
+
* (`Poseidon([balA,balB,salt])` decimal string), integer `nonce`, base64 `proof`,
|
|
1632
|
+
* and `salt`. `transferredAmount`/`balanceB`/`signatureB`/`network` are OPTIONAL
|
|
1633
|
+
* at validation; the apex-as-recipient single-direction claim sends party-A only.
|
|
1634
|
+
*/
|
|
1635
|
+
interface MinaClaimMessage {
|
|
1636
|
+
version: '1.0';
|
|
1637
|
+
blockchain: 'mina';
|
|
1638
|
+
messageId: string;
|
|
1639
|
+
timestamp: string;
|
|
1640
|
+
senderId: string;
|
|
1641
|
+
/** Deployed payment-channel zkApp address (B62 base58) — the channel id. */
|
|
1642
|
+
zkAppAddress: string;
|
|
1643
|
+
/** Mina token id (default `'MINA'`). */
|
|
1644
|
+
tokenId: string;
|
|
1645
|
+
/** `Poseidon([balanceA, balanceB, salt]).toString()`. */
|
|
1646
|
+
balanceCommitment: string;
|
|
1647
|
+
nonce: number;
|
|
1648
|
+
/** base64-encoded JSON `{ commitment, signature: { r, s }, nonce, signerPublicKey }`. */
|
|
1649
|
+
proof: string;
|
|
1650
|
+
/** Commitment salt (decimal string). */
|
|
1651
|
+
salt: string;
|
|
1652
|
+
/** Cumulative transferred amount (optional; string for bigint precision). */
|
|
1653
|
+
transferredAmount?: string;
|
|
935
1654
|
/**
|
|
936
|
-
*
|
|
937
|
-
* Auto-reconnects on connection errors.
|
|
1655
|
+
* Signer's Mina public key (B62 base58) — the claiming participant.
|
|
938
1656
|
*
|
|
939
|
-
*
|
|
940
|
-
*
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
*
|
|
945
|
-
*
|
|
946
|
-
* to register cumulative claim state independently of the per-packet
|
|
947
|
-
* forwarding path. Auto-reconnects on connection errors.
|
|
948
|
-
*/
|
|
949
|
-
sendClaimMessage(claim: Record<string, unknown>): Promise<void>;
|
|
950
|
-
private _sendClaimMessageOnce;
|
|
951
|
-
/**
|
|
952
|
-
* Build the ILP PREPARE for a send, applying the sender-chosen condition /
|
|
953
|
-
* explicit expiry when provided (toon-client#350) and validating that a
|
|
954
|
-
* non-zero condition is exactly 32 bytes (the OER serializer would
|
|
955
|
-
* otherwise silently zero-fill it, downgrading the packet to the legacy
|
|
956
|
-
* unverified class).
|
|
957
|
-
*/
|
|
958
|
-
private buildPrepare;
|
|
959
|
-
/**
|
|
960
|
-
* Single-attempt ILP packet send. Reconnects if not connected.
|
|
961
|
-
*/
|
|
962
|
-
private _sendIlpPacketOnce;
|
|
963
|
-
/**
|
|
964
|
-
* Single-attempt claim + ILP packet send. Reconnects if not connected.
|
|
1657
|
+
* Surfaced top-level (in addition to being embedded in `proof`) so the
|
|
1658
|
+
* connector's `SettlementExecutor` can resolve participant keys for the
|
|
1659
|
+
* on-chain `claimFromChannel` on an externally-opened (inbound) channel. The
|
|
1660
|
+
* connector reads `latestClaim.signerPublicKey` directly (not the proof blob);
|
|
1661
|
+
* without it the Mina SDK's `claimFromChannel` throws `ACCOUNT_NOT_FOUND`
|
|
1662
|
+
* ("Participant keys not found in cache and none were supplied"). The
|
|
1663
|
+
* connector accepts this as an optional `MinaClaimMessage` field.
|
|
965
1664
|
*/
|
|
966
|
-
|
|
1665
|
+
signerPublicKey?: string;
|
|
1666
|
+
/** Mina network id — defaults to `devnet` connector-side when omitted. */
|
|
1667
|
+
network?: 'mainnet' | 'devnet' | 'berkeley' | 'lightnet';
|
|
967
1668
|
}
|
|
968
1669
|
|
|
969
1670
|
/**
|
|
970
|
-
*
|
|
971
|
-
*
|
|
972
|
-
* The connector now serves ILP-over-HTTP on the SAME port as BTP (connector
|
|
973
|
-
* PR #181). This adapter lets a client do stateless one-shot writes over HTTP
|
|
974
|
-
* (`POST /ilp`) and upgrade to a duplex BTP session when it needs to receive
|
|
975
|
-
* server-initiated packets or act as a peer.
|
|
976
|
-
*
|
|
977
|
-
* Wire contract (targets connector PR #181's `/ilp`):
|
|
978
|
-
* - One-shot write: `POST /ilp`
|
|
979
|
-
* body: OER-encoded ILP PREPARE (`application/octet-stream`)
|
|
980
|
-
* header: `ILP-Payment-Channel-Claim: base64(JSON of the claim)` — the
|
|
981
|
-
* SAME claim JSON the BTP path attaches as the
|
|
982
|
-
* `payment-channel-claim` protocolData entry.
|
|
983
|
-
* optional: `ILP-Peer-Id` + `Authorization: Bearer <secret>` identity.
|
|
984
|
-
* response: `200 OK` with an OER FULFILL or REJECT body. HTTP non-2xx is
|
|
985
|
-
* reserved for TRANSPORT errors (400/401/413/5xx); ILP-level
|
|
986
|
-
* rejects come back as a 200 + REJECT body.
|
|
987
|
-
* - Upgrade to BTP: standard HTTP `Upgrade` with `Sec-WebSocket-Protocol: btp`
|
|
988
|
-
* plus the same `ILP-Peer-Id` + `Authorization` headers. The connector
|
|
989
|
-
* pre-authenticates the BTP session from those headers (continuity), so
|
|
990
|
-
* after `101` we send BTP frames WITHOUT a separate in-band auth frame.
|
|
991
|
-
* Omitting the auth headers falls back to the normal BTP auth-frame flow.
|
|
1671
|
+
* EVM claim message for BTP protocol data.
|
|
1672
|
+
* Matches @toon-protocol/connector's EVMClaimMessage interface.
|
|
992
1673
|
*
|
|
993
|
-
*
|
|
994
|
-
*
|
|
995
|
-
*
|
|
1674
|
+
* The connector's validateClaimMessage() requires envelope fields
|
|
1675
|
+
* (version, messageId, timestamp) plus EVM claim fields, and optionally
|
|
1676
|
+
* chainId + tokenNetworkAddress for self-describing signature verification.
|
|
996
1677
|
*/
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
maxRetries?: number;
|
|
1017
|
-
/** Initial retry delay in milliseconds (default: 1000). */
|
|
1018
|
-
retryDelay?: number;
|
|
1019
|
-
/** Custom fetch implementation (for testing / custom transports). */
|
|
1020
|
-
httpClient?: typeof fetch;
|
|
1021
|
-
/**
|
|
1022
|
-
* Custom WebSocket constructor for the BTP upgrade path (for testing /
|
|
1023
|
-
* custom transports). Forwarded to the underlying BtpRuntimeClient.
|
|
1024
|
-
*/
|
|
1025
|
-
createWebSocket?: (url: string) => WebSocket;
|
|
1678
|
+
interface EVMClaimMessage {
|
|
1679
|
+
version: '1.0';
|
|
1680
|
+
blockchain: 'evm';
|
|
1681
|
+
messageId: string;
|
|
1682
|
+
timestamp: string;
|
|
1683
|
+
senderId: string;
|
|
1684
|
+
channelId: string;
|
|
1685
|
+
nonce: number;
|
|
1686
|
+
transferredAmount: string;
|
|
1687
|
+
lockedAmount: string;
|
|
1688
|
+
locksRoot: string;
|
|
1689
|
+
signature: string;
|
|
1690
|
+
signerAddress: string;
|
|
1691
|
+
/** Chain ID for self-describing EIP-712 verification */
|
|
1692
|
+
chainId: number;
|
|
1693
|
+
/** TokenNetwork address for self-describing EIP-712 verification */
|
|
1694
|
+
tokenNetworkAddress: string;
|
|
1695
|
+
/** ERC-20 token address for self-describing claim verification */
|
|
1696
|
+
tokenAddress?: string;
|
|
1026
1697
|
}
|
|
1027
1698
|
/**
|
|
1028
|
-
*
|
|
1699
|
+
* EVM signer for EIP-712 balance proofs and on-chain transactions.
|
|
1029
1700
|
*
|
|
1030
|
-
*
|
|
1031
|
-
* client needs a duplex session — to receive server-initiated packets or to act
|
|
1032
|
-
* as a peer — call {@link upgradeToBtp} to obtain a connected BtpRuntimeClient
|
|
1033
|
-
* that reuses the existing BTP code path.
|
|
1701
|
+
* Encapsulates the private key — no getPrivateKey() method is exposed.
|
|
1034
1702
|
*/
|
|
1035
|
-
declare class
|
|
1036
|
-
|
|
1037
|
-
private readonly
|
|
1038
|
-
private readonly authToken;
|
|
1039
|
-
private readonly timeout;
|
|
1040
|
-
private readonly retryConfig;
|
|
1041
|
-
private readonly httpClient;
|
|
1042
|
-
private readonly createWebSocket;
|
|
1043
|
-
constructor(config: HttpIlpClientConfig);
|
|
1044
|
-
/**
|
|
1045
|
-
* The client edge this transport pays — the origin `GET /ilp/identity` and
|
|
1046
|
-
* `GET /ilp/routes/price` hang off (`ConnectorEdgeClient` normalizes the
|
|
1047
|
-
* trailing `/ilp` away). Exposed because a sealed write must ask the
|
|
1048
|
-
* connector it is ACTUALLY paying for its key, not a configured guess.
|
|
1049
|
-
*/
|
|
1050
|
-
get clientEdgeEndpoint(): string;
|
|
1703
|
+
declare class EvmSigner {
|
|
1704
|
+
readonly chainType: "evm";
|
|
1705
|
+
private readonly _account;
|
|
1051
1706
|
/**
|
|
1052
|
-
*
|
|
1053
|
-
* this only on free/zero-amount routes; paid writes must use
|
|
1054
|
-
* {@link sendIlpPacketWithClaim}. Satisfies the IlpClient interface.
|
|
1055
|
-
*
|
|
1056
|
-
* `params` may carry a sender-chosen `executionCondition` and an explicit
|
|
1057
|
-
* `expiresAt` (toon-client#350); omitting both is the legacy zero-condition
|
|
1058
|
-
* path, unchanged. With a non-zero condition the FULFILL preimage is
|
|
1059
|
-
* verified (`sha256(fulfillment) == condition`) and a mismatch is surfaced
|
|
1060
|
-
* as a failed result — see {@link mapIlpResponse}.
|
|
1707
|
+
* @param privateKey - EVM private key as hex string (with or without 0x prefix) or Uint8Array
|
|
1061
1708
|
*/
|
|
1062
|
-
|
|
1709
|
+
constructor(privateKey: string | Uint8Array);
|
|
1710
|
+
/** Derived 0x EVM address */
|
|
1711
|
+
get address(): string;
|
|
1712
|
+
/** ChainSigner identifier — EVM address */
|
|
1713
|
+
get signerIdentifier(): string;
|
|
1714
|
+
/** Viem PrivateKeyAccount — usable with walletClient for on-chain transactions */
|
|
1715
|
+
get account(): PrivateKeyAccount;
|
|
1063
1716
|
/**
|
|
1064
|
-
*
|
|
1065
|
-
* as the `ILP-Payment-Channel-Claim` header. `claim` is the SAME JSON object
|
|
1066
|
-
* the BTP path attaches as the `payment-channel-claim` protocolData entry —
|
|
1067
|
-
* we base64(JSON.stringify(claim)) it, byte-for-byte identical to BTP.
|
|
1717
|
+
* Signs a balance proof using EIP-712 typed data.
|
|
1068
1718
|
*
|
|
1069
|
-
*
|
|
1070
|
-
*
|
|
1719
|
+
* @param params - Balance proof parameters plus chain context
|
|
1720
|
+
* @returns Signed balance proof with signature
|
|
1071
1721
|
*/
|
|
1072
|
-
|
|
1722
|
+
signBalanceProof(params: BalanceProofParams & {
|
|
1723
|
+
chainId: number;
|
|
1724
|
+
tokenNetworkAddress: string;
|
|
1725
|
+
tokenAddress?: string;
|
|
1726
|
+
}): Promise<SignedBalanceProof>;
|
|
1073
1727
|
/**
|
|
1074
|
-
*
|
|
1075
|
-
*
|
|
1076
|
-
*
|
|
1077
|
-
*
|
|
1078
|
-
*
|
|
1079
|
-
* are present the connector pre-authenticates the session (no in-band auth
|
|
1080
|
-
* frame); without them the BtpRuntimeClient falls back to the normal BTP
|
|
1081
|
-
* auth-frame flow.
|
|
1728
|
+
* Signs a `POST /ilp/claim-state` claim-state challenge (client-edge-spec.md
|
|
1729
|
+
* §1.10): proves ownership of `channelId` without moving any value or
|
|
1730
|
+
* advancing the channel's nonce — this is a READ, not a claim. Read the
|
|
1731
|
+
* connector's answer for the actual credited/available balance (toon-meta#262
|
|
1732
|
+
* decision 9); this signature only unlocks the read.
|
|
1082
1733
|
*
|
|
1083
|
-
*
|
|
1084
|
-
*
|
|
1085
|
-
*
|
|
1086
|
-
* transport or BTP-with-auth-frame instead.
|
|
1087
|
-
*/
|
|
1088
|
-
upgradeToBtp(): Promise<BtpRuntimeClient>;
|
|
1089
|
-
private authHeaders;
|
|
1090
|
-
/**
|
|
1091
|
-
* Single attempt: serialize the PREPARE, POST it, and map the response.
|
|
1092
|
-
* @throws {NetworkError} On connection/timeout failures (retried).
|
|
1093
|
-
* @throws {ConnectorError} On non-retryable transport errors (5xx / unexpected).
|
|
1734
|
+
* @param params.expires - Unix seconds the signature stops verifying.
|
|
1735
|
+
* Reissue with a fresh value whenever an outstanding one should stop
|
|
1736
|
+
* being trusted — the endpoint has no other replay bound.
|
|
1094
1737
|
*/
|
|
1095
|
-
|
|
1738
|
+
signClaimStateChallenge(params: {
|
|
1739
|
+
chainId: number;
|
|
1740
|
+
tokenNetworkAddress: string;
|
|
1741
|
+
channelId: string;
|
|
1742
|
+
expires: number;
|
|
1743
|
+
}): Promise<string>;
|
|
1096
1744
|
/**
|
|
1097
|
-
*
|
|
1098
|
-
*
|
|
1099
|
-
*
|
|
1100
|
-
*
|
|
1101
|
-
*
|
|
1102
|
-
*
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
private mapResponse;
|
|
1106
|
-
private mapTransportError;
|
|
1107
|
-
}
|
|
1108
|
-
/**
|
|
1109
|
-
* Derive the BTP WebSocket URL from a `POST /ilp` HTTP endpoint. The connector
|
|
1110
|
-
* serves BTP on the SAME path, so we only swap the scheme (http→ws, https→wss).
|
|
1111
|
-
*/
|
|
1112
|
-
declare function httpEndpointToBtpUrl(httpEndpoint: string): string;
|
|
1113
|
-
|
|
1114
|
-
/**
|
|
1115
|
-
* Base error class for all TOON client errors.
|
|
1116
|
-
*/
|
|
1117
|
-
declare class ToonClientError extends Error {
|
|
1118
|
-
readonly code: string;
|
|
1119
|
-
constructor(message: string, code: string, cause?: Error);
|
|
1120
|
-
}
|
|
1121
|
-
/**
|
|
1122
|
-
* Network error for connection failures (ECONNREFUSED, ETIMEDOUT).
|
|
1123
|
-
* These errors trigger retry logic with exponential backoff.
|
|
1124
|
-
*/
|
|
1125
|
-
declare class NetworkError extends ToonClientError {
|
|
1126
|
-
constructor(message: string, cause?: Error);
|
|
1745
|
+
* Builds an EVMClaimMessage from a signed balance proof.
|
|
1746
|
+
* Static so it can be called without an EvmSigner instance.
|
|
1747
|
+
*
|
|
1748
|
+
* @param proof - Signed balance proof (includes chainId and tokenNetworkAddress)
|
|
1749
|
+
* @param senderId - Nostr pubkey or identifier of the sender
|
|
1750
|
+
* @returns EVMClaimMessage compatible with BTP_CLAIM_PROTOCOL
|
|
1751
|
+
*/
|
|
1752
|
+
static buildClaimMessage(proof: SignedBalanceProof, senderId: string): EVMClaimMessage;
|
|
1127
1753
|
}
|
|
1754
|
+
|
|
1128
1755
|
/**
|
|
1129
|
-
*
|
|
1130
|
-
*
|
|
1756
|
+
* Plain token transfer — send the settlement token or native gas from the
|
|
1757
|
+
* caller's own configured key to an ARBITRARY address, on any chain this
|
|
1758
|
+
* client already supports (evm/solana/mina). This is the missing primitive
|
|
1759
|
+
* underneath provisioning a buzz agent (toon-protocol/buzz#74): before a
|
|
1760
|
+
* derived agent address can open a payment channel, the owner's treasury has
|
|
1761
|
+
* to send it USDC and native gas.
|
|
1762
|
+
*
|
|
1763
|
+
* `@toon-protocol/client` was built around payment CHANNELS, not transfers —
|
|
1764
|
+
* `faucet.ts` is the only prior funding path, and it only reaches the devnet
|
|
1765
|
+
* faucet. This module is a direct, non-custodial send: the caller's own key
|
|
1766
|
+
* signs its own transaction/payment, straight to `to`.
|
|
1767
|
+
*
|
|
1768
|
+
* Every send is confirmed by an OBSERVED balance delta at the destination,
|
|
1769
|
+
* never by the send call/transaction merely landing. The devnet faucet's
|
|
1770
|
+
* Solana leg has been seen returning success with a REAL transaction
|
|
1771
|
+
* signature while delivering 0 lamports (toon-protocol/connector#691) — a
|
|
1772
|
+
* send that trusted its own receipt would report a funded agent that in fact
|
|
1773
|
+
* holds nothing. {@link TransferNotDeliveredError} is exactly that failure
|
|
1774
|
+
* mode, made loud instead of silent.
|
|
1131
1775
|
*/
|
|
1132
|
-
|
|
1133
|
-
|
|
1776
|
+
|
|
1777
|
+
/** Chains this client can send a plain transfer on. */
|
|
1778
|
+
type TransferChain = 'evm' | 'solana' | 'mina';
|
|
1779
|
+
/** `'native'` — the chain's own gas token. `'token'` — the settlement token. */
|
|
1780
|
+
type TransferAssetKind = 'native' | 'token';
|
|
1781
|
+
interface SendTransferParams {
|
|
1782
|
+
chain: TransferChain;
|
|
1783
|
+
asset: TransferAssetKind;
|
|
1784
|
+
/** Destination address, in the target chain's native format. */
|
|
1785
|
+
to: string;
|
|
1786
|
+
/** Amount to send, in the asset's base units (wei / lamports+SPL / nanomina). */
|
|
1787
|
+
amount: string | bigint;
|
|
1788
|
+
/**
|
|
1789
|
+
* How long to wait for the destination's observed balance to reflect the
|
|
1790
|
+
* transfer before giving up with {@link TransferNotDeliveredError}. Defaults
|
|
1791
|
+
* are chain-specific (EVM/Solana 30s, Mina 5 min — Mina block inclusion is
|
|
1792
|
+
* materially slower).
|
|
1793
|
+
*/
|
|
1794
|
+
confirmTimeoutMs?: number;
|
|
1795
|
+
/** Poll interval (ms) while waiting for the balance delta. Default 2000. */
|
|
1796
|
+
confirmPollIntervalMs?: number;
|
|
1797
|
+
}
|
|
1798
|
+
interface SendTransferResult {
|
|
1799
|
+
chain: TransferChain;
|
|
1800
|
+
asset: TransferAssetKind;
|
|
1801
|
+
to: string;
|
|
1802
|
+
/** Base units actually requested (echoed back as a decimal string). */
|
|
1803
|
+
amount: string;
|
|
1804
|
+
/** Transaction hash / signature of the send. */
|
|
1805
|
+
txHash: string;
|
|
1806
|
+
/** Destination's observed balance immediately before the send. */
|
|
1807
|
+
balanceBefore: string;
|
|
1808
|
+
/** Destination's observed balance once the delta was confirmed. */
|
|
1809
|
+
balanceAfter: string;
|
|
1810
|
+
}
|
|
1811
|
+
/** Per-chain config a caller supplies to {@link sendTransfer}. */
|
|
1812
|
+
interface EvmTransferConfig {
|
|
1813
|
+
/** Chain key, e.g. `'evm:base-sepolia:84532'` (used for chainId + RPC). */
|
|
1814
|
+
chainKey: string;
|
|
1815
|
+
rpcUrl: string;
|
|
1816
|
+
signer: EvmSigner;
|
|
1817
|
+
/** ERC-20 settlement-token address. Required only for `asset: 'token'`. */
|
|
1818
|
+
tokenAddress?: string;
|
|
1134
1819
|
}
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1820
|
+
interface SolanaTransferConfig {
|
|
1821
|
+
rpcUrl: string;
|
|
1822
|
+
/** Ed25519 signing seed (32 bytes) or a 64-byte seed||pubkey keypair. */
|
|
1823
|
+
keypair: Uint8Array;
|
|
1824
|
+
/** SPL settlement-token mint. Required only for `asset: 'token'`. */
|
|
1825
|
+
tokenMint?: string;
|
|
1141
1826
|
}
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
declare class ChannelFundingError extends ToonClientError {
|
|
1153
|
-
readonly retryable = true;
|
|
1154
|
-
constructor(message: string, cause?: Error);
|
|
1827
|
+
interface MinaTransferConfig {
|
|
1828
|
+
graphqlUrl: string;
|
|
1829
|
+
/** Big-endian hex scalar (as `deriveFullIdentity` emits) or `EK…` base58. */
|
|
1830
|
+
privateKey: string;
|
|
1831
|
+
/** Mina network id for the signature domain separator. Default `'devnet'`. */
|
|
1832
|
+
networkId?: 'devnet' | 'mainnet';
|
|
1833
|
+
/** Transaction fee, nanomina. Default 1_000_000 (0.001 MINA). */
|
|
1834
|
+
fee?: string;
|
|
1835
|
+
/** Injectable fetch (tests). */
|
|
1836
|
+
fetchImpl?: typeof fetch;
|
|
1155
1837
|
}
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1838
|
+
interface TransferConfig {
|
|
1839
|
+
evm?: EvmTransferConfig;
|
|
1840
|
+
solana?: SolanaTransferConfig;
|
|
1841
|
+
mina?: MinaTransferConfig;
|
|
1842
|
+
}
|
|
1843
|
+
/**
|
|
1844
|
+
* Send `params.amount` base units of `params.asset` to `params.to` on
|
|
1845
|
+
* `params.chain`, using whichever chain config in `config` matches. Confirms
|
|
1846
|
+
* delivery by re-reading the destination's balance (see module docs) rather
|
|
1847
|
+
* than trusting the send call's own success signal.
|
|
1848
|
+
*
|
|
1849
|
+
* @throws {UnknownChainError} `params.chain` is unrecognized, or this client
|
|
1850
|
+
* has no configuration for it.
|
|
1851
|
+
* @throws {InvalidAddressError} `params.to` is malformed for the chain.
|
|
1852
|
+
* @throws {InsufficientBalanceError} the sender cannot cover the amount
|
|
1853
|
+
* (plus fees, where applicable) — checked before anything is submitted.
|
|
1854
|
+
* @throws {TransferNotDeliveredError} the send was accepted (a landed,
|
|
1855
|
+
* non-reverted transaction / a node-accepted payment) but the destination
|
|
1856
|
+
* balance never reflected it within the wait window.
|
|
1857
|
+
* @throws {TransferUnsupportedError} this chain/asset combination isn't
|
|
1858
|
+
* implemented yet (currently: the Mina settlement token).
|
|
1859
|
+
*/
|
|
1860
|
+
declare function sendTransfer(config: TransferConfig, params: SendTransferParams): Promise<SendTransferResult>;
|
|
1162
1861
|
|
|
1163
1862
|
/**
|
|
1164
|
-
*
|
|
1165
|
-
*
|
|
1166
|
-
*
|
|
1167
|
-
* ADR 0018 makes holding the terminating connector's public key a
|
|
1168
|
-
* precondition of forming a packet: `Prepare.data` is sealed to that key, and
|
|
1169
|
-
* sealing to the wrong one is a confidentiality failure, not a delivery
|
|
1170
|
-
* failure. ADR 0022 says the connector *answers* — it never announces — so
|
|
1171
|
-
* both facts are fetched from the connector's own client edge, on the same
|
|
1172
|
-
* origin this client already POSTs `/ilp` to
|
|
1173
|
-
* (`docs/protocol/client-edge-spec.md` §1.7):
|
|
1174
|
-
*
|
|
1175
|
-
* - `GET /ilp/identity` → `{ "keyId": "...", "publicKey": "0x04..." }` — the
|
|
1176
|
-
* uncompressed secp256k1 key, 65 bytes, `0x`-prefixed hex.
|
|
1177
|
-
* - `GET /ilp/routes/price?destination=<ILP address>` →
|
|
1178
|
-
* `{ "destination": "...", "price": 100 }`, or `404` when no
|
|
1179
|
-
* locally-terminated route matches.
|
|
1180
|
-
*
|
|
1181
|
-
* Both are unauthenticated and neither changes state.
|
|
1863
|
+
* Shared sender-side plumbing for sender-chosen execution conditions
|
|
1864
|
+
* (toon-client#350; contract: connector `docs/local-delivery-fulfillment-contract.md`,
|
|
1865
|
+
* connector#309; spec: toon-meta `docs/rolling-swap.md` §3).
|
|
1182
1866
|
*
|
|
1183
|
-
*
|
|
1184
|
-
*
|
|
1185
|
-
*
|
|
1186
|
-
* parsed STRICTLY. A key that is the wrong length, not `0x04`-prefixed, or not
|
|
1187
|
-
* valid hex is refused with a distinguishable error rather than carried
|
|
1188
|
-
* forward: a half-understood key would be sealed to, and the failure would be
|
|
1189
|
-
* silent. There is no "best effort" reading of a public key.
|
|
1867
|
+
* Both ILP transports (HTTP `POST /ilp` and BTP) take the SAME extended send
|
|
1868
|
+
* params and map FULFILL/REJECT responses through the SAME verifier so the
|
|
1869
|
+
* two paths cannot drift:
|
|
1190
1870
|
*
|
|
1191
|
-
*
|
|
1192
|
-
*
|
|
1871
|
+
* - absent/all-zero `executionCondition` → legacy class: today's behavior,
|
|
1872
|
+
* byte-for-byte (zero condition on the wire, no FULFILL verification);
|
|
1873
|
+
* - non-zero `executionCondition` → sender-chosen: the condition goes on
|
|
1874
|
+
* the PREPARE verbatim and the FULFILL's 32-byte fulfillment MUST hash
|
|
1875
|
+
* back to it — a missing/malformed/mismatching preimage is surfaced as a
|
|
1876
|
+
* FAILED result (never a silent accept, never retried).
|
|
1193
1877
|
*/
|
|
1194
1878
|
|
|
1195
|
-
/** The terminating connector's own identity, as reported by `GET /ilp/identity`. */
|
|
1196
|
-
interface ConnectorIdentity {
|
|
1197
|
-
/** The key id identifying the key (opaque to this client). */
|
|
1198
|
-
keyId: string;
|
|
1199
|
-
/** The uncompressed secp256k1 public key — exactly 65 raw bytes, leading `0x04`. */
|
|
1200
|
-
publicKey: Uint8Array;
|
|
1201
|
-
/** The key exactly as reported, `0x`-prefixed lowercase hex (65 bytes → 132 chars). */
|
|
1202
|
-
publicKeyHex: string;
|
|
1203
|
-
/** The normalized client-edge base URL this identity was read from. */
|
|
1204
|
-
endpoint: string;
|
|
1205
|
-
}
|
|
1206
|
-
/**
|
|
1207
|
-
* The channel-opening facts a settling connector carries in its x402
|
|
1208
|
-
* greeting (connector #617): everything a buyer needs to OPEN a channel
|
|
1209
|
-
* with the node, learned by ASKING (ADR 0022) rather than from a
|
|
1210
|
-
* kind:10032 announce the Rust fleet never makes.
|
|
1211
|
-
*/
|
|
1212
|
-
interface ConnectorSettlementTerms {
|
|
1213
|
-
/** `evm:<chainId>` — the chain the node's settlement backend runs on. */
|
|
1214
|
-
chain: string;
|
|
1215
|
-
/** The on-chain counterparty a buyer opens a channel WITH. */
|
|
1216
|
-
settlementAddress: string;
|
|
1217
|
-
/** The stable TokenNetworkRegistry factory address. */
|
|
1218
|
-
tokenNetworkRegistry: string;
|
|
1219
|
-
/** The resolved TokenNetwork — the EIP-712 verifyingContract. */
|
|
1220
|
-
tokenNetwork: string;
|
|
1221
|
-
tokenAddress: string;
|
|
1222
|
-
/** Informational; claims are already in base units. */
|
|
1223
|
-
decimals: number;
|
|
1224
|
-
}
|
|
1225
1879
|
/**
|
|
1226
|
-
*
|
|
1227
|
-
*
|
|
1228
|
-
*
|
|
1880
|
+
* Send parameters accepted by both ILP transports. Extends the
|
|
1881
|
+
* `@toon-protocol/core` `IlpClient` param shape with the sender-chosen
|
|
1882
|
+
* condition and an explicit expiry — plain `IlpClient` callers keep working
|
|
1883
|
+
* unchanged (both extras are optional; omitting them is the legacy path).
|
|
1229
1884
|
*/
|
|
1230
|
-
interface
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
/**
|
|
1234
|
-
|
|
1235
|
-
/**
|
|
1236
|
-
|
|
1237
|
-
/**
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1885
|
+
interface IlpSendParams {
|
|
1886
|
+
destination: string;
|
|
1887
|
+
amount: string;
|
|
1888
|
+
/** Base64 ILP `data` payload. */
|
|
1889
|
+
data: string;
|
|
1890
|
+
/** Transport timeout in ms; also the default expiry window. */
|
|
1891
|
+
timeout?: number;
|
|
1892
|
+
/**
|
|
1893
|
+
* Sender-chosen 32-byte execution condition `C = sha256(P)` (spec R2).
|
|
1894
|
+
* Absent or all-zero = legacy unverified packet (default — ordinary
|
|
1895
|
+
* publish/upload writes MUST keep this default).
|
|
1896
|
+
*/
|
|
1897
|
+
executionCondition?: Uint8Array;
|
|
1898
|
+
/**
|
|
1899
|
+
* Explicit PREPARE `expiresAt` (spec R7). Defaults to `now + timeout`,
|
|
1900
|
+
* preserving pre-#350 behavior. Accepts a `Date` or an ISO 8601 string —
|
|
1901
|
+
* `@toon-protocol/core` ≥2.1.0's `IlpClient` passes the string form.
|
|
1902
|
+
*/
|
|
1903
|
+
expiresAt?: Date | string;
|
|
1241
1904
|
}
|
|
1242
1905
|
/**
|
|
1243
|
-
*
|
|
1244
|
-
*
|
|
1245
|
-
*
|
|
1246
|
-
* names EVM, `programId` names Solana).
|
|
1247
|
-
*/
|
|
1248
|
-
type ConnectorChainSettlementTerms = ({
|
|
1249
|
-
kind: 'evm';
|
|
1250
|
-
} & ConnectorSettlementTerms) | ({
|
|
1251
|
-
kind: 'solana';
|
|
1252
|
-
} & ConnectorSolanaSettlementTerms);
|
|
1253
|
-
/**
|
|
1254
|
-
* A route's terms as the x402 greeting states them: the price, plus (from a
|
|
1255
|
-
* settling node) the channel-opening facts. `settlement` is absent exactly
|
|
1256
|
-
* when the node has no settlement backend — the wire's own shape. `settlements`
|
|
1257
|
-
* is the additive per-chain list (connector #632): one entry per chain the
|
|
1258
|
-
* node settles on, including the same EVM entry `settlement` already carries.
|
|
1259
|
-
* Absent — not an empty array — on a node with no settlement backend, or one
|
|
1260
|
-
* still answering the pre-#632 greeting shape.
|
|
1906
|
+
* `IlpSendResult` plus the FULFILL preimage when a sender-chosen condition
|
|
1907
|
+
* was verified. Only populated on the sender-chosen path so legacy result
|
|
1908
|
+
* objects stay byte-identical.
|
|
1261
1909
|
*/
|
|
1262
|
-
interface
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
settlement?: ConnectorSettlementTerms;
|
|
1266
|
-
settlements?: ConnectorChainSettlementTerms[];
|
|
1910
|
+
interface IlpSendResultWithFulfillment extends IlpSendResult {
|
|
1911
|
+
/** Base64 32-byte fulfillment preimage (verified: sha256 == condition). */
|
|
1912
|
+
fulfillment?: string;
|
|
1267
1913
|
}
|
|
1268
|
-
/**
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1914
|
+
/** ILP code used for a client-side fulfillment-verification failure. */
|
|
1915
|
+
declare const FULFILLMENT_MISMATCH_CODE = "F99";
|
|
1916
|
+
/** Message for a client-side fulfillment-verification failure. */
|
|
1917
|
+
declare const FULFILLMENT_MISMATCH_MESSAGE: string;
|
|
1918
|
+
|
|
1919
|
+
interface BtpRuntimeClientConfig {
|
|
1920
|
+
btpUrl: string;
|
|
1921
|
+
peerId: string;
|
|
1922
|
+
authToken: string;
|
|
1923
|
+
/** Max reconnection attempts on send failure (default: 3) */
|
|
1924
|
+
maxRetries?: number;
|
|
1925
|
+
/** Delay between reconnection attempts in ms (default: 1000) */
|
|
1926
|
+
retryDelay?: number;
|
|
1927
|
+
/** Custom WebSocket constructor (for testing / custom transports). */
|
|
1928
|
+
createWebSocket?: (url: string) => WebSocket;
|
|
1929
|
+
/**
|
|
1930
|
+
* Handles a server-originated MESSAGE (RFC-0023 symmetric grammar,
|
|
1931
|
+
* toon-client#493). Re-registered on every `connect()`/`reconnect()` since
|
|
1932
|
+
* each creates a fresh `IsomorphicBtpClient` for the new socket.
|
|
1933
|
+
*/
|
|
1934
|
+
onMessage?: BtpMessageHandler;
|
|
1935
|
+
/** Handles a server-originated TRANSFER. Re-registered the same way as `onMessage`. */
|
|
1936
|
+
onTransfer?: BtpTransferHandler;
|
|
1937
|
+
/** Surfaces in-flight inbound work orphaned by a disconnect instead of silently vanishing. */
|
|
1938
|
+
onInboundError?: (error: Error, requestId: number) => void;
|
|
1274
1939
|
}
|
|
1275
1940
|
/**
|
|
1276
|
-
*
|
|
1277
|
-
*
|
|
1278
|
-
* caller's next move differs per cause (retry a transport failure; never
|
|
1279
|
-
* retry a malformed key).
|
|
1280
|
-
*/
|
|
1281
|
-
type ConnectorEdgeErrorCode =
|
|
1282
|
-
/** Non-2xx from `GET /ilp/identity`. */
|
|
1283
|
-
'IDENTITY_HTTP_STATUS'
|
|
1284
|
-
/** `GET /ilp/identity` answered 2xx with a body that is not the documented object. */
|
|
1285
|
-
| 'IDENTITY_MALFORMED'
|
|
1286
|
-
/** `publicKey` is present but is not `0x`-prefixed even-length hex. */
|
|
1287
|
-
| 'IDENTITY_KEY_NOT_HEX'
|
|
1288
|
-
/** `publicKey` decodes, but not to exactly 65 bytes. */
|
|
1289
|
-
| 'IDENTITY_KEY_LENGTH'
|
|
1290
|
-
/** `publicKey` is 65 bytes but does not start with the SEC1 uncompressed tag `0x04`. */
|
|
1291
|
-
| 'IDENTITY_KEY_NOT_UNCOMPRESSED'
|
|
1292
|
-
/** Non-2xx, non-404 from `GET /ilp/routes/price` (404 is not an error — see below). */
|
|
1293
|
-
| 'ROUTE_PRICE_HTTP_STATUS'
|
|
1294
|
-
/** `GET /ilp/routes/price` answered 2xx with a body that is not the documented object. */
|
|
1295
|
-
| 'ROUTE_PRICE_MALFORMED'
|
|
1296
|
-
/** A destination that cannot be put in a query string was asked about. */
|
|
1297
|
-
| 'INVALID_DESTINATION'
|
|
1298
|
-
/** A 402 greeting whose body is not the documented x402 shape (or whose
|
|
1299
|
-
* optional `settlement` facts are present but malformed — refused rather
|
|
1300
|
-
* than silently dropped, since they would be opened AGAINST). */
|
|
1301
|
-
| 'TERMS_MALFORMED';
|
|
1302
|
-
/**
|
|
1303
|
-
* A refusal to carry a connector's answer forward. Distinct from
|
|
1304
|
-
* {@link NetworkError} (which this module throws for a transport failure), so
|
|
1305
|
-
* "the connector is unreachable" and "the connector answered something I will
|
|
1306
|
-
* not seal to" are never confused.
|
|
1941
|
+
* BTP transport implementing IlpClient.
|
|
1942
|
+
* Uses IsomorphicBtpClient (browser-native, no Node.js dependencies).
|
|
1307
1943
|
*/
|
|
1308
|
-
declare class
|
|
1309
|
-
|
|
1310
|
-
readonly
|
|
1311
|
-
|
|
1944
|
+
declare class BtpRuntimeClient implements IlpClient {
|
|
1945
|
+
private btpClient;
|
|
1946
|
+
private readonly config;
|
|
1947
|
+
private _isConnected;
|
|
1948
|
+
constructor(config: BtpRuntimeClientConfig);
|
|
1949
|
+
/**
|
|
1950
|
+
* Connects to the BTP peer via WebSocket.
|
|
1951
|
+
*/
|
|
1952
|
+
connect(): Promise<void>;
|
|
1953
|
+
/**
|
|
1954
|
+
* Attempts to reconnect by creating a fresh client and connecting.
|
|
1955
|
+
*/
|
|
1956
|
+
reconnect(): Promise<void>;
|
|
1957
|
+
/**
|
|
1958
|
+
* Disconnects from the BTP peer.
|
|
1959
|
+
*/
|
|
1960
|
+
disconnect(): Promise<void>;
|
|
1961
|
+
get isConnected(): boolean;
|
|
1962
|
+
/**
|
|
1963
|
+
* Sends an ILP packet via BTP with auto-reconnect on connection errors.
|
|
1964
|
+
* Satisfies IlpClient interface.
|
|
1965
|
+
*
|
|
1966
|
+
* `params` may carry a sender-chosen `executionCondition` and an explicit
|
|
1967
|
+
* `expiresAt` (toon-client#350); omitting both is the legacy zero-condition
|
|
1968
|
+
* path, unchanged. With a non-zero condition the FULFILL preimage is
|
|
1969
|
+
* verified (`sha256(fulfillment) == condition`) and a mismatch is surfaced
|
|
1970
|
+
* as a failed result — see `mapIlpResponse`.
|
|
1971
|
+
*/
|
|
1972
|
+
sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult>;
|
|
1973
|
+
/**
|
|
1974
|
+
* Sends a balance proof claim via BTP protocol data, then sends an ILP packet.
|
|
1975
|
+
* Auto-reconnects on connection errors.
|
|
1976
|
+
*
|
|
1977
|
+
* Sender-chosen `executionCondition` / explicit `expiresAt` semantics are
|
|
1978
|
+
* identical to {@link sendIlpPacket}.
|
|
1979
|
+
*/
|
|
1980
|
+
sendIlpPacketWithClaim(params: IlpSendParams, claim: Record<string, unknown>): Promise<IlpSendResult>;
|
|
1981
|
+
/**
|
|
1982
|
+
* Send a standalone `payment-channel-claim` BTP MESSAGE (no ILP packet
|
|
1983
|
+
* attached). The connector's ClaimReceiver consumes this fire-and-forget
|
|
1984
|
+
* to register cumulative claim state independently of the per-packet
|
|
1985
|
+
* forwarding path. Auto-reconnects on connection errors.
|
|
1986
|
+
*/
|
|
1987
|
+
sendClaimMessage(claim: Record<string, unknown>): Promise<void>;
|
|
1988
|
+
private _sendClaimMessageOnce;
|
|
1989
|
+
/**
|
|
1990
|
+
* Build the ILP PREPARE for a send, applying the sender-chosen condition /
|
|
1991
|
+
* explicit expiry when provided (toon-client#350) and validating that a
|
|
1992
|
+
* non-zero condition is exactly 32 bytes (the OER serializer would
|
|
1993
|
+
* otherwise silently zero-fill it, downgrading the packet to the legacy
|
|
1994
|
+
* unverified class).
|
|
1995
|
+
*/
|
|
1996
|
+
private buildPrepare;
|
|
1997
|
+
/**
|
|
1998
|
+
* Single-attempt ILP packet send. Reconnects if not connected.
|
|
1999
|
+
*/
|
|
2000
|
+
private _sendIlpPacketOnce;
|
|
2001
|
+
/**
|
|
2002
|
+
* Single-attempt claim + ILP packet send. Reconnects if not connected.
|
|
2003
|
+
*/
|
|
2004
|
+
private _sendIlpPacketWithClaimOnce;
|
|
1312
2005
|
}
|
|
2006
|
+
|
|
1313
2007
|
/**
|
|
1314
|
-
*
|
|
1315
|
-
* `/ilp/*` routes hang off.
|
|
2008
|
+
* ILP-over-HTTP (RFC-0035) transport for the TOON client.
|
|
1316
2009
|
*
|
|
1317
|
-
*
|
|
1318
|
-
*
|
|
1319
|
-
* `POST /ilp`
|
|
1320
|
-
*
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
*
|
|
1325
|
-
*
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
*
|
|
1330
|
-
*
|
|
2010
|
+
* The connector now serves ILP-over-HTTP on the SAME port as BTP (connector
|
|
2011
|
+
* PR #181). This adapter lets a client do stateless one-shot writes over HTTP
|
|
2012
|
+
* (`POST /ilp`) and upgrade to a duplex BTP session when it needs to receive
|
|
2013
|
+
* server-initiated packets or act as a peer.
|
|
2014
|
+
*
|
|
2015
|
+
* Wire contract (targets connector PR #181's `/ilp`):
|
|
2016
|
+
* - One-shot write: `POST /ilp`
|
|
2017
|
+
* body: OER-encoded ILP PREPARE (`application/octet-stream`)
|
|
2018
|
+
* header: `ILP-Payment-Channel-Claim: base64(JSON of the claim)` — the
|
|
2019
|
+
* SAME claim JSON the BTP path attaches as the
|
|
2020
|
+
* `payment-channel-claim` protocolData entry.
|
|
2021
|
+
* optional: `ILP-Peer-Id` + `Authorization: Bearer <secret>` identity.
|
|
2022
|
+
* response: `200 OK` with an OER FULFILL or REJECT body. HTTP non-2xx is
|
|
2023
|
+
* reserved for TRANSPORT errors (400/401/413/5xx); ILP-level
|
|
2024
|
+
* rejects come back as a 200 + REJECT body.
|
|
2025
|
+
* - Upgrade to BTP: standard HTTP `Upgrade` with `Sec-WebSocket-Protocol: btp`
|
|
2026
|
+
* plus the same `ILP-Peer-Id` + `Authorization` headers. The connector
|
|
2027
|
+
* pre-authenticates the BTP session from those headers (continuity), so
|
|
2028
|
+
* after `101` we send BTP frames WITHOUT a separate in-band auth frame.
|
|
2029
|
+
* Omitting the auth headers falls back to the normal BTP auth-frame flow.
|
|
2030
|
+
*
|
|
2031
|
+
* Reuses `serializeIlpPrepare`/`deserializeIlpPacket` from `btp/protocol.ts` —
|
|
2032
|
+
* the SAME OER codec the BTP path uses. Claim signing/construction is owned by
|
|
2033
|
+
* the caller (BootstrapService); this transport never builds or signs claims.
|
|
1331
2034
|
*/
|
|
1332
|
-
|
|
1333
|
-
/**
|
|
1334
|
-
declare
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
/**
|
|
2035
|
+
|
|
2036
|
+
/** Header carrying the base64(JSON) payment-channel claim. */
|
|
2037
|
+
declare const ILP_CLAIM_HEADER = "ILP-Payment-Channel-Claim";
|
|
2038
|
+
/** Header carrying the peer identity. */
|
|
2039
|
+
declare const ILP_PEER_ID_HEADER = "ILP-Peer-Id";
|
|
2040
|
+
interface HttpIlpClientConfig {
|
|
2041
|
+
/** The peer's `POST /ilp` URL (the `httpEndpoint` from discovery). */
|
|
2042
|
+
httpEndpoint: string;
|
|
2043
|
+
/**
|
|
2044
|
+
* Optional peer identity. With no `peerId`/`authToken` the connector treats
|
|
2045
|
+
* the request as an anonymous no-auth peer (permissionless default) and
|
|
2046
|
+
* derives an ephemeral id from the claim signer.
|
|
2047
|
+
*/
|
|
2048
|
+
peerId?: string;
|
|
2049
|
+
/** Bearer secret for `Authorization`. Omit for the no-auth peer path. */
|
|
2050
|
+
authToken?: string;
|
|
2051
|
+
/** Request timeout in milliseconds (default: 30000). */
|
|
1339
2052
|
timeout?: number;
|
|
2053
|
+
/** Max retry attempts for transport-level network failures (default: 3). */
|
|
2054
|
+
maxRetries?: number;
|
|
2055
|
+
/** Initial retry delay in milliseconds (default: 1000). */
|
|
2056
|
+
retryDelay?: number;
|
|
2057
|
+
/** Custom fetch implementation (for testing / custom transports). */
|
|
2058
|
+
httpClient?: typeof fetch;
|
|
2059
|
+
/**
|
|
2060
|
+
* Custom WebSocket constructor for the BTP upgrade path (for testing /
|
|
2061
|
+
* custom transports). Forwarded to the underlying BtpRuntimeClient.
|
|
2062
|
+
*/
|
|
2063
|
+
createWebSocket?: (url: string) => WebSocket;
|
|
1340
2064
|
}
|
|
1341
2065
|
/**
|
|
1342
|
-
*
|
|
1343
|
-
* per client-edge endpoint and each route price per (endpoint, destination).
|
|
1344
|
-
*
|
|
1345
|
-
* The cache is per endpoint rather than per client instance because a sender
|
|
1346
|
-
* routinely speaks to several connectors, and re-fetching a key per packet
|
|
1347
|
-
* would put a network round trip in front of every send. Nothing here expires
|
|
1348
|
-
* on a timer: an operator key rotation, or a route being repriced, is a
|
|
1349
|
-
* deliberate event, so {@link invalidateIdentity} / {@link invalidateRoutePrice}
|
|
1350
|
-
* are how a stale answer is dropped.
|
|
2066
|
+
* Stateless ILP-over-HTTP transport implementing `IlpClient`.
|
|
1351
2067
|
*
|
|
1352
|
-
*
|
|
1353
|
-
*
|
|
1354
|
-
*
|
|
1355
|
-
*
|
|
2068
|
+
* Use this for pure one-shot consumers (publish-and-forget writes). When the
|
|
2069
|
+
* client needs a duplex session — to receive server-initiated packets or to act
|
|
2070
|
+
* as a peer — call {@link upgradeToBtp} to obtain a connected BtpRuntimeClient
|
|
2071
|
+
* that reuses the existing BTP code path.
|
|
1356
2072
|
*/
|
|
1357
|
-
declare class
|
|
1358
|
-
private readonly
|
|
2073
|
+
declare class HttpIlpClient implements IlpClient {
|
|
2074
|
+
private readonly httpEndpoint;
|
|
2075
|
+
private readonly peerId;
|
|
2076
|
+
private readonly authToken;
|
|
1359
2077
|
private readonly timeout;
|
|
1360
|
-
private readonly
|
|
1361
|
-
private readonly
|
|
1362
|
-
|
|
2078
|
+
private readonly retryConfig;
|
|
2079
|
+
private readonly httpClient;
|
|
2080
|
+
private readonly createWebSocket;
|
|
2081
|
+
constructor(config: HttpIlpClientConfig);
|
|
1363
2082
|
/**
|
|
1364
|
-
* The
|
|
1365
|
-
*
|
|
1366
|
-
*
|
|
1367
|
-
*
|
|
2083
|
+
* The client edge this transport pays — the origin `GET /ilp/identity` and
|
|
2084
|
+
* `GET /ilp/routes/price` hang off (`ConnectorEdgeClient` normalizes the
|
|
2085
|
+
* trailing `/ilp` away). Exposed because a sealed write must ask the
|
|
2086
|
+
* connector it is ACTUALLY paying for its key, not a configured guess.
|
|
1368
2087
|
*/
|
|
1369
|
-
|
|
1370
|
-
forceRefresh?: boolean;
|
|
1371
|
-
}): Promise<ConnectorIdentity>;
|
|
2088
|
+
get clientEdgeEndpoint(): string;
|
|
1372
2089
|
/**
|
|
1373
|
-
*
|
|
1374
|
-
*
|
|
2090
|
+
* Send an ILP PREPARE via `POST /ilp` WITHOUT a claim. The connector accepts
|
|
2091
|
+
* this only on free/zero-amount routes; paid writes must use
|
|
2092
|
+
* {@link sendIlpPacketWithClaim}. Satisfies the IlpClient interface.
|
|
2093
|
+
*
|
|
2094
|
+
* `params` may carry a sender-chosen `executionCondition` and an explicit
|
|
2095
|
+
* `expiresAt` (toon-client#350); omitting both is the legacy zero-condition
|
|
2096
|
+
* path, unchanged. With a non-zero condition the FULFILL preimage is
|
|
2097
|
+
* verified (`sha256(fulfillment) == condition`) and a mismatch is surfaced
|
|
2098
|
+
* as a failed result — see {@link mapIlpResponse}.
|
|
1375
2099
|
*/
|
|
1376
|
-
|
|
1377
|
-
/** Whether an identity for `endpoint` is already held (no request is made). */
|
|
1378
|
-
hasCachedIdentity(endpoint: string): boolean;
|
|
2100
|
+
sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult>;
|
|
1379
2101
|
/**
|
|
1380
|
-
*
|
|
1381
|
-
*
|
|
1382
|
-
*
|
|
1383
|
-
*
|
|
1384
|
-
* a transport failure throws {@link NetworkError} instead, so a caller can
|
|
1385
|
-
* always tell "not mine" from "could not ask".
|
|
1386
|
-
*
|
|
1387
|
-
* Fetched once per (endpoint, destination) and reused. ADR 0020 makes a
|
|
1388
|
-
* price flat per handler, so it does not vary with the packet — a route
|
|
1389
|
-
* being repriced is an operator event, and {@link invalidateRoutePrice} is
|
|
1390
|
-
* how a caller reacts to one.
|
|
2102
|
+
* Send an ILP PREPARE via `POST /ilp` with the payment-channel claim attached
|
|
2103
|
+
* as the `ILP-Payment-Channel-Claim` header. `claim` is the SAME JSON object
|
|
2104
|
+
* the BTP path attaches as the `payment-channel-claim` protocolData entry —
|
|
2105
|
+
* we base64(JSON.stringify(claim)) it, byte-for-byte identical to BTP.
|
|
1391
2106
|
*
|
|
1392
|
-
*
|
|
2107
|
+
* Sender-chosen `executionCondition` / explicit `expiresAt` semantics are
|
|
2108
|
+
* identical to {@link sendIlpPacket}.
|
|
1393
2109
|
*/
|
|
1394
|
-
|
|
1395
|
-
forceRefresh?: boolean;
|
|
1396
|
-
}): Promise<ConnectorRoutePrice | null>;
|
|
2110
|
+
sendIlpPacketWithClaim(params: IlpSendParams, claim: unknown): Promise<IlpSendResult>;
|
|
1397
2111
|
/**
|
|
1398
|
-
*
|
|
1399
|
-
* is answered with (client-edge-spec.md §1.4) — including, from a settling
|
|
1400
|
-
* node, the channel-opening facts (connector #617).
|
|
2112
|
+
* Upgrade to a duplex BTP session over the SAME endpoint.
|
|
1401
2113
|
*
|
|
1402
|
-
*
|
|
1403
|
-
*
|
|
1404
|
-
*
|
|
1405
|
-
*
|
|
1406
|
-
*
|
|
1407
|
-
*
|
|
2114
|
+
* Derives the `ws(s)://` URL from `httpEndpoint`, opens a WebSocket with
|
|
2115
|
+
* `Sec-WebSocket-Protocol: btp` and the same `ILP-Peer-Id` + `Authorization`
|
|
2116
|
+
* headers, and returns a connected {@link BtpRuntimeClient}. When auth headers
|
|
2117
|
+
* are present the connector pre-authenticates the session (no in-band auth
|
|
2118
|
+
* frame); without them the BtpRuntimeClient falls back to the normal BTP
|
|
2119
|
+
* auth-frame flow.
|
|
2120
|
+
*
|
|
2121
|
+
* NOTE: passing per-connection headers + a subprotocol to a WebSocket is
|
|
2122
|
+
* Node-only (the `ws` package). Browsers cannot set arbitrary request headers
|
|
2123
|
+
* on a WebSocket handshake, so a browser consumer must use the gateway
|
|
2124
|
+
* transport or BTP-with-auth-frame instead.
|
|
1408
2125
|
*/
|
|
1409
|
-
|
|
2126
|
+
upgradeToBtp(): Promise<BtpRuntimeClient>;
|
|
2127
|
+
private authHeaders;
|
|
1410
2128
|
/**
|
|
1411
|
-
*
|
|
1412
|
-
*
|
|
1413
|
-
*
|
|
2129
|
+
* Single attempt: serialize the PREPARE, POST it, and map the response.
|
|
2130
|
+
* @throws {NetworkError} On connection/timeout failures (retried).
|
|
2131
|
+
* @throws {ConnectorError} On non-retryable transport errors (5xx / unexpected).
|
|
1414
2132
|
*/
|
|
1415
|
-
|
|
2133
|
+
private postPrepare;
|
|
1416
2134
|
/**
|
|
1417
|
-
*
|
|
1418
|
-
*
|
|
2135
|
+
* Map a `200 OK` body (OER FULFILL/REJECT) to an IlpSendResult; map a non-2xx
|
|
2136
|
+
* to a transport error. Per the wire contract, ILP-level rejects arrive as a
|
|
2137
|
+
* 200 + REJECT body — only HTTP non-2xx means a transport-layer failure.
|
|
2138
|
+
*
|
|
2139
|
+
* When `sentCondition` is non-zero the FULFILL preimage is verified against
|
|
2140
|
+
* it; a mismatch yields `accepted: false` (shared `mapIlpResponse` logic,
|
|
2141
|
+
* identical to the BTP path).
|
|
1419
2142
|
*/
|
|
1420
|
-
|
|
1421
|
-
private
|
|
1422
|
-
private fetchIdentity;
|
|
1423
|
-
private readJson;
|
|
1424
|
-
/** GET with a timeout, mapping any transport failure onto {@link NetworkError}. */
|
|
1425
|
-
private get;
|
|
2143
|
+
private mapResponse;
|
|
2144
|
+
private mapTransportError;
|
|
1426
2145
|
}
|
|
2146
|
+
/**
|
|
2147
|
+
* Derive the BTP WebSocket URL from a `POST /ilp` HTTP endpoint. The connector
|
|
2148
|
+
* serves BTP on the SAME path, so we only swap the scheme (http→ws, https→wss).
|
|
2149
|
+
*/
|
|
2150
|
+
declare function httpEndpointToBtpUrl(httpEndpoint: string): string;
|
|
1427
2151
|
|
|
1428
2152
|
/**
|
|
1429
2153
|
* Payment-aware HTTP fetch over TOON (the "h402" flow).
|
|
@@ -1811,7 +2535,7 @@ interface SubmitEvmSettlementParams {
|
|
|
1811
2535
|
/** JSON-RPC endpoint of the bundle's chain (`chainRpcUrls[bundle.chain]`). */
|
|
1812
2536
|
rpcUrl: string;
|
|
1813
2537
|
/** The claim recipient's EVM account (signs + pays gas for the redeem). */
|
|
1814
|
-
account: PrivateKeyAccount;
|
|
2538
|
+
account: PrivateKeyAccount$1;
|
|
1815
2539
|
/** Receipt wait bound, ms (default 60_000). */
|
|
1816
2540
|
timeoutMs?: number;
|
|
1817
2541
|
}
|
|
@@ -1939,6 +2663,24 @@ declare class ToonClient {
|
|
|
1939
2663
|
* the private key — signing happens here, inside the key owner.
|
|
1940
2664
|
*/
|
|
1941
2665
|
signEvent(template: EventTemplate): NostrEvent;
|
|
2666
|
+
/**
|
|
2667
|
+
* Unwrap a NIP-59 gift wrap (kind:1059) addressed to this client's own
|
|
2668
|
+
* Nostr identity, decrypting both NIP-44 layers with the identity's secret
|
|
2669
|
+
* key. The secret key never leaves this call — only the decrypted rumor
|
|
2670
|
+
* and the seal's (signature-verified) signer pubkey come back out.
|
|
2671
|
+
*
|
|
2672
|
+
* Backs the daemon's `POST /nip59-unwrap` control-API endpoint (buzz#19
|
|
2673
|
+
* agent-members receiving gift-wrapped channel keys addressed to the
|
|
2674
|
+
* daemon's identity). Callers MUST validate authorship from the returned
|
|
2675
|
+
* `sealPubkey` — never from `wrap.pubkey`, which NIP-59 mints fresh and
|
|
2676
|
+
* throws away per wrap.
|
|
2677
|
+
*
|
|
2678
|
+
* @throws {GiftWrapAddressError} malformed input, wrong kind, or not
|
|
2679
|
+
* addressed to this identity.
|
|
2680
|
+
* @throws {GiftWrapDecryptError} a NIP-44 layer failed to decrypt, or the
|
|
2681
|
+
* seal's signature didn't verify.
|
|
2682
|
+
*/
|
|
2683
|
+
unwrapGiftWrap(wrap: NostrEvent): UnwrappedGiftWrap;
|
|
1942
2684
|
/**
|
|
1943
2685
|
* Upload bytes to Arweave via the kind:5094 blob-storage DVM (single-packet),
|
|
1944
2686
|
* signing the request with this client's Nostr key and paying through its
|
|
@@ -2189,6 +2931,13 @@ declare class ToonClient {
|
|
|
2189
2931
|
* `connectorHttpEndpoint` is configured, else the BtpRuntimeClient.
|
|
2190
2932
|
* 2. `btpClient` as an explicit fallback (always present when `btpUrl` is set).
|
|
2191
2933
|
*
|
|
2934
|
+
* `config.preferBtpForPaidWrites` (toon-client#482) SWAPS that order: when
|
|
2935
|
+
* set, `btpClient` — which `modes/http.ts` wraps in a
|
|
2936
|
+
* {@link BtpPaidWriteTransport} for this case, giving persistent,
|
|
2937
|
+
* strictly-ordered claim dispatch with its own fallback to `runtimeClient`
|
|
2938
|
+
* — is tried first, and `runtimeClient` remains as a second candidate.
|
|
2939
|
+
* Default `false` reproduces the exact precedence above, unchanged.
|
|
2940
|
+
*
|
|
2192
2941
|
* The level-3 `HttpRuntimeClient` (connector-admin HTTP, no `btpUrl` AND no
|
|
2193
2942
|
* proxy) does NOT implement `sendIlpPacketWithClaim`; in that case there is no
|
|
2194
2943
|
* paid-write transport and we throw a clear, actionable error.
|
|
@@ -2227,6 +2976,17 @@ declare class ToonClient {
|
|
|
2227
2976
|
* configured, or peer negotiation metadata missing.
|
|
2228
2977
|
*/
|
|
2229
2978
|
openChannel(destination?: string): Promise<string>;
|
|
2979
|
+
/**
|
|
2980
|
+
* Adopt an ALREADY-OPEN payment channel for `destination` — the restart path
|
|
2981
|
+
* for a host that persisted the channel id itself (#489).
|
|
2982
|
+
*
|
|
2983
|
+
* Tracking a channel is not enough: the lazy-open path keys off the peer, so
|
|
2984
|
+
* a host that only re-tracked its saved channel still opened (and funded) a
|
|
2985
|
+
* SECOND one on the first paid write. This binds it, so every later write
|
|
2986
|
+
* resumes it, with its claim watermark, and the on-chain client can deposit
|
|
2987
|
+
* into and close it too. Idempotent.
|
|
2988
|
+
*/
|
|
2989
|
+
adoptChannel(destination: string, channelId: string): Promise<void>;
|
|
2230
2990
|
/**
|
|
2231
2991
|
* Gets list of tracked payment channel IDs.
|
|
2232
2992
|
*/
|
|
@@ -2239,6 +2999,28 @@ declare class ToonClient {
|
|
|
2239
2999
|
* Gets the cumulative transferred amount for a tracked channel.
|
|
2240
3000
|
*/
|
|
2241
3001
|
getChannelCumulativeAmount(channelId: string): bigint;
|
|
3002
|
+
/**
|
|
3003
|
+
* The credited balance — earning's read surface (toon-client#494,
|
|
3004
|
+
* toon-meta#262 decision 9). Asks the connector's `POST /ilp/claim-state`
|
|
3005
|
+
* (client-edge-spec.md §1.10) for the netted off-chain position of one or
|
|
3006
|
+
* more tracked channels: deposit, cumulative claimed, available, nonce and
|
|
3007
|
+
* last-claim time — the SAME place `getBalances`'s on-chain reads and a
|
|
3008
|
+
* paid write's claim gate both already treat as this channel's runway
|
|
3009
|
+
* source of truth, rather than a parallel figure this client derives
|
|
3010
|
+
* itself (#262 decision 4 forbids self-reported money).
|
|
3011
|
+
*
|
|
3012
|
+
* `channelIds` defaults to every tracked channel. A channel this client has
|
|
3013
|
+
* no signer for (e.g. Mina — unsupported by this endpoint) or no recorded
|
|
3014
|
+
* chain context for is silently skipped, matching `getBalances`'s
|
|
3015
|
+
* best-effort-per-chain posture.
|
|
3016
|
+
*
|
|
3017
|
+
* @param opts.expiresInSeconds - How long the signed challenge stays valid
|
|
3018
|
+
* (default 300s). This is a READ signature, distinct from a real claim —
|
|
3019
|
+
* it moves no value and advances no nonce.
|
|
3020
|
+
*/
|
|
3021
|
+
getClaimState(channelIds?: string[], opts?: {
|
|
3022
|
+
expiresInSeconds?: number;
|
|
3023
|
+
}): Promise<ClaimStateResult[]>;
|
|
2242
3024
|
/**
|
|
2243
3025
|
* Gets the on-chain deposit total (locked collateral) for a tracked channel.
|
|
2244
3026
|
* The available (spendable) balance is this minus the cumulative spent amount.
|
|
@@ -2317,6 +3099,21 @@ declare class ToonClient {
|
|
|
2317
3099
|
* are derived there).
|
|
2318
3100
|
*/
|
|
2319
3101
|
getBalances(): Promise<WalletBalance[]>;
|
|
3102
|
+
/**
|
|
3103
|
+
* Lazily derive the mnemonic's full multi-chain identity, at most once per
|
|
3104
|
+
* call to the returned function. Solana/Mina keys are only registered as
|
|
3105
|
+
* signers during `start()`; this lets an UNSTARTED client (e.g. `rig
|
|
3106
|
+
* balance`, or `sendTransfer` before `start()`) derive them on demand
|
|
3107
|
+
* instead. Shared by {@link getWalletBalances} and {@link sendTransfer}.
|
|
3108
|
+
*/
|
|
3109
|
+
private createIdentityDeriver;
|
|
3110
|
+
/**
|
|
3111
|
+
* The EVM chain key + RPC URL to use for a settlement-token/native-gas
|
|
3112
|
+
* operation: the settlement chain wins over the preset-first chain, mirroring
|
|
3113
|
+
* {@link getBalances}. Shared by {@link getWalletBalances} and
|
|
3114
|
+
* {@link sendTransfer}.
|
|
3115
|
+
*/
|
|
3116
|
+
private resolveSettlementEvmChain;
|
|
2320
3117
|
/**
|
|
2321
3118
|
* The FULL multi-chain wallet view (#299): for every chain the identity is
|
|
2322
3119
|
* configured for, the native coin (ETH / SOL / MINA) AND every configured
|
|
@@ -2343,6 +3140,34 @@ declare class ToonClient {
|
|
|
2343
3140
|
solanaChannel?: ToonClientConfig['solanaChannel'];
|
|
2344
3141
|
minaChannel?: ToonClientConfig['minaChannel'];
|
|
2345
3142
|
}): Promise<WalletChainBalances[]>;
|
|
3143
|
+
/**
|
|
3144
|
+
* Send the settlement token or native gas from THIS client's own wallet to
|
|
3145
|
+
* an arbitrary address, on any chain this client is configured for.
|
|
3146
|
+
* Non-custodial plain send (issue #491) — distinct from the payment-channel
|
|
3147
|
+
* machinery, and the missing primitive underneath provisioning a buzz agent
|
|
3148
|
+
* (toon-protocol/buzz#74): the owner's treasury funds a freshly-derived
|
|
3149
|
+
* agent address with USDC + gas before that address can open a channel.
|
|
3150
|
+
*
|
|
3151
|
+
* Confirmed by an OBSERVED balance delta at the destination, never by the
|
|
3152
|
+
* send call/transaction merely landing — see `transfer.ts` module docs
|
|
3153
|
+
* (the devnet faucet's Solana leg has returned a real tx signature while
|
|
3154
|
+
* delivering 0 lamports, connector#691).
|
|
3155
|
+
*
|
|
3156
|
+
* Chain resolution mirrors {@link getWalletBalances}: EVM picks the
|
|
3157
|
+
* settlement chain key (falling back to the first usable EVM chain) from
|
|
3158
|
+
* `chainRpcUrls`/`settlementAddresses`; Solana/Mina need `solanaChannel`/
|
|
3159
|
+
* `minaChannel` configured, and their signing keys are either already
|
|
3160
|
+
* derived (client was `start()`-ed) or derived on demand from `mnemonic`.
|
|
3161
|
+
*
|
|
3162
|
+
* @throws {UnknownChainError} `params.chain` isn't configured on this client.
|
|
3163
|
+
* @throws {InvalidAddressError} `params.to` is malformed for the chain.
|
|
3164
|
+
* @throws {InsufficientBalanceError} the sender can't cover amount (+ fees).
|
|
3165
|
+
* @throws {TransferNotDeliveredError} accepted on-chain/by-node, but the
|
|
3166
|
+
* destination balance never reflected it within the wait window.
|
|
3167
|
+
* @throws {TransferUnsupportedError} chain/asset combination not implemented
|
|
3168
|
+
* yet (currently: the Mina settlement token).
|
|
3169
|
+
*/
|
|
3170
|
+
sendTransfer(params: SendTransferParams): Promise<SendTransferResult>;
|
|
2346
3171
|
/**
|
|
2347
3172
|
* Resolves an ILP destination address to a peer ID.
|
|
2348
3173
|
* Convention: destination "g.toon.peer1" → peerId "peer1" (last segment).
|
|
@@ -2445,7 +3270,37 @@ declare class ToonClient {
|
|
|
2445
3270
|
*/
|
|
2446
3271
|
private getChainContext;
|
|
2447
3272
|
/**
|
|
2448
|
-
*
|
|
3273
|
+
* Picks the settlement chain both `ourChains` and `peerChains` support,
|
|
3274
|
+
* used by the lightweight bootstrap-fallback negotiation (peer discovered
|
|
3275
|
+
* but no connector admin registered a chain). Prefers
|
|
3276
|
+
* `this.config.preferredChain`'s family (#485) over array order; picks the
|
|
3277
|
+
* first mutually-supported chain (legacy behavior) when unconfigured.
|
|
3278
|
+
*
|
|
3279
|
+
* Chains are matched by {@link canonicalChainId} rather than exact string
|
|
3280
|
+
* equality (#500): the devnet preset's family-qualified `evm:base:84532`
|
|
3281
|
+
* and the live apex's unqualified `evm:84532` name the same chain, and
|
|
3282
|
+
* exact matching skipped straight past it to the next mutually-supported
|
|
3283
|
+
* chain (`solana:devnet`) — negotiating a chain nobody asked for instead
|
|
3284
|
+
* of failing loudly. The PEER's own chain string is returned (not ours),
|
|
3285
|
+
* since callers index the peer's own `settlementAddresses` /
|
|
3286
|
+
* `preferredTokens` / `tokenNetworks` maps with it.
|
|
3287
|
+
*
|
|
3288
|
+
* @throws {ToonClientError} `CHAIN_NOT_SUPPORTED` naming both chain sets
|
|
3289
|
+
* when no common chain exists — a caller explicitly configured this
|
|
3290
|
+
* peer as a counterparty, so silently negotiating a different chain (or
|
|
3291
|
+
* returning nothing) would hide a real incompatibility behind an
|
|
3292
|
+
* unrelated failure several layers downstream (#500).
|
|
3293
|
+
*/
|
|
3294
|
+
private matchNegotiatedChain;
|
|
3295
|
+
/**
|
|
3296
|
+
* Gets the default chain context: the explicitly-configured
|
|
3297
|
+
* `preferredChain` family when set (#485 — e.g. `TOON_CLIENT_CHAIN=evm`
|
|
3298
|
+
* must not silently pin to `supportedChains[0]` when that happens to be a
|
|
3299
|
+
* different chain, such as Solana), else the first supported chain.
|
|
3300
|
+
*
|
|
3301
|
+
* @throws {ToonClientError} `CHAIN_NOT_SUPPORTED` if `preferredChain` is
|
|
3302
|
+
* set but none of `supportedChains` belong to that family — this must
|
|
3303
|
+
* fail loudly rather than fall back to a chain the caller didn't choose.
|
|
2449
3304
|
*/
|
|
2450
3305
|
private getDefaultChainContext;
|
|
2451
3306
|
/**
|
|
@@ -2491,6 +3346,131 @@ declare class ToonClient {
|
|
|
2491
3346
|
getDiscoveredPeers(): _toon_protocol_core.DiscoveredPeer[];
|
|
2492
3347
|
}
|
|
2493
3348
|
|
|
3349
|
+
/**
|
|
3350
|
+
* Hashlock delivery helpers (toon-meta#262 decision 5, toon-client#495) —
|
|
3351
|
+
* symmetric between the provider and buyer sides of one factory-job
|
|
3352
|
+
* increment, per `docs/factory-job-protocol.md` §4.2 (toon-meta).
|
|
3353
|
+
*
|
|
3354
|
+
* The provider encrypts an increment's artifact under a fresh key and sets
|
|
3355
|
+
* `condition = sha256(key)`; the only way to claim the increment's payment
|
|
3356
|
+
* is to reveal `key` as the ILP fulfillment — which is the same instant the
|
|
3357
|
+
* buyer can decrypt. Neither party moves first, because there is no first.
|
|
3358
|
+
*
|
|
3359
|
+
* That property holds only if `condition` is derived from nothing but the
|
|
3360
|
+
* key that actually decrypts the artifact. {@link encryptArtifact} is the
|
|
3361
|
+
* ONLY place a `condition` is minted, and it takes no key or condition
|
|
3362
|
+
* parameter — there is no way to call it with a condition that does not
|
|
3363
|
+
* match the key it generates. Do not build a second path that derives a
|
|
3364
|
+
* condition from the artifact, a job id, or any other value.
|
|
3365
|
+
*
|
|
3366
|
+
* Artifacts are permanent on Arweave (decision 13) — there is no deletion —
|
|
3367
|
+
* so confidentiality rests entirely on `key`. Never log a key, and never let
|
|
3368
|
+
* one reach an error message.
|
|
3369
|
+
*
|
|
3370
|
+
* AEAD: ChaCha20-Poly1305 (RFC 8439), the same primitive `wire/giftwrap.ts`
|
|
3371
|
+
* uses for the connector's sealed envelopes — 12-byte random nonce prepended
|
|
3372
|
+
* to the ciphertext, no additional authenticated data. The key doubles as
|
|
3373
|
+
* the 32-byte ILP fulfillment ({@link fulfillIncrement}), which is why it is
|
|
3374
|
+
* exactly {@link CONDITION_LENGTH} bytes rather than a cipher-chosen size.
|
|
3375
|
+
*
|
|
3376
|
+
* Isomorphic: `@noble/*` only, no Buffer, no `node:crypto`.
|
|
3377
|
+
*/
|
|
3378
|
+
/** What encrypting an artifact produces (provider side). */
|
|
3379
|
+
interface EncryptedArtifact {
|
|
3380
|
+
/** `nonce(12) || AEAD ciphertext` — safe to upload to Arweave as-is. */
|
|
3381
|
+
readonly ciphertext: Uint8Array;
|
|
3382
|
+
/**
|
|
3383
|
+
* The freshly minted 32-byte symmetric key. This is also the ILP
|
|
3384
|
+
* fulfillment ({@link fulfillIncrement}) — never reuse it for another
|
|
3385
|
+
* increment, never log it, never put it in an error message.
|
|
3386
|
+
*/
|
|
3387
|
+
readonly key: Uint8Array;
|
|
3388
|
+
/** `sha256(key)` — publish as the kind:7000 offer's `condition` tag. */
|
|
3389
|
+
readonly condition: Uint8Array;
|
|
3390
|
+
}
|
|
3391
|
+
/**
|
|
3392
|
+
* Provider: encrypt one increment's artifact under a freshly minted key and
|
|
3393
|
+
* derive its hashlock condition.
|
|
3394
|
+
*
|
|
3395
|
+
* Deliberately takes only the artifact bytes. There is no `key` or
|
|
3396
|
+
* `condition` parameter — accepting either would let a caller mint a
|
|
3397
|
+
* condition that does not match the key that actually decrypts the
|
|
3398
|
+
* artifact, silently breaking the atomicity this module exists to
|
|
3399
|
+
* guarantee. Call this once per increment; a reused key means paying for
|
|
3400
|
+
* increment *i* unlocks increment *i+1*.
|
|
3401
|
+
*/
|
|
3402
|
+
declare function encryptArtifact(artifact: Uint8Array): EncryptedArtifact;
|
|
3403
|
+
/**
|
|
3404
|
+
* Provider: fulfil an increment by revealing `key` as the ILP fulfillment.
|
|
3405
|
+
* The key IS the fulfillment (identity) — this exists so the "reveal the
|
|
3406
|
+
* key" step has one named call site rather than being inlined wherever a
|
|
3407
|
+
* FULFILL is built, and so a wrongly-sized key fails loudly here instead of
|
|
3408
|
+
* on the wire.
|
|
3409
|
+
*
|
|
3410
|
+
* @throws {Error} if `key` is not exactly {@link CONDITION_LENGTH} bytes.
|
|
3411
|
+
*/
|
|
3412
|
+
declare function fulfillIncrement(key: Uint8Array): Uint8Array;
|
|
3413
|
+
/**
|
|
3414
|
+
* Thrown when `sha256(key)` does not match the condition the buyer actually
|
|
3415
|
+
* paid. Never carries `key` or any derived secret — only lengths and hex of
|
|
3416
|
+
* the (public) conditions being compared.
|
|
3417
|
+
*/
|
|
3418
|
+
declare class HashlockConditionMismatchError extends Error {
|
|
3419
|
+
constructor(message: string);
|
|
3420
|
+
}
|
|
3421
|
+
/**
|
|
3422
|
+
* Thrown when a ciphertext fails to decrypt under a key that DID satisfy the
|
|
3423
|
+
* paid condition — a corrupted or tampered artifact fetch. Never carries the
|
|
3424
|
+
* key or any recovered plaintext.
|
|
3425
|
+
*/
|
|
3426
|
+
declare class HashlockDecryptError extends Error {
|
|
3427
|
+
readonly cause?: Error | undefined;
|
|
3428
|
+
constructor(message: string, cause?: Error | undefined);
|
|
3429
|
+
}
|
|
3430
|
+
/**
|
|
3431
|
+
* Buyer: verify `key` against `paidCondition`, then decrypt.
|
|
3432
|
+
*
|
|
3433
|
+
* `paidCondition` MUST be the condition the buyer's own PREPARE carried as
|
|
3434
|
+
* `executionCondition` — read from local state, never re-derived from the
|
|
3435
|
+
* `key` just handed over by the provider at reveal time. Re-deriving it
|
|
3436
|
+
* would make this check tautological and defeat the reason it exists: to
|
|
3437
|
+
* catch a provider who advertised one condition, got paid against it, then
|
|
3438
|
+
* revealed a DIFFERENT key that happens to decrypt something.
|
|
3439
|
+
*
|
|
3440
|
+
* @throws {HashlockConditionMismatchError} `sha256(key) !== paidCondition`.
|
|
3441
|
+
* @throws {HashlockDecryptError} the AEAD open failed (tampered/corrupted
|
|
3442
|
+
* ciphertext, or a truncated one).
|
|
3443
|
+
*/
|
|
3444
|
+
declare function decryptArtifact(ciphertext: Uint8Array, key: Uint8Array, paidCondition: Uint8Array): Uint8Array;
|
|
3445
|
+
/** What a buyer reads off an advertised kind:7000 increment offer (§4.1). */
|
|
3446
|
+
interface IncrementOfferTags {
|
|
3447
|
+
/** The `condition` tag's value: hex-encoded `sha256(key)`. */
|
|
3448
|
+
readonly conditionHex: string;
|
|
3449
|
+
/** The `amount` tag's value: decimal micro-USDC. */
|
|
3450
|
+
readonly amountUsdc: string;
|
|
3451
|
+
}
|
|
3452
|
+
/** PREPARE-ready fields derived from an advertised increment offer. */
|
|
3453
|
+
interface IncrementPrepare {
|
|
3454
|
+
/** Spread into `ToonClient.sendSwapPacket`'s `executionCondition`. */
|
|
3455
|
+
readonly executionCondition: Uint8Array;
|
|
3456
|
+
/** Spread into `ToonClient.sendSwapPacket`'s `amount`. */
|
|
3457
|
+
readonly amount: bigint;
|
|
3458
|
+
}
|
|
3459
|
+
/**
|
|
3460
|
+
* Buyer: turn an advertised kind:7000 increment offer's `condition` and
|
|
3461
|
+
* `amount` tags into the fields a PREPARE needs — `executionCondition` MUST
|
|
3462
|
+
* equal the offer's `condition` byte for byte (spec §4.2), which is exactly
|
|
3463
|
+
* what this returns, undecorated.
|
|
3464
|
+
*
|
|
3465
|
+
* Pure parsing: does not send anything, does not touch a channel. Feed the
|
|
3466
|
+
* result into `sendSwapPacket({ destination, amount, toonData, executionCondition })`.
|
|
3467
|
+
*
|
|
3468
|
+
* @throws {Error} a malformed hex condition, a condition that is not
|
|
3469
|
+
* {@link CONDITION_LENGTH} bytes once decoded, or a non-positive/
|
|
3470
|
+
* non-numeric amount.
|
|
3471
|
+
*/
|
|
3472
|
+
declare function buildIncrementPrepare(offer: IncrementOfferTags): IncrementPrepare;
|
|
3473
|
+
|
|
2494
3474
|
/**
|
|
2495
3475
|
* Configuration options for HttpRuntimeClient.
|
|
2496
3476
|
*/
|
|
@@ -2755,316 +3735,254 @@ declare class HttpConnectorAdmin implements ConnectorAdminClient {
|
|
|
2755
3735
|
/**
|
|
2756
3736
|
* Send HTTP POST request to add a peer.
|
|
2757
3737
|
* Separated for retry logic wrapping.
|
|
2758
|
-
*/
|
|
2759
|
-
private sendAddPeerRequest;
|
|
2760
|
-
/**
|
|
2761
|
-
* Send HTTP DELETE request to remove a peer.
|
|
2762
|
-
* Separated for retry logic wrapping.
|
|
2763
|
-
*/
|
|
2764
|
-
private sendRemovePeerRequest;
|
|
2765
|
-
/**
|
|
2766
|
-
* Handle network errors from HTTP requests.
|
|
2767
|
-
*
|
|
2768
|
-
* Converts connection failures, timeouts, and unknown errors to NetworkError.
|
|
2769
|
-
* Re-throws existing ToonClientError instances.
|
|
2770
|
-
*
|
|
2771
|
-
* @param error - Error thrown by HTTP client
|
|
2772
|
-
* @param url - Request URL (for error messages)
|
|
2773
|
-
* @param operation - Operation name (for error messages)
|
|
2774
|
-
* @throws {NetworkError} Network connection or timeout error
|
|
2775
|
-
*/
|
|
2776
|
-
private handleNetworkError;
|
|
2777
|
-
/**
|
|
2778
|
-
* Handle HTTP error responses from the admin API.
|
|
2779
|
-
*
|
|
2780
|
-
* Converts HTTP status codes to appropriate error types.
|
|
2781
|
-
*
|
|
2782
|
-
* @param response - HTTP response from admin API
|
|
2783
|
-
* @param endpoint - Endpoint being called (for error messages)
|
|
2784
|
-
* @param peerId - Peer ID (for error messages)
|
|
2785
|
-
* @throws {UnauthorizedError} 401 Unauthorized
|
|
2786
|
-
* @throws {PeerNotFoundError} 404 Not Found
|
|
2787
|
-
* @throws {PeerAlreadyExistsError} 409 Conflict
|
|
2788
|
-
* @throws {ConnectorError} 5xx Server Error
|
|
2789
|
-
*/
|
|
2790
|
-
private handleErrorResponse;
|
|
2791
|
-
}
|
|
2792
|
-
|
|
2793
|
-
/**
|
|
2794
|
-
* Transport selection policy for the client ILP layer.
|
|
2795
|
-
*
|
|
2796
|
-
* The connector serves ILP-over-HTTP (`POST /ilp`) and BTP on the SAME port
|
|
2797
|
-
* (connector PR #181). A peer advertises this in discovery via the toon-core
|
|
2798
|
-
* `IlpPeerInfo` fields added in toon PR #29:
|
|
2799
|
-
* - `httpEndpoint?: string` — the `POST /ilp` URL.
|
|
2800
|
-
* - `supportsUpgrade?: boolean` — whether the host accepts the BTP upgrade.
|
|
2801
|
-
*
|
|
2802
|
-
* Those fields may not yet exist on the installed `@toon-protocol/core`
|
|
2803
|
-
* `IlpPeerInfo` type, so we read them defensively here (see `DiscoveredIlpPeer`).
|
|
2804
|
-
*
|
|
2805
|
-
* Policy:
|
|
2806
|
-
* - Pure one-shot consumers (`needsDuplex: false`) prefer HTTP when the peer
|
|
2807
|
-
* advertises an `httpEndpoint` — stateless, no persistent socket.
|
|
2808
|
-
* - Clients that must receive server-initiated packets or act as a peer
|
|
2809
|
-
* (`needsDuplex: true`) use BTP. If the peer only exposes `httpEndpoint`
|
|
2810
|
-
* and `supportsUpgrade` is true, we go HTTP-then-upgrade; otherwise we
|
|
2811
|
-
* connect to the BTP endpoint directly.
|
|
2812
|
-
*/
|
|
2813
|
-
/**
|
|
2814
|
-
* The subset of discovery fields this policy reads. Structurally compatible with
|
|
2815
|
-
* core's `IlpPeerInfo`; `httpEndpoint`/`supportsUpgrade` are optional so a
|
|
2816
|
-
* pre-PR-#29 `IlpPeerInfo` can be passed through a cast.
|
|
2817
|
-
*/
|
|
2818
|
-
interface DiscoveredIlpPeer {
|
|
2819
|
-
/** BTP WebSocket endpoint (always present on a TOON peer). */
|
|
2820
|
-
btpEndpoint?: string;
|
|
2821
|
-
/** `POST /ilp` URL (toon PR #29). */
|
|
2822
|
-
httpEndpoint?: string;
|
|
2823
|
-
/** Whether the host accepts the BTP upgrade over the HTTP endpoint (toon PR #29). */
|
|
2824
|
-
supportsUpgrade?: boolean;
|
|
2825
|
-
}
|
|
2826
|
-
type IlpTransportChoice =
|
|
2827
|
-
/** Stateless one-shot writes via `POST /ilp`. */
|
|
2828
|
-
{
|
|
2829
|
-
kind: 'http';
|
|
2830
|
-
httpEndpoint: string;
|
|
2831
|
-
canUpgrade: boolean;
|
|
2832
|
-
}
|
|
2833
|
-
/** Duplex BTP session via the WebSocket endpoint. */
|
|
2834
|
-
| {
|
|
2835
|
-
kind: 'btp';
|
|
2836
|
-
btpEndpoint: string;
|
|
2837
|
-
}
|
|
2838
|
-
/**
|
|
2839
|
-
* Open HTTP first (one-shot writes) but upgrade to BTP when duplex is needed.
|
|
2840
|
-
* Only chosen when the peer exposes `httpEndpoint` + `supportsUpgrade` and no
|
|
2841
|
-
* separate `btpEndpoint`.
|
|
2842
|
-
*/
|
|
2843
|
-
| {
|
|
2844
|
-
kind: 'http-upgradable';
|
|
2845
|
-
httpEndpoint: string;
|
|
2846
|
-
};
|
|
2847
|
-
interface SelectIlpTransportOptions {
|
|
2848
|
-
/**
|
|
2849
|
-
* Whether the client needs a duplex session (receive server-initiated
|
|
2850
|
-
* packets / act as a peer). Default: false (pure one-shot consumer).
|
|
2851
|
-
*/
|
|
2852
|
-
needsDuplex?: boolean;
|
|
2853
|
-
}
|
|
2854
|
-
/**
|
|
2855
|
-
* Read discovery fields defensively from a (possibly pre-PR-#29) peer info
|
|
2856
|
-
* object. Accepts core's `IlpPeerInfo` or any structurally-compatible shape.
|
|
2857
|
-
*/
|
|
2858
|
-
declare function readDiscoveredIlpPeer(peer: unknown): DiscoveredIlpPeer;
|
|
2859
|
-
/**
|
|
2860
|
-
* Choose the ILP transport for a discovered peer given the consumer's needs.
|
|
2861
|
-
*
|
|
2862
|
-
* @throws {Error} If the peer advertises no usable endpoint at all.
|
|
2863
|
-
*/
|
|
2864
|
-
declare function selectIlpTransport(peer: DiscoveredIlpPeer, options?: SelectIlpTransportOptions): IlpTransportChoice;
|
|
2865
|
-
|
|
2866
|
-
/**
|
|
2867
|
-
* Chain-specific metadata (discriminated union).
|
|
2868
|
-
*/
|
|
2869
|
-
type ChainMetadata = {
|
|
2870
|
-
chainType: 'evm';
|
|
2871
|
-
chainId: number;
|
|
2872
|
-
tokenNetworkAddress: string;
|
|
2873
|
-
tokenAddress?: string;
|
|
2874
|
-
} | {
|
|
2875
|
-
chainType: 'solana';
|
|
2876
|
-
programId: string;
|
|
2877
|
-
tokenMint?: string;
|
|
2878
|
-
} | {
|
|
2879
|
-
chainType: 'mina';
|
|
2880
|
-
zkAppAddress: string;
|
|
2881
|
-
tokenId?: string;
|
|
2882
|
-
};
|
|
2883
|
-
/**
|
|
2884
|
-
* Chain-agnostic signing interface for balance proofs.
|
|
2885
|
-
*/
|
|
2886
|
-
interface ChainSigner {
|
|
2887
|
-
readonly chainType: 'evm' | 'solana' | 'mina';
|
|
2888
|
-
readonly signerIdentifier: string;
|
|
2889
|
-
signBalanceProof(params: {
|
|
2890
|
-
channelId: string;
|
|
2891
|
-
nonce: number;
|
|
2892
|
-
transferredAmount: bigint;
|
|
2893
|
-
lockedAmount: bigint;
|
|
2894
|
-
locksRoot: string;
|
|
2895
|
-
/**
|
|
2896
|
-
* Counterparty settlement address the proof is bound to. Required for
|
|
2897
|
-
* Solana/Mina (folded into the canonical balance-proof message); the EVM
|
|
2898
|
-
* adapter ignores it (EIP-712 has no recipient term).
|
|
2899
|
-
*/
|
|
2900
|
-
recipient: string;
|
|
2901
|
-
metadata: ChainMetadata;
|
|
2902
|
-
/**
|
|
2903
|
-
* On-chain channel `depositTotal` (base units). When supplied (>0), a Mina
|
|
2904
|
-
* signer binds the conserved `balanceB = depositTotal − balanceA` commitment
|
|
2905
|
-
* required to settle on a funded zkApp (connector#133); EVM/Solana signers
|
|
2906
|
-
* ignore it. When omitted, a Mina signer self-resolves it from chain if it
|
|
2907
|
-
* was configured with a GraphQL URL (#223), else falls back to the legacy
|
|
2908
|
-
* `balanceB = 0` form.
|
|
2909
|
-
*/
|
|
2910
|
-
depositTotal?: bigint;
|
|
2911
|
-
}): Promise<SignedBalanceProof>;
|
|
2912
|
-
buildClaimMessage(proof: SignedBalanceProof, senderId: string): ClaimMessage;
|
|
2913
|
-
}
|
|
2914
|
-
type ClaimMessage = EVMClaimMessage | SolanaClaimMessage | MinaClaimMessage;
|
|
2915
|
-
/**
|
|
2916
|
-
* Solana payment-channel claim — wire-compatible with the connector's
|
|
2917
|
-
* `SolanaClaimMessage` (`@toon-protocol/connector` `btp/btp-claim-types.ts`).
|
|
2918
|
-
* Field names match the connector's `validateSolanaClaim` exactly:
|
|
2919
|
-
* `channelAccount` (base58 PDA), `signerPublicKey` (base58), base64 `signature`.
|
|
2920
|
-
*/
|
|
2921
|
-
interface SolanaClaimMessage {
|
|
2922
|
-
version: '1.0';
|
|
2923
|
-
blockchain: 'solana';
|
|
2924
|
-
messageId: string;
|
|
2925
|
-
timestamp: string;
|
|
2926
|
-
senderId: string;
|
|
2927
|
-
/** On-chain PDA account address for the payment channel (base58). */
|
|
2928
|
-
channelAccount: string;
|
|
2929
|
-
nonce: number;
|
|
2930
|
-
/** Cumulative transferred amount (string for bigint precision). */
|
|
2931
|
-
transferredAmount: string;
|
|
2932
|
-
/** Ed25519 signature over the 48-byte balance-proof message (base64). */
|
|
2933
|
-
signature: string;
|
|
2934
|
-
/** Base58-encoded Ed25519 public key of the signer. */
|
|
2935
|
-
signerPublicKey: string;
|
|
2936
|
-
/** Solana program id for the payment-channel program (base58). */
|
|
2937
|
-
programId: string;
|
|
2938
|
-
}
|
|
2939
|
-
/**
|
|
2940
|
-
* Mina payment-channel claim — wire-compatible with the connector's
|
|
2941
|
-
* `MinaClaimMessage` (`@toon-protocol/connector` `btp/btp-claim-types.ts`).
|
|
2942
|
-
* Field names + types match `validateMinaClaim` exactly: `zkAppAddress`
|
|
2943
|
-
* (B62-prefixed 55-char base58, the channel id), `tokenId`, `balanceCommitment`
|
|
2944
|
-
* (`Poseidon([balA,balB,salt])` decimal string), integer `nonce`, base64 `proof`,
|
|
2945
|
-
* and `salt`. `transferredAmount`/`balanceB`/`signatureB`/`network` are OPTIONAL
|
|
2946
|
-
* at validation; the apex-as-recipient single-direction claim sends party-A only.
|
|
2947
|
-
*/
|
|
2948
|
-
interface MinaClaimMessage {
|
|
2949
|
-
version: '1.0';
|
|
2950
|
-
blockchain: 'mina';
|
|
2951
|
-
messageId: string;
|
|
2952
|
-
timestamp: string;
|
|
2953
|
-
senderId: string;
|
|
2954
|
-
/** Deployed payment-channel zkApp address (B62 base58) — the channel id. */
|
|
2955
|
-
zkAppAddress: string;
|
|
2956
|
-
/** Mina token id (default `'MINA'`). */
|
|
2957
|
-
tokenId: string;
|
|
2958
|
-
/** `Poseidon([balanceA, balanceB, salt]).toString()`. */
|
|
2959
|
-
balanceCommitment: string;
|
|
2960
|
-
nonce: number;
|
|
2961
|
-
/** base64-encoded JSON `{ commitment, signature: { r, s }, nonce, signerPublicKey }`. */
|
|
2962
|
-
proof: string;
|
|
2963
|
-
/** Commitment salt (decimal string). */
|
|
2964
|
-
salt: string;
|
|
2965
|
-
/** Cumulative transferred amount (optional; string for bigint precision). */
|
|
2966
|
-
transferredAmount?: string;
|
|
3738
|
+
*/
|
|
3739
|
+
private sendAddPeerRequest;
|
|
2967
3740
|
/**
|
|
2968
|
-
*
|
|
3741
|
+
* Send HTTP DELETE request to remove a peer.
|
|
3742
|
+
* Separated for retry logic wrapping.
|
|
3743
|
+
*/
|
|
3744
|
+
private sendRemovePeerRequest;
|
|
3745
|
+
/**
|
|
3746
|
+
* Handle network errors from HTTP requests.
|
|
2969
3747
|
*
|
|
2970
|
-
*
|
|
2971
|
-
*
|
|
2972
|
-
*
|
|
2973
|
-
*
|
|
2974
|
-
*
|
|
2975
|
-
*
|
|
2976
|
-
*
|
|
3748
|
+
* Converts connection failures, timeouts, and unknown errors to NetworkError.
|
|
3749
|
+
* Re-throws existing ToonClientError instances.
|
|
3750
|
+
*
|
|
3751
|
+
* @param error - Error thrown by HTTP client
|
|
3752
|
+
* @param url - Request URL (for error messages)
|
|
3753
|
+
* @param operation - Operation name (for error messages)
|
|
3754
|
+
* @throws {NetworkError} Network connection or timeout error
|
|
2977
3755
|
*/
|
|
2978
|
-
|
|
2979
|
-
/**
|
|
2980
|
-
|
|
3756
|
+
private handleNetworkError;
|
|
3757
|
+
/**
|
|
3758
|
+
* Handle HTTP error responses from the admin API.
|
|
3759
|
+
*
|
|
3760
|
+
* Converts HTTP status codes to appropriate error types.
|
|
3761
|
+
*
|
|
3762
|
+
* @param response - HTTP response from admin API
|
|
3763
|
+
* @param endpoint - Endpoint being called (for error messages)
|
|
3764
|
+
* @param peerId - Peer ID (for error messages)
|
|
3765
|
+
* @throws {UnauthorizedError} 401 Unauthorized
|
|
3766
|
+
* @throws {PeerNotFoundError} 404 Not Found
|
|
3767
|
+
* @throws {PeerAlreadyExistsError} 409 Conflict
|
|
3768
|
+
* @throws {ConnectorError} 5xx Server Error
|
|
3769
|
+
*/
|
|
3770
|
+
private handleErrorResponse;
|
|
2981
3771
|
}
|
|
2982
3772
|
|
|
2983
3773
|
/**
|
|
2984
|
-
*
|
|
2985
|
-
*
|
|
2986
|
-
*
|
|
2987
|
-
*
|
|
2988
|
-
*
|
|
2989
|
-
*
|
|
3774
|
+
* Persistent, strictly-ordered BTP transport for paid writes (issue #482).
|
|
3775
|
+
*
|
|
3776
|
+
* ─── Why this exists ─────────────────────────────────────────────────────
|
|
3777
|
+
* `HttpIlpClient` (the default paid-write transport, `POST /ilp`) is
|
|
3778
|
+
* stateless: every write is an independent HTTP request, and the connector's
|
|
3779
|
+
* claim gate advances a channel's nonce watermark per request in WHATEVER
|
|
3780
|
+
* order those requests happen to arrive — client-edge-spec.md §1.3 step 2. A
|
|
3781
|
+
* burst of concurrent paid writes on one channel can therefore race each
|
|
3782
|
+
* other into `F01 NonceNotAdvancing`: two requests both built against the
|
|
3783
|
+
* same last-known nonce, one arrives first and advances the watermark, the
|
|
3784
|
+
* other is now stale.
|
|
3785
|
+
*
|
|
3786
|
+
* The connector's client-facing BTP websocket ingress (client-edge-spec.md
|
|
3787
|
+
* §1.9, connector#680/#674) processes frames on ONE session strictly in
|
|
3788
|
+
* arrival order — the next frame is not read until the previous frame's
|
|
3789
|
+
* claim has been judged. A client that dispatches its OWN claims in the same
|
|
3790
|
+
* order it enqueued them therefore never races itself. This was measured on
|
|
3791
|
+
* the huddle-over-ILP prototype (`toon-meta/prototypes/huddle-over-ilp`,
|
|
3792
|
+
* branch `proto/huddle-over-ilp`): 0 F01 rejects across 4,156 events at a
|
|
3793
|
+
* paced 50fps (audio-frame-rate) sustained load, where the equivalent
|
|
3794
|
+
* unordered concurrent-HTTP baseline raced.
|
|
3795
|
+
*
|
|
3796
|
+
* This module productizes that pattern as a reusable transport rather than
|
|
3797
|
+
* a one-off harness: a caller that needs many ordered paid writes on one
|
|
3798
|
+
* channel (the motivating consumer is relay-native huddle audio, ~140fps of
|
|
3799
|
+
* measured headroom per session) constructs one `BtpPaidWriteTransport`
|
|
3800
|
+
* around a `BtpRuntimeClient` session and sends through it exactly like any
|
|
3801
|
+
* other `sendIlpPacketWithClaim`-shaped transport.
|
|
3802
|
+
*
|
|
3803
|
+
* ─── What it adds over a bare `BtpRuntimeClient` ────────────────────────
|
|
3804
|
+
* - **Persistent session**: the underlying session is connected once,
|
|
3805
|
+
* lazily, on the first write, and stays open across every subsequent
|
|
3806
|
+
* write. This is NOT the `Http402Client.upgradeToBtp()` pattern (open,
|
|
3807
|
+
* send one packet, immediately disconnect) — the whole point is to reuse
|
|
3808
|
+
* one ordered socket across a burst.
|
|
3809
|
+
* - **Strictly ordered dispatch**: every `sendIlpPacketWithClaim` call is
|
|
3810
|
+
* appended to a FIFO queue; the next call is not dispatched onto the wire
|
|
3811
|
+
* until the previous one has fully settled (fulfilled, rejected, or
|
|
3812
|
+
* fallen back to HTTP). Callers may still fire writes concurrently
|
|
3813
|
+
* (`Promise.all`) — ordering is enforced here, not pushed onto the
|
|
3814
|
+
* caller.
|
|
3815
|
+
* - **Reconnect + resume**: a write that fails on a connection-level error
|
|
3816
|
+
* (socket dropped mid-burst) reconnects the SAME session and retries
|
|
3817
|
+
* that write in place, without losing its position in the queue and
|
|
3818
|
+
* without reordering the writes queued behind it — they simply wait for
|
|
3819
|
+
* it to resolve one way or another.
|
|
3820
|
+
* - **Falls back to HTTP**: once the reconnect budget for one write is
|
|
3821
|
+
* exhausted, the write is handed to `fallback` (typically the existing
|
|
3822
|
+
* `HttpIlpClient`) when one is configured, so a BTP outage degrades a
|
|
3823
|
+
* session to the pre-existing one-shot behavior instead of failing the
|
|
3824
|
+
* write outright.
|
|
3825
|
+
*
|
|
3826
|
+
* Only CONNECTION-level failures (dropped socket, timeout — the errors
|
|
3827
|
+
* `BtpRuntimeClient`/`IsomorphicBtpClient` throw) are retried or routed to
|
|
3828
|
+
* the fallback. An ILP-level REJECT (F02, T01, ...) is a normal
|
|
3829
|
+
* `IlpSendResult`, exactly like every other transport here — it is returned
|
|
3830
|
+
* to the caller unchanged, never retried and never silently resent over
|
|
3831
|
+
* HTTP (a claim that was actually judged and refused must not be replayed).
|
|
2990
3832
|
*/
|
|
2991
|
-
|
|
2992
|
-
|
|
2993
|
-
|
|
2994
|
-
|
|
2995
|
-
|
|
2996
|
-
|
|
2997
|
-
|
|
2998
|
-
|
|
2999
|
-
|
|
3000
|
-
lockedAmount: string;
|
|
3001
|
-
locksRoot: string;
|
|
3002
|
-
signature: string;
|
|
3003
|
-
signerAddress: string;
|
|
3004
|
-
/** Chain ID for self-describing EIP-712 verification */
|
|
3005
|
-
chainId: number;
|
|
3006
|
-
/** TokenNetwork address for self-describing EIP-712 verification */
|
|
3007
|
-
tokenNetworkAddress: string;
|
|
3008
|
-
/** ERC-20 token address for self-describing claim verification */
|
|
3009
|
-
tokenAddress?: string;
|
|
3833
|
+
|
|
3834
|
+
/**
|
|
3835
|
+
* The narrow shape a paid-write transport candidate needs — the same method
|
|
3836
|
+
* `ToonClient.getClaimTransport()` already requires of `HttpIlpClient` and
|
|
3837
|
+
* `BtpRuntimeClient`. Declared independently so this module (and its tests)
|
|
3838
|
+
* do not need the concrete transport classes.
|
|
3839
|
+
*/
|
|
3840
|
+
interface ClaimSendingTransport {
|
|
3841
|
+
sendIlpPacketWithClaim(params: IlpSendParams, claim: unknown): Promise<IlpSendResult>;
|
|
3010
3842
|
}
|
|
3011
3843
|
/**
|
|
3012
|
-
*
|
|
3013
|
-
*
|
|
3014
|
-
*
|
|
3844
|
+
* The subset of `BtpRuntimeClient` this transport drives. `BtpRuntimeClient`
|
|
3845
|
+
* satisfies this structurally — no adapter needed — but tests can supply a
|
|
3846
|
+
* lightweight fake instead of a real WebSocket-backed instance.
|
|
3015
3847
|
*/
|
|
3016
|
-
|
|
3017
|
-
readonly
|
|
3018
|
-
|
|
3848
|
+
interface OrderedBtpSession {
|
|
3849
|
+
readonly isConnected: boolean;
|
|
3850
|
+
connect(): Promise<void>;
|
|
3851
|
+
reconnect(): Promise<void>;
|
|
3852
|
+
disconnect(): Promise<void>;
|
|
3853
|
+
sendIlpPacketWithClaim(params: IlpSendParams, claim: Record<string, unknown>): Promise<IlpSendResult>;
|
|
3854
|
+
}
|
|
3855
|
+
interface BtpPaidWriteTransportConfig {
|
|
3019
3856
|
/**
|
|
3020
|
-
*
|
|
3857
|
+
* The persistent BTP session this transport owns the connect/reconnect
|
|
3858
|
+
* lifecycle of. May already be connected (the common case — `modes/http.ts`
|
|
3859
|
+
* connects `btpClient` at startup) or not; either way it is connected
|
|
3860
|
+
* lazily on first use and never disconnected between writes.
|
|
3021
3861
|
*/
|
|
3022
|
-
|
|
3023
|
-
/** Derived 0x EVM address */
|
|
3024
|
-
get address(): string;
|
|
3025
|
-
/** ChainSigner identifier — EVM address */
|
|
3026
|
-
get signerIdentifier(): string;
|
|
3027
|
-
/** Viem PrivateKeyAccount — usable with walletClient for on-chain transactions */
|
|
3028
|
-
get account(): PrivateKeyAccount$1;
|
|
3862
|
+
session: OrderedBtpSession;
|
|
3029
3863
|
/**
|
|
3030
|
-
*
|
|
3031
|
-
*
|
|
3032
|
-
*
|
|
3033
|
-
* @returns Signed balance proof with signature
|
|
3864
|
+
* Stateless fallback used once a write's reconnect budget is exhausted.
|
|
3865
|
+
* Typically an `HttpIlpClient` pointed at the same connector's `POST /ilp`.
|
|
3866
|
+
* Omit to have an exhausted BTP session fail the write outright.
|
|
3034
3867
|
*/
|
|
3035
|
-
|
|
3036
|
-
chainId: number;
|
|
3037
|
-
tokenNetworkAddress: string;
|
|
3038
|
-
tokenAddress?: string;
|
|
3039
|
-
}): Promise<SignedBalanceProof>;
|
|
3868
|
+
fallback?: ClaimSendingTransport;
|
|
3040
3869
|
/**
|
|
3041
|
-
*
|
|
3042
|
-
*
|
|
3043
|
-
*
|
|
3044
|
-
* @param proof - Signed balance proof (includes chainId and tokenNetworkAddress)
|
|
3045
|
-
* @param senderId - Nostr pubkey or identifier of the sender
|
|
3046
|
-
* @returns EVMClaimMessage compatible with BTP_CLAIM_PROTOCOL
|
|
3870
|
+
* Reconnect attempts for one write before giving up on BTP (and, if
|
|
3871
|
+
* configured, falling back to HTTP). Default 1 — one explicit reconnect
|
|
3872
|
+
* beyond whatever retrying the session already does internally.
|
|
3047
3873
|
*/
|
|
3048
|
-
|
|
3874
|
+
maxReconnectAttempts?: number;
|
|
3875
|
+
/** Delay before each reconnect attempt, in ms. Default 250. */
|
|
3876
|
+
reconnectDelay?: number;
|
|
3877
|
+
}
|
|
3878
|
+
/**
|
|
3879
|
+
* Wraps an {@link OrderedBtpSession} (a `BtpRuntimeClient`) as a first-class,
|
|
3880
|
+
* persistent, strictly-ordered paid-write transport with an optional HTTP
|
|
3881
|
+
* fallback. See the module docs above for the full rationale.
|
|
3882
|
+
*/
|
|
3883
|
+
declare class BtpPaidWriteTransport implements ClaimSendingTransport {
|
|
3884
|
+
private readonly session;
|
|
3885
|
+
private readonly fallback;
|
|
3886
|
+
private readonly maxReconnectAttempts;
|
|
3887
|
+
private readonly reconnectDelay;
|
|
3888
|
+
/**
|
|
3889
|
+
* Tail of the ordering queue. ALWAYS settles (never rejects) so one
|
|
3890
|
+
* failed write can never strand every write queued behind it — only the
|
|
3891
|
+
* write itself carries its own outcome, via the promise `sendIlpPacketWithClaim`
|
|
3892
|
+
* returns to its caller.
|
|
3893
|
+
*/
|
|
3894
|
+
private queueTail;
|
|
3895
|
+
constructor(config: BtpPaidWriteTransportConfig);
|
|
3896
|
+
/** Whether the underlying session currently holds an open socket. */
|
|
3897
|
+
get isConnected(): boolean;
|
|
3898
|
+
/** Explicitly closes the persistent session (e.g. `ToonClient.stop()`). */
|
|
3899
|
+
disconnect(): Promise<void>;
|
|
3900
|
+
/**
|
|
3901
|
+
* Enqueue a claim-bearing write. The returned promise resolves/rejects
|
|
3902
|
+
* with THIS write's own outcome; its position in the queue only controls
|
|
3903
|
+
* WHEN it is dispatched onto the wire, never what it returns.
|
|
3904
|
+
*/
|
|
3905
|
+
sendIlpPacketWithClaim(params: IlpSendParams, claim: unknown): Promise<IlpSendResult>;
|
|
3906
|
+
/**
|
|
3907
|
+
* One write's worth of connect/send/reconnect/fallback policy. Runs
|
|
3908
|
+
* strictly after every write enqueued ahead of it has settled.
|
|
3909
|
+
*/
|
|
3910
|
+
private dispatchWithRetry;
|
|
3049
3911
|
}
|
|
3050
3912
|
|
|
3051
3913
|
/**
|
|
3052
|
-
*
|
|
3914
|
+
* Transport selection policy for the client ILP layer.
|
|
3915
|
+
*
|
|
3916
|
+
* The connector serves ILP-over-HTTP (`POST /ilp`) and BTP on the SAME port
|
|
3917
|
+
* (connector PR #181). A peer advertises this in discovery via the toon-core
|
|
3918
|
+
* `IlpPeerInfo` fields added in toon PR #29:
|
|
3919
|
+
* - `httpEndpoint?: string` — the `POST /ilp` URL.
|
|
3920
|
+
* - `supportsUpgrade?: boolean` — whether the host accepts the BTP upgrade.
|
|
3921
|
+
*
|
|
3922
|
+
* Those fields may not yet exist on the installed `@toon-protocol/core`
|
|
3923
|
+
* `IlpPeerInfo` type, so we read them defensively here (see `DiscoveredIlpPeer`).
|
|
3053
3924
|
*
|
|
3054
|
-
*
|
|
3055
|
-
*
|
|
3056
|
-
*
|
|
3057
|
-
*
|
|
3058
|
-
*
|
|
3059
|
-
* is
|
|
3060
|
-
* to
|
|
3925
|
+
* Policy:
|
|
3926
|
+
* - Pure one-shot consumers (`needsDuplex: false`) prefer HTTP when the peer
|
|
3927
|
+
* advertises an `httpEndpoint` — stateless, no persistent socket.
|
|
3928
|
+
* - Clients that must receive server-initiated packets or act as a peer
|
|
3929
|
+
* (`needsDuplex: true`) use BTP. If the peer only exposes `httpEndpoint`
|
|
3930
|
+
* and `supportsUpgrade` is true, we go HTTP-then-upgrade; otherwise we
|
|
3931
|
+
* connect to the BTP endpoint directly.
|
|
3932
|
+
*/
|
|
3933
|
+
/**
|
|
3934
|
+
* The subset of discovery fields this policy reads. Structurally compatible with
|
|
3935
|
+
* core's `IlpPeerInfo`; `httpEndpoint`/`supportsUpgrade` are optional so a
|
|
3936
|
+
* pre-PR-#29 `IlpPeerInfo` can be passed through a cast.
|
|
3937
|
+
*/
|
|
3938
|
+
interface DiscoveredIlpPeer {
|
|
3939
|
+
/** BTP WebSocket endpoint (always present on a TOON peer). */
|
|
3940
|
+
btpEndpoint?: string;
|
|
3941
|
+
/** `POST /ilp` URL (toon PR #29). */
|
|
3942
|
+
httpEndpoint?: string;
|
|
3943
|
+
/** Whether the host accepts the BTP upgrade over the HTTP endpoint (toon PR #29). */
|
|
3944
|
+
supportsUpgrade?: boolean;
|
|
3945
|
+
}
|
|
3946
|
+
type IlpTransportChoice =
|
|
3947
|
+
/** Stateless one-shot writes via `POST /ilp`. */
|
|
3948
|
+
{
|
|
3949
|
+
kind: 'http';
|
|
3950
|
+
httpEndpoint: string;
|
|
3951
|
+
canUpgrade: boolean;
|
|
3952
|
+
}
|
|
3953
|
+
/** Duplex BTP session via the WebSocket endpoint. */
|
|
3954
|
+
| {
|
|
3955
|
+
kind: 'btp';
|
|
3956
|
+
btpEndpoint: string;
|
|
3957
|
+
}
|
|
3958
|
+
/**
|
|
3959
|
+
* Open HTTP first (one-shot writes) but upgrade to BTP when duplex is needed.
|
|
3960
|
+
* Only chosen when the peer exposes `httpEndpoint` + `supportsUpgrade` and no
|
|
3961
|
+
* separate `btpEndpoint`.
|
|
3962
|
+
*/
|
|
3963
|
+
| {
|
|
3964
|
+
kind: 'http-upgradable';
|
|
3965
|
+
httpEndpoint: string;
|
|
3966
|
+
};
|
|
3967
|
+
interface SelectIlpTransportOptions {
|
|
3968
|
+
/**
|
|
3969
|
+
* Whether the client needs a duplex session (receive server-initiated
|
|
3970
|
+
* packets / act as a peer). Default: false (pure one-shot consumer).
|
|
3971
|
+
*/
|
|
3972
|
+
needsDuplex?: boolean;
|
|
3973
|
+
}
|
|
3974
|
+
/**
|
|
3975
|
+
* Read discovery fields defensively from a (possibly pre-PR-#29) peer info
|
|
3976
|
+
* object. Accepts core's `IlpPeerInfo` or any structurally-compatible shape.
|
|
3977
|
+
*/
|
|
3978
|
+
declare function readDiscoveredIlpPeer(peer: unknown): DiscoveredIlpPeer;
|
|
3979
|
+
/**
|
|
3980
|
+
* Choose the ILP transport for a discovered peer given the consumer's needs.
|
|
3061
3981
|
*
|
|
3062
|
-
*
|
|
3063
|
-
* contract (`balanceProofHashSolana`, SDK `verifyEd25519Signature`). The client
|
|
3064
|
-
* here is paying a payment-channel claim to the apex, not issuing a swap claim,
|
|
3065
|
-
* so it must sign the connector's on-chain payment-channel message. `channelId`
|
|
3066
|
-
* MUST be the base58 channel PDA (produced by `OnChainChannelClient.openChannel`).
|
|
3982
|
+
* @throws {Error} If the peer advertises no usable endpoint at all.
|
|
3067
3983
|
*/
|
|
3984
|
+
declare function selectIlpTransport(peer: DiscoveredIlpPeer, options?: SelectIlpTransportOptions): IlpTransportChoice;
|
|
3985
|
+
|
|
3068
3986
|
declare class SolanaSigner implements ChainSigner {
|
|
3069
3987
|
readonly chainType: "solana";
|
|
3070
3988
|
/** 32-byte Ed25519 seed. */
|
|
@@ -3087,6 +4005,21 @@ declare class SolanaSigner implements ChainSigner {
|
|
|
3087
4005
|
recipient: string;
|
|
3088
4006
|
metadata: ChainMetadata;
|
|
3089
4007
|
}): Promise<SignedBalanceProof>;
|
|
4008
|
+
/**
|
|
4009
|
+
* Signs a `POST /ilp/claim-state` claim-state challenge (client-edge-spec.md
|
|
4010
|
+
* §1.10): `"toon-claim-state-challenge-v1" || channelAccount(32) ||
|
|
4011
|
+
* expires(u64 LE)` — a tagged message distinct in both content and length
|
|
4012
|
+
* from a real 48-byte balance-proof message, so a captured challenge can
|
|
4013
|
+
* never be replayed as a payment or vice versa. Returns base64 (the
|
|
4014
|
+
* connector's documented wire encoding for this endpoint, unlike the
|
|
4015
|
+
* hex-encoded balance-proof signature elsewhere in this class).
|
|
4016
|
+
*
|
|
4017
|
+
* @param params.expires - Unix seconds the signature stops verifying.
|
|
4018
|
+
*/
|
|
4019
|
+
signClaimStateChallenge(params: {
|
|
4020
|
+
channelAccount: string;
|
|
4021
|
+
expires: number;
|
|
4022
|
+
}): Promise<string>;
|
|
3090
4023
|
buildClaimMessage(proof: SignedBalanceProof, senderId: string): ClaimMessage;
|
|
3091
4024
|
}
|
|
3092
4025
|
|
|
@@ -3308,6 +4241,25 @@ interface OnChainChannelClientConfig {
|
|
|
3308
4241
|
chainRpcUrls: Record<string, string>;
|
|
3309
4242
|
solanaConfig?: SolanaChannelConfig;
|
|
3310
4243
|
minaConfig?: MinaChannelConfig;
|
|
4244
|
+
/**
|
|
4245
|
+
* How hard the EVM opener works to survive a STALE-READ RPC (#489).
|
|
4246
|
+
*
|
|
4247
|
+
* Public Base Sepolia (`sepolia.base.org`) is a load balancer: the
|
|
4248
|
+
* `setTotalDeposit` that follows a just-confirmed `openChannel` can land on a
|
|
4249
|
+
* replica that has not seen the open yet and reverts `InvalidChannelState()`
|
|
4250
|
+
* (`0xf806e9d9`). So the opener polls the channel back until the RPC agrees
|
|
4251
|
+
* it exists, and retries the deposit on that specific revert.
|
|
4252
|
+
*/
|
|
4253
|
+
readConsistency?: EvmReadConsistencyConfig;
|
|
4254
|
+
}
|
|
4255
|
+
/** Read-after-write polling knobs for the EVM open path (#489). */
|
|
4256
|
+
interface EvmReadConsistencyConfig {
|
|
4257
|
+
/** Reads of the freshly opened channel before giving up. Default 12. */
|
|
4258
|
+
attempts?: number;
|
|
4259
|
+
/** Delay between those reads, ms. Default 1000. */
|
|
4260
|
+
delayMs?: number;
|
|
4261
|
+
/** `setTotalDeposit` retries on `InvalidChannelState()`. Default 3. */
|
|
4262
|
+
depositRetries?: number;
|
|
3311
4263
|
}
|
|
3312
4264
|
/**
|
|
3313
4265
|
* Implements ConnectorChannelClient using viem for direct on-chain
|
|
@@ -3321,7 +4273,20 @@ declare class OnChainChannelClient implements ConnectorChannelClient {
|
|
|
3321
4273
|
private solanaConfig?;
|
|
3322
4274
|
private minaConfig?;
|
|
3323
4275
|
private readonly channelContext;
|
|
4276
|
+
private readonly readConsistency;
|
|
3324
4277
|
constructor(config: OnChainChannelClientConfig);
|
|
4278
|
+
/**
|
|
4279
|
+
* Adopt a channel this process did NOT open — a RESUMED one (#489), whose
|
|
4280
|
+
* chain/token-network/token context came back from the channel store rather
|
|
4281
|
+
* than from an `openChannel` call. Without it a restarted client can track
|
|
4282
|
+
* and pay on a resumed channel but cannot deposit into, close, or read it,
|
|
4283
|
+
* because those all look up the in-memory `channelContext` this seeds.
|
|
4284
|
+
*/
|
|
4285
|
+
adoptChannel(channelId: string, ctx: {
|
|
4286
|
+
chain: string;
|
|
4287
|
+
tokenNetworkAddress: string;
|
|
4288
|
+
tokenAddress?: string;
|
|
4289
|
+
}): void;
|
|
3325
4290
|
/**
|
|
3326
4291
|
* Late-binds the Solana channel config.
|
|
3327
4292
|
*
|
|
@@ -3516,6 +4481,19 @@ declare class OnChainChannelClient implements ConnectorChannelClient {
|
|
|
3516
4481
|
* 4. Deposit initial funds if specified
|
|
3517
4482
|
*/
|
|
3518
4483
|
private openEvmChannelUnchecked;
|
|
4484
|
+
/**
|
|
4485
|
+
* Poll the TokenNetwork until it reports the just-opened channel (non-zero
|
|
4486
|
+
* `participant1`). Tolerates a read that throws or returns nothing — a stale
|
|
4487
|
+
* replica does both — and surfaces a {@link StaleRpcReadError} naming the RPC
|
|
4488
|
+
* when the endpoint never converges.
|
|
4489
|
+
*/
|
|
4490
|
+
private waitForEvmChannelVisible;
|
|
4491
|
+
/**
|
|
4492
|
+
* `setTotalDeposit`, retried on `InvalidChannelState()` — the revert a stale
|
|
4493
|
+
* replica produces for a channel it hasn't observed. Every other revert
|
|
4494
|
+
* propagates immediately (an under-funded wallet must not be retried).
|
|
4495
|
+
*/
|
|
4496
|
+
private setTotalDepositWithRetry;
|
|
3519
4497
|
/**
|
|
3520
4498
|
* Gets the current state of a payment channel from on-chain data.
|
|
3521
4499
|
*/
|
|
@@ -3532,14 +4510,109 @@ interface ChannelStoreEntry {
|
|
|
3532
4510
|
/** Unix SECONDS the channel was settled (collateral released). */
|
|
3533
4511
|
settledAt?: bigint;
|
|
3534
4512
|
}
|
|
4513
|
+
/**
|
|
4514
|
+
* Chain context needed to re-track a RESUMED channel — the same shape
|
|
4515
|
+
* {@link ChannelManager.trackChannel} takes.
|
|
4516
|
+
*/
|
|
4517
|
+
interface ChannelBindingContext {
|
|
4518
|
+
chainType: string;
|
|
4519
|
+
chainId: number;
|
|
4520
|
+
tokenNetworkAddress: string;
|
|
4521
|
+
tokenAddress?: string;
|
|
4522
|
+
/** Counterparty settlement address (required for Solana/Mina proofs). */
|
|
4523
|
+
recipient?: string;
|
|
4524
|
+
}
|
|
4525
|
+
/**
|
|
4526
|
+
* One persisted peer→channel binding: WHICH on-chain channel this identity
|
|
4527
|
+
* already holds with a peer, on a given chain + token network (#489).
|
|
4528
|
+
*/
|
|
4529
|
+
interface ChannelBinding {
|
|
4530
|
+
/** On-chain payment channel id (EVM bytes32 / Solana PDA / Mina zkApp). */
|
|
4531
|
+
channelId: string;
|
|
4532
|
+
/** Context for `trackChannel` on resume. */
|
|
4533
|
+
context: ChannelBindingContext;
|
|
4534
|
+
/** On-chain collateral locked at open time, when the open surfaced it. */
|
|
4535
|
+
depositTotal?: bigint;
|
|
4536
|
+
/** ISO timestamp of the open that created this binding. */
|
|
4537
|
+
openedAt?: string;
|
|
4538
|
+
}
|
|
3535
4539
|
/**
|
|
3536
4540
|
* Persistence interface for payment channel nonce/amount state.
|
|
4541
|
+
*
|
|
4542
|
+
* The binding methods are OPTIONAL so a third-party `ChannelStore` written
|
|
4543
|
+
* against the pre-#489 surface still satisfies the type; a store that omits
|
|
4544
|
+
* them simply can't resume a peer's channel across restarts (it will open a
|
|
4545
|
+
* fresh one, the old behaviour). {@link JsonFileChannelStore} implements them.
|
|
3537
4546
|
*/
|
|
3538
4547
|
interface ChannelStore {
|
|
3539
4548
|
save(channelId: string, tracking: ChannelStoreEntry): void;
|
|
3540
4549
|
load(channelId: string): ChannelStoreEntry | undefined;
|
|
3541
4550
|
list(): string[];
|
|
3542
4551
|
delete(channelId: string): void;
|
|
4552
|
+
/** Persist the channel a peer key is bound to. */
|
|
4553
|
+
saveBinding?(key: string, binding: ChannelBinding): void;
|
|
4554
|
+
/** The channel a peer key is bound to, if any. */
|
|
4555
|
+
loadBinding?(key: string): ChannelBinding | undefined;
|
|
4556
|
+
/** Every persisted binding, keyed as {@link saveBinding} stored it. */
|
|
4557
|
+
listBindings?(): {
|
|
4558
|
+
key: string;
|
|
4559
|
+
binding: ChannelBinding;
|
|
4560
|
+
}[];
|
|
4561
|
+
/** Forget a binding (its nonce watermark is deliberately left intact). */
|
|
4562
|
+
deleteBinding?(key: string): void;
|
|
4563
|
+
}
|
|
4564
|
+
/**
|
|
4565
|
+
* JSON file-backed ChannelStore.
|
|
4566
|
+
* Uses synchronous I/O to match ChannelManager's sync API surface.
|
|
4567
|
+
*
|
|
4568
|
+
* Two files, on purpose: the nonce/cumulative watermark keeps its historical
|
|
4569
|
+
* `{ [channelId]: entry }` schema in `filePath` (rig and the MCP daemon parse
|
|
4570
|
+
* that file directly), while the peer→channel bindings live in a SIBLING file
|
|
4571
|
+
* (`channels.json` → `channels.peers.json`, override with `bindingsPath`).
|
|
4572
|
+
* Extending the watermark file's schema in place would have broken those
|
|
4573
|
+
* external readers.
|
|
4574
|
+
*/
|
|
4575
|
+
declare class JsonFileChannelStore implements ChannelStore {
|
|
4576
|
+
private readonly filePath;
|
|
4577
|
+
private readonly bindingsPath;
|
|
4578
|
+
constructor(filePath: string, options?: {
|
|
4579
|
+
bindingsPath?: string;
|
|
4580
|
+
});
|
|
4581
|
+
save(channelId: string, tracking: ChannelStoreEntry): void;
|
|
4582
|
+
load(channelId: string): ChannelStoreEntry | undefined;
|
|
4583
|
+
list(): string[];
|
|
4584
|
+
delete(channelId: string): void;
|
|
4585
|
+
saveBinding(key: string, binding: ChannelBinding): void;
|
|
4586
|
+
loadBinding(key: string): ChannelBinding | undefined;
|
|
4587
|
+
listBindings(): {
|
|
4588
|
+
key: string;
|
|
4589
|
+
binding: ChannelBinding;
|
|
4590
|
+
}[];
|
|
4591
|
+
deleteBinding(key: string): void;
|
|
4592
|
+
private readFile;
|
|
4593
|
+
private writeFile;
|
|
4594
|
+
private readBindings;
|
|
4595
|
+
private writeBindings;
|
|
4596
|
+
}
|
|
4597
|
+
/**
|
|
4598
|
+
* In-memory {@link ChannelStore} (watermarks + bindings). Handy for tests and
|
|
4599
|
+
* for a process that wants resume semantics within its own lifetime without
|
|
4600
|
+
* touching disk.
|
|
4601
|
+
*/
|
|
4602
|
+
declare class InMemoryChannelStore implements ChannelStore {
|
|
4603
|
+
private readonly entries;
|
|
4604
|
+
private readonly bindings;
|
|
4605
|
+
save(channelId: string, tracking: ChannelStoreEntry): void;
|
|
4606
|
+
load(channelId: string): ChannelStoreEntry | undefined;
|
|
4607
|
+
list(): string[];
|
|
4608
|
+
delete(channelId: string): void;
|
|
4609
|
+
saveBinding(key: string, binding: ChannelBinding): void;
|
|
4610
|
+
loadBinding(key: string): ChannelBinding | undefined;
|
|
4611
|
+
listBindings(): {
|
|
4612
|
+
key: string;
|
|
4613
|
+
binding: ChannelBinding;
|
|
4614
|
+
}[];
|
|
4615
|
+
deleteBinding(key: string): void;
|
|
3543
4616
|
}
|
|
3544
4617
|
|
|
3545
4618
|
interface ChannelManagerConfig {
|
|
@@ -3591,13 +4664,69 @@ declare class ChannelManager {
|
|
|
3591
4664
|
* For EVM, returns an adapter wrapping the EvmSigner.
|
|
3592
4665
|
*/
|
|
3593
4666
|
getSignerForChannel(channelId: string): ChainSigner;
|
|
4667
|
+
/**
|
|
4668
|
+
* The key a peer's channel binding is persisted under: the peer, the
|
|
4669
|
+
* negotiated chain, and the token network the channel lives on. All three
|
|
4670
|
+
* matter — the same peer on a second chain (or a redeployed token network) is
|
|
4671
|
+
* a DIFFERENT channel.
|
|
4672
|
+
*/
|
|
4673
|
+
private static bindingKey;
|
|
3594
4674
|
/**
|
|
3595
4675
|
* Lazily open a channel for a peer. Idempotent — returns existing channel
|
|
3596
4676
|
* if already open. Deduplicates concurrent opens for the same peer.
|
|
4677
|
+
*
|
|
4678
|
+
* RESUME (#489): before opening anything on-chain, the persisted peer→channel
|
|
4679
|
+
* binding is consulted, so a restarted process re-attaches to the channel it
|
|
4680
|
+
* already holds instead of locking a second lot of collateral. Solana got this
|
|
4681
|
+
* for free (its channel id is a deterministic PDA, so a re-open re-derived the
|
|
4682
|
+
* same channel); EVM mints a fresh `bytes32` per `openChannel` call, so every
|
|
4683
|
+
* restart stranded a deposit until this binding existed.
|
|
3597
4684
|
*/
|
|
3598
4685
|
ensureChannel(peerId: string, negotiation: PeerNegotiation): Promise<string>;
|
|
3599
4686
|
/**
|
|
3600
|
-
*
|
|
4687
|
+
* Adopt an ALREADY-OPEN channel as this peer's channel: track it (rehydrating
|
|
4688
|
+
* its watermark from the store), bind it so later lazy opens RESUME it rather
|
|
4689
|
+
* than opening a second one, and hand the on-chain client its context back.
|
|
4690
|
+
*
|
|
4691
|
+
* For a host that persisted the channel id itself before the client could
|
|
4692
|
+
* (the MCP daemon's apex-channel store, rig's channel map): those hosts used
|
|
4693
|
+
* to `trackChannel` on restart, which left `ensureChannel` unaware — so the
|
|
4694
|
+
* first paid write opened a SECOND on-chain channel anyway (#489).
|
|
4695
|
+
*/
|
|
4696
|
+
adoptChannel(peerId: string, negotiation: PeerNegotiation, channelId: string): void;
|
|
4697
|
+
/**
|
|
4698
|
+
* Re-attach to the channel this identity already holds with `peerId`, from the
|
|
4699
|
+
* store's peer→channel binding. Returns the resumed channel id, or undefined
|
|
4700
|
+
* when there is nothing to resume (no store, no binding, or a binding whose
|
|
4701
|
+
* channel is closing/settled — a spent channel must not be reused).
|
|
4702
|
+
*
|
|
4703
|
+
* `trackChannel` rehydrates the nonce/cumulative watermark from the store, so
|
|
4704
|
+
* the resumed channel keeps signing ABOVE the last claim the connector saw.
|
|
4705
|
+
*
|
|
4706
|
+
* @throws {ChannelResumeError} when the binding's watermark is missing —
|
|
4707
|
+
* resuming would silently reset the nonce and every later claim would be
|
|
4708
|
+
* rejected (F01), so the caller is told loudly instead.
|
|
4709
|
+
*/
|
|
4710
|
+
private resumeChannel;
|
|
4711
|
+
/**
|
|
4712
|
+
* Persist a freshly opened channel as this peer's binding, and SEED its
|
|
4713
|
+
* watermark entry (`nonce 0`) so a later resume can tell "never claimed
|
|
4714
|
+
* against" apart from "watermark lost" (which is a hard
|
|
4715
|
+
* {@link ChannelResumeError}).
|
|
4716
|
+
*/
|
|
4717
|
+
private bindChannel;
|
|
4718
|
+
/**
|
|
4719
|
+
* Re-seed the on-chain client's per-channel context for a RESUMED channel.
|
|
4720
|
+
* `OnChainChannelClient` caches `chain`/`tokenNetwork`/`token` only for
|
|
4721
|
+
* channels it opened in this process, so without this a resumed channel
|
|
4722
|
+
* cannot be deposited into or closed. Optional capability — a channel client
|
|
4723
|
+
* that doesn't implement `adoptChannel` is simply left alone.
|
|
4724
|
+
*/
|
|
4725
|
+
private adoptOnChainContext;
|
|
4726
|
+
/**
|
|
4727
|
+
* Get channel ID for a peer (if any). Channels are held per peer AND chain
|
|
4728
|
+
* AND token network, so a peer settled with on two chains has two — this
|
|
4729
|
+
* returns the first one tracked for the peer.
|
|
3601
4730
|
*/
|
|
3602
4731
|
getChannelForPeer(peerId: string): string | undefined;
|
|
3603
4732
|
/**
|
|
@@ -3674,6 +4803,20 @@ declare class ChannelManager {
|
|
|
3674
4803
|
* Returns true if the channel is being tracked.
|
|
3675
4804
|
*/
|
|
3676
4805
|
isTracking(channelId: string): boolean;
|
|
4806
|
+
/**
|
|
4807
|
+
* The chain context a tracked channel was opened/resumed with — the
|
|
4808
|
+
* chainType/chainId/tokenNetworkAddress a caller needs to build a
|
|
4809
|
+
* `POST /ilp/claim-state` request (toon-client#494) without re-deriving
|
|
4810
|
+
* them from the peer negotiation. `undefined` when `channelId` is not
|
|
4811
|
+
* tracked.
|
|
4812
|
+
*/
|
|
4813
|
+
getChannelContext(channelId: string): {
|
|
4814
|
+
chainType: string;
|
|
4815
|
+
chainId: number;
|
|
4816
|
+
tokenNetworkAddress: string;
|
|
4817
|
+
tokenAddress?: string;
|
|
4818
|
+
recipient?: string;
|
|
4819
|
+
} | undefined;
|
|
3677
4820
|
}
|
|
3678
4821
|
|
|
3679
4822
|
/**
|
|
@@ -4505,7 +5648,7 @@ declare function validateConfig(config: ToonClientConfig): void;
|
|
|
4505
5648
|
* The resolved config type after defaults are applied.
|
|
4506
5649
|
* secretKey is guaranteed to be present (auto-generated if omitted).
|
|
4507
5650
|
*/
|
|
4508
|
-
type ResolvedConfig = Required<Omit<ToonClientConfig, 'connector' | 'mnemonic' | 'mnemonicAccountIndex' | 'evmPrivateKey' | 'network' | 'supportedChains' | 'settlementAddresses' | 'preferredTokens' | 'tokenNetworks' | 'btpUrl' | 'btpAuthToken' | 'btpPeerId' | 'connectorHttpEndpoint' | 'proxyUrl' | 'faucetUrl' | 'connectorSupportsUpgrade' | 'chainRpcUrls' | 'initialDeposit' | 'settlementTimeout' | 'solanaChannel' | 'minaChannel' | 'swapMinaMakerSignatures' | 'channelStorePath' | 'knownPeers' | 'destinationAddress'>> & {
|
|
5651
|
+
type ResolvedConfig = Required<Omit<ToonClientConfig, 'connector' | 'mnemonic' | 'mnemonicAccountIndex' | 'evmPrivateKey' | 'network' | 'supportedChains' | 'preferredChain' | 'settlementAddresses' | 'preferredTokens' | 'tokenNetworks' | 'btpUrl' | 'btpAuthToken' | 'btpPeerId' | 'connectorHttpEndpoint' | 'proxyUrl' | 'faucetUrl' | 'connectorSupportsUpgrade' | 'chainRpcUrls' | 'initialDeposit' | 'settlementTimeout' | 'solanaChannel' | 'minaChannel' | 'swapMinaMakerSignatures' | 'channelStorePath' | 'knownPeers' | 'destinationAddress' | 'jobHandler'>> & {
|
|
4509
5652
|
connector?: unknown;
|
|
4510
5653
|
/** Always present after applyDefaults() — derived from secretKey if not explicitly provided */
|
|
4511
5654
|
evmPrivateKey: string | Uint8Array;
|
|
@@ -4524,6 +5667,7 @@ type ResolvedConfig = Required<Omit<ToonClientConfig, 'connector' | 'mnemonic' |
|
|
|
4524
5667
|
/** Named network tier, retained for `getNetworkStatus()`. */
|
|
4525
5668
|
network?: ToonClientConfig['network'];
|
|
4526
5669
|
supportedChains?: string[];
|
|
5670
|
+
preferredChain?: ToonClientConfig['preferredChain'];
|
|
4527
5671
|
settlementAddresses?: Record<string, string>;
|
|
4528
5672
|
preferredTokens?: Record<string, string>;
|
|
4529
5673
|
tokenNetworks?: Record<string, string>;
|
|
@@ -4547,6 +5691,7 @@ type ResolvedConfig = Required<Omit<ToonClientConfig, 'connector' | 'mnemonic' |
|
|
|
4547
5691
|
btpEndpoint?: string;
|
|
4548
5692
|
}[];
|
|
4549
5693
|
destinationAddress: string;
|
|
5694
|
+
jobHandler?: ToonClientConfig['jobHandler'];
|
|
4550
5695
|
};
|
|
4551
5696
|
/**
|
|
4552
5697
|
* Applies default values to optional configuration fields.
|
|
@@ -5565,4 +6710,4 @@ declare function readExchangeOutcome(result: {
|
|
|
5565
6710
|
/** Read a response header, case-insensitively; the first match wins. */
|
|
5566
6711
|
declare function envelopeHeader(response: EnvelopeResponse, name: string): string | undefined;
|
|
5567
6712
|
|
|
5568
|
-
export { type BackupPayload, type BalanceProofParams, BtpRuntimeClient, type BtpRuntimeClientConfig, type BuildSwapSettlementsParams, CLAIM_TYPEHASH, CONDITION_LENGTH, COOP_CLOSE_TYPEHASH, type ChainMetadata, type ChainSigner, ChannelFundingError, ChannelManager, type ClaimMessage, type ClaimResolver, type ClaimSignature, ConnectorEdgeClient, type ConnectorEdgeClientConfig, ConnectorEdgeError, type ConnectorEdgeErrorCode, ConnectorError, type ConnectorIdentity, type ConnectorRoutePrice, type Decoded, type DeployMinaZkAppParams, type DiscoveredIlpPeer, type EVMClaimMessage, type EncryptedKeystore, type EnsureOwnedMinaZkAppParams, type EnsureOwnedMinaZkAppResult, type Envelope, EnvelopeError, EnvelopeErrorKind, type EnvelopeHeader, type EnvelopeRequest, type EnvelopeResponse, type EvmClaimDomainContext, type EvmClaimMessage, type EvmClaimVerifyResult, type EvmCooperativeCloseMessage, EvmSigner, type ExchangeOutcome, type ExecutionConditionPair, FULFILLMENT_MISMATCH_CODE, FULFILLMENT_MISMATCH_MESSAGE, type FaucetChain, type FundWalletOptions, type FundWalletResult, GIFTWRAP_NONCE_LENGTH, GIFTWRAP_PUBLIC_KEY_LENGTH, GIFTWRAP_SECRET_LENGTH, GIFTWRAP_TYPE_REQUEST, GIFTWRAP_TYPE_RESPONSE, type GiftWrapEcdh, GiftWrapError, GiftWrapErrorKind, type H402FetchOptions, Http402Client, type Http402ClientConfig, HttpConnectorAdmin, type HttpConnectorAdminConfig, HttpIlpClient, type HttpIlpClientConfig, type HttpIlpClientFactory, HttpRuntimeClient, type HttpRuntimeClientConfig, ILP_CLAIM_HEADER, ILP_PEER_ID_HEADER, type IlpSendParams, type IlpSendResultWithFulfillment, type IlpTransportChoice, InMemoryPreimageRetentionStore, InMemoryReceivedClaimStore, type IngestAndRevealParams, type IngestAndRevealResult, type IngestReceivedClaimsParams, type IngestReceivedClaimsResult, JsonFileReceivedClaimStore, KeyManager, type KeyManagerConfig, MINA_CHANNEL_STATE, type MinaChannelStateReader, type MinaClaimMessage, type MinaClaimSubmitArgs, type MinaClaimSubmitter, type MinaCoSignInputs, type MinaCoSignedClaim, type MinaDepositReader, type MinaOnChainChannelState, type MinaSettlementContext, MinaSettlementError, type MinaSettlementErrorCode, type MinaSettlementResult, type MinaSignaturePair, MinaSigner, type MinaSignerOptions, type MinaZkAppDeployRecord, NetworkError, OerError, OerErrorKind, OnChainChannelClient, type OnChainChannelClientConfig, type OpenedRequest, type ParsedX402Challenge, type PasskeyInfo, type PreimageRetentionStore, type PublishEventResult, ROLLING_SWAP_DOMAIN_NAME, ROLLING_SWAP_DOMAIN_VERSION, type ReceivedClaimEntry, type ReceivedClaimRejection, type ReceivedClaimRejectionCode, type ReceivedClaimStore, type RequestBlobStorageParams, type RequestBlobStorageResult, type RetainedPreimage, type RetryOptions, type RevealDecision, type RevealFn, type RevealResult, type RevealedClaim, type RolledBackClaim, type SealedExchange, type SealedRequest, SealedResponseError, type SealedResponseErrorKind, type SelectIlpTransportOptions, type SignedBalanceProof, type SolanaChannelClientOptions, type SolanaClaimMessage, SolanaSigner, type SubmitEvmSettlementParams, type SubmitEvmSettlementResult, type SwapSettlementBuild, type ToonChannelAccept, ToonClient, type ToonClientConfig, ToonClientError, type ToonIdentity, type ToonSigners, type ToonStartResult, ValidationError, type VaultData, type VerifiedReceivedClaim, type WalletBalance, type WalletBalanceSources, type WalletChainBalances, type WalletTokenAmount, applyDefaults, applyNetworkPresets, assertValidCondition, buildBackupEvent, buildBackupFilter, buildMinaCoSignedClaim, buildSettlementInfo, buildSwapSettlements, connectorEdgeBaseUrl, createO1jsMinaClaimSubmitter, decodeConnectorPublicKey, decodeEnvelope, decodeEnvelopeRequest, decodeEnvelopeResponse, decodeEvmSettlementTx, decodeVarOctetString, decodeVarUint, decryptMnemonic, defaultFaucetTimeout, deployMinaChannelZkApp, deriveCondition, deriveFromNsec, deriveFulfillment, deriveFullIdentity, deriveNostrKeyFromMnemonic, encodeEnvelope, encodeEnvelopeRequest, encodeEnvelopeResponse, encodeVarOctetString, encodeVarUint, encryptMnemonic, ensureOwnedMinaZkApp, entryToAccumulatedClaim, envelopeHeader, evmClaimDigest, evmCooperativeCloseDigest, extractArweaveTxId, fulfillmentMatchesCondition, fundWallet, generateKeystore, generateMnemonic, generateRandomIdentity, getNetworkStatus, hasSettlementMetadata, httpEndpointToBtpUrl, importKeystore, ingestAndReveal, ingestReceivedClaims, isInsufficientGasError, isPrfSupported, isZeroCondition, loadKeystore, localGiftWrapEcdh, looksLikeSealedResponse, mintExecutionCondition, openRequest, openResponse, parseBackupPayload, parseConnectorIdentity, parseConnectorRoutePrice, parseEvmChainId, parseX402Body, parseX402Challenge, proxyIlpEndpoint, readDiscoveredIlpPeer, readEvmNativeBalance, readEvmTokenBalance, readExchangeOutcome, readMinaBalance, readMinaChannelState, readMinaDepositTotal, readSolanaNativeBalance, readSolanaTokenBalance, readWalletBalances, recoverEvmClaimSigner, requestBlobStorage, sealExchange, sealRequest, sealRequestWithRandomness, sealResponse, sealResponseWithRandomness, selectIlpTransport, submitEvmSettlement, submitMinaSettlement, validateConfig, validateMnemonic, verifyEvmClaimSignature, withRetry, writeKeystoreFile };
|
|
6713
|
+
export { type BackupPayload, type BalanceProofParams, BtpPaidWriteTransport, type BtpPaidWriteTransportConfig, BtpRuntimeClient, type BtpRuntimeClientConfig, type BuildSwapSettlementsParams, CLAIM_TYPEHASH, CONDITION_LENGTH, COOP_CLOSE_TYPEHASH, type ChainMetadata, type ChainSigner, type ChannelBinding, type ChannelBindingContext, ChannelFundingError, ChannelManager, ChannelResumeError, type ChannelStore, type ChannelStoreEntry, type ClaimMessage, type ClaimResolver, type ClaimSendingTransport, type ClaimSignature, type ClaimStateFailed, type ClaimStateOk, type ClaimStateRequestEntry, type ClaimStateResult, ConnectorEdgeClient, type ConnectorEdgeClientConfig, ConnectorEdgeError, type ConnectorEdgeErrorCode, ConnectorError, type ConnectorIdentity, type ConnectorRoutePrice, type Decoded, type DeployMinaZkAppParams, type DiscoveredIlpPeer, type EVMClaimMessage, type EncryptedArtifact, type EncryptedKeystore, type EnsureOwnedMinaZkAppParams, type EnsureOwnedMinaZkAppResult, type Envelope, EnvelopeError, EnvelopeErrorKind, type EnvelopeHeader, type EnvelopeRequest, type EnvelopeResponse, type EvmClaimDomainContext, type EvmClaimMessage, type EvmClaimVerifyResult, type EvmCooperativeCloseMessage, type EvmReadConsistencyConfig, EvmSigner, type EvmTransferConfig, type ExchangeOutcome, type ExecutionConditionPair, FULFILLMENT_MISMATCH_CODE, FULFILLMENT_MISMATCH_MESSAGE, type FaucetChain, type FundWalletOptions, type FundWalletResult, GIFTWRAP_NONCE_LENGTH, GIFTWRAP_PUBLIC_KEY_LENGTH, GIFTWRAP_SECRET_LENGTH, GIFTWRAP_TYPE_REQUEST, GIFTWRAP_TYPE_RESPONSE, GIFT_WRAP_KIND, GiftWrapAddressError, GiftWrapDecryptError, type GiftWrapEcdh, GiftWrapError, GiftWrapErrorKind, type H402FetchOptions, HashlockConditionMismatchError, HashlockDecryptError, Http402Client, type Http402ClientConfig, HttpConnectorAdmin, type HttpConnectorAdminConfig, HttpIlpClient, type HttpIlpClientConfig, type HttpIlpClientFactory, HttpRuntimeClient, type HttpRuntimeClientConfig, ILP_CLAIM_HEADER, ILP_PEER_ID_HEADER, type IlpSendParams, type IlpSendResultWithFulfillment, type IlpTransportChoice, InMemoryChannelStore, InMemoryPreimageRetentionStore, InMemoryReceivedClaimStore, type IncrementOfferTags, type IncrementPrepare, type IngestAndRevealParams, type IngestAndRevealResult, type IngestReceivedClaimsParams, type IngestReceivedClaimsResult, InsufficientBalanceError, InvalidAddressError, type JobAnswer, type JobHandler, type JobRequest, JsonFileChannelStore, JsonFileReceivedClaimStore, KeyManager, type KeyManagerConfig, MINA_CHANNEL_STATE, type MinaChannelStateReader, type MinaClaimMessage, type MinaClaimSubmitArgs, type MinaClaimSubmitter, type MinaCoSignInputs, type MinaCoSignedClaim, type MinaDepositReader, type MinaOnChainChannelState, type MinaSettlementContext, MinaSettlementError, type MinaSettlementErrorCode, type MinaSettlementResult, type MinaSignaturePair, MinaSigner, type MinaSignerOptions, type MinaTransferConfig, type MinaZkAppDeployRecord, NetworkError, OerError, OerErrorKind, OnChainChannelClient, type OnChainChannelClientConfig, type OpenedRequest, type OrderedBtpSession, type ParsedX402Challenge, type PasskeyInfo, type PreimageRetentionStore, type PublishEventResult, ROLLING_SWAP_DOMAIN_NAME, ROLLING_SWAP_DOMAIN_VERSION, type ReceivedClaimEntry, type ReceivedClaimRejection, type ReceivedClaimRejectionCode, type ReceivedClaimStore, type RequestBlobStorageParams, type RequestBlobStorageResult, type RetainedPreimage, type RetryOptions, type RevealDecision, type RevealFn, type RevealResult, type RevealedClaim, type RolledBackClaim, SEAL_KIND, type SealedExchange, type SealedRequest, SealedResponseError, type SealedResponseErrorKind, type SelectIlpTransportOptions, type SendTransferParams, type SendTransferResult, type SignedBalanceProof, type SolanaChannelClientOptions, type SolanaClaimMessage, SolanaSigner, type SolanaTransferConfig, StaleRpcReadError, type SubmitEvmSettlementParams, type SubmitEvmSettlementResult, type SwapSettlementBuild, type ToonChannelAccept, ToonClient, type ToonClientConfig, ToonClientError, type ToonIdentity, type ToonSigners, type ToonStartResult, type TransferAssetKind, type TransferChain, type TransferConfig, TransferNotDeliveredError, TransferUnsupportedError, UnknownChainError, type UnwrappedGiftWrap, ValidationError, type VaultData, type VerifiedReceivedClaim, type WalletBalance, type WalletBalanceSources, type WalletChainBalances, type WalletTokenAmount, applyDefaults, applyNetworkPresets, assertValidCondition, buildBackupEvent, buildBackupFilter, buildIncrementPrepare, buildMinaCoSignedClaim, buildSettlementInfo, buildSwapSettlements, connectorEdgeBaseUrl, createJobMessageHandler, createO1jsMinaClaimSubmitter, decodeConnectorPublicKey, decodeEnvelope, decodeEnvelopeRequest, decodeEnvelopeResponse, decodeEvmSettlementTx, decodeVarOctetString, decodeVarUint, decryptArtifact, decryptMnemonic, defaultFaucetTimeout, deployMinaChannelZkApp, deriveCondition, deriveFromNsec, deriveFulfillment, deriveFullIdentity, deriveNostrKeyFromMnemonic, encodeEnvelope, encodeEnvelopeRequest, encodeEnvelopeResponse, encodeVarOctetString, encodeVarUint, encryptArtifact, encryptMnemonic, ensureOwnedMinaZkApp, entryToAccumulatedClaim, envelopeHeader, evmClaimDigest, evmCooperativeCloseDigest, extractArweaveTxId, fulfillIncrement, fulfillmentMatchesCondition, fundWallet, generateKeystore, generateMnemonic, generateRandomIdentity, getNetworkStatus, hasSettlementMetadata, httpEndpointToBtpUrl, importKeystore, ingestAndReveal, ingestReceivedClaims, isInsufficientGasError, isPrfSupported, isZeroCondition, loadKeystore, localGiftWrapEcdh, looksLikeSealedResponse, mintExecutionCondition, openRequest, openResponse, parseBackupPayload, parseClaimStateResponse, parseConnectorIdentity, parseConnectorRoutePrice, parseEvmChainId, parseX402Body, parseX402Challenge, proxyIlpEndpoint, readDiscoveredIlpPeer, readEvmNativeBalance, readEvmTokenBalance, readExchangeOutcome, readMinaBalance, readMinaChannelState, readMinaDepositTotal, readSolanaNativeBalance, readSolanaTokenBalance, readWalletBalances, recoverEvmClaimSigner, requestBlobStorage, sealExchange, sealRequest, sealRequestWithRandomness, sealResponse, sealResponseWithRandomness, selectIlpTransport, sendTransfer, submitEvmSettlement, submitMinaSettlement, unwrapGiftWrapWithKey, validateConfig, validateMnemonic, verifyEvmClaimSignature, withRetry, writeKeystoreFile };
|