@paybox-sh/sdk 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -14
- package/SKILL.md +118 -0
- package/dist/{chunk-EBB4HNOB.js → chunk-7VW4QMV4.js} +304 -125
- package/dist/chunk-7VW4QMV4.js.map +1 -0
- package/dist/cli.js +24 -34
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +131 -51
- package/dist/index.js +1 -1
- package/package.json +12 -4
- package/dist/chunk-EBB4HNOB.js.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -38,10 +38,44 @@ interface PortfolioArgs {
|
|
|
38
38
|
/** Comma-separated network IDs, e.g. "1,8453". Omit to auto-detect. */
|
|
39
39
|
networkIds?: string;
|
|
40
40
|
}
|
|
41
|
+
interface VerifySolanaBalanceArgs$1 {
|
|
42
|
+
address: string;
|
|
43
|
+
tokenMint: string;
|
|
44
|
+
transactionSignature: string;
|
|
45
|
+
}
|
|
46
|
+
interface VerifySolanaBalanceResult {
|
|
47
|
+
address: string;
|
|
48
|
+
token_mint: string;
|
|
49
|
+
transaction_signature: string;
|
|
50
|
+
source: "alchemy_rpc";
|
|
51
|
+
network: "solana-mainnet";
|
|
52
|
+
transaction: {
|
|
53
|
+
slot: number;
|
|
54
|
+
pre_balance: string;
|
|
55
|
+
post_balance: string;
|
|
56
|
+
delta: string;
|
|
57
|
+
};
|
|
58
|
+
balance: {
|
|
59
|
+
amount: string;
|
|
60
|
+
decimals: number;
|
|
61
|
+
ui_amount_string: string;
|
|
62
|
+
};
|
|
63
|
+
observed_slot: number;
|
|
64
|
+
read_covers_transaction: true;
|
|
65
|
+
as_of: string;
|
|
66
|
+
}
|
|
41
67
|
interface DiscoverServicesOptions {
|
|
42
|
-
/**
|
|
68
|
+
/** Catalogs to search. Defaults to both. */
|
|
69
|
+
network?: "all" | "base" | "solana";
|
|
70
|
+
/** @deprecated Accepted for compatibility but not advertised to agents. */
|
|
43
71
|
raw?: boolean;
|
|
44
72
|
}
|
|
73
|
+
interface DiscoverServicesPageOptions extends DiscoverServicesOptions {
|
|
74
|
+
/** Results per page. Defaults to 10; maximum 25. */
|
|
75
|
+
limit?: number;
|
|
76
|
+
/** Opaque continuation from a prior page. */
|
|
77
|
+
cursor?: string;
|
|
78
|
+
}
|
|
45
79
|
type RequestStatus = "pending_approval" | "pending_signature" | "pending_settlement" | "pending_confirmation" | "success" | "denied" | "error";
|
|
46
80
|
type OutputType = "payment_token" | "signature" | "tx_hash" | "secret_token" | "raw_secret";
|
|
47
81
|
interface CredentialOutput {
|
|
@@ -62,6 +96,12 @@ interface AgentResponse {
|
|
|
62
96
|
output: CredentialOutput | null;
|
|
63
97
|
approval_id: string | null;
|
|
64
98
|
error: string | null;
|
|
99
|
+
/** SPE-456: set on a terminal `error`/`denied` when the failure was an expiry
|
|
100
|
+
* (the signing/approval window elapsed and nothing was signed or spent), so
|
|
101
|
+
* re-issuing the same request is the correct recovery. `retry_hint` is plain
|
|
102
|
+
* guidance. Absent on non-expiry outcomes. */
|
|
103
|
+
retryable?: boolean;
|
|
104
|
+
retry_hint?: string | null;
|
|
65
105
|
}
|
|
66
106
|
interface CredentialSummary {
|
|
67
107
|
id: string;
|
|
@@ -75,13 +115,27 @@ interface CredentialSummary {
|
|
|
75
115
|
}
|
|
76
116
|
interface Grant {
|
|
77
117
|
credential_id: string;
|
|
78
|
-
approval_mode: "always_approve" | "autonomous";
|
|
118
|
+
approval_mode: "always_approve" | "iframe" | "autonomous";
|
|
79
119
|
[key: string]: unknown;
|
|
80
120
|
}
|
|
81
121
|
interface ClientGrantSummary {
|
|
82
122
|
credential: CredentialSummary;
|
|
83
123
|
grant: Grant;
|
|
84
124
|
}
|
|
125
|
+
/** An active credential the user owns but has not granted this connector.
|
|
126
|
+
* Carries identity + safe display metadata (wallet chain family, card
|
|
127
|
+
* brand/last4) so the connector can request a specific credential by id; never
|
|
128
|
+
* card tokens or secret material. */
|
|
129
|
+
interface UngrantedCredential {
|
|
130
|
+
credential_id: string;
|
|
131
|
+
name: string;
|
|
132
|
+
kind: "card" | "wallet" | "secret";
|
|
133
|
+
metadata: Record<string, unknown>;
|
|
134
|
+
}
|
|
135
|
+
interface ClientCredentialList {
|
|
136
|
+
credentials: ClientGrantSummary[];
|
|
137
|
+
ungranted: UngrantedCredential[];
|
|
138
|
+
}
|
|
85
139
|
/** The wallet binding the server echoes for a wallet-sign / resolve. Mirrors
|
|
86
140
|
* `WalletBinding` in server/src/agent.rs (key_id/derivation_path may be null
|
|
87
141
|
* for an unprovisioned wallet). */
|
|
@@ -100,13 +154,15 @@ interface SwapPlan {
|
|
|
100
154
|
quote: Record<string, unknown>;
|
|
101
155
|
txs: PlanTx[];
|
|
102
156
|
}
|
|
103
|
-
/** `POST /agent/swap` response
|
|
157
|
+
/** `POST /agent/swap` response. The sign-ready plan is present only while the
|
|
158
|
+
* request is awaiting approval or signature; terminal responses return null. */
|
|
104
159
|
interface SwapResult {
|
|
105
160
|
response: AgentResponse;
|
|
106
|
-
plan: SwapPlan;
|
|
161
|
+
plan: SwapPlan | null;
|
|
107
162
|
}
|
|
108
|
-
/** `POST /agent/wallet-sign` response
|
|
109
|
-
*
|
|
163
|
+
/** `POST /agent/wallet-sign` response. The wallet binding is present only while
|
|
164
|
+
* approval or signature is pending, so the signer can sign without a separate
|
|
165
|
+
* resolve round-trip; terminal responses return null. */
|
|
110
166
|
interface WalletSignResult {
|
|
111
167
|
response: AgentResponse;
|
|
112
168
|
binding: BindingResponse | null;
|
|
@@ -139,20 +195,32 @@ interface X402Plan {
|
|
|
139
195
|
};
|
|
140
196
|
x402: Record<string, unknown>;
|
|
141
197
|
}
|
|
142
|
-
/** `POST /agent/x402` | `/agent/use-service` response
|
|
143
|
-
* success, header mode puts the
|
|
198
|
+
/** `POST /agent/x402` | `/agent/use-service` response. The plan is present only
|
|
199
|
+
* while approval or signature is pending. On success, header mode puts the
|
|
200
|
+
* X-PAYMENT header in
|
|
144
201
|
* `response.output.value.x_payment`; gateway mode puts the resource's reply in
|
|
145
202
|
* `response.output.value.response`. */
|
|
146
203
|
interface X402Result {
|
|
147
204
|
response: AgentResponse;
|
|
148
|
-
plan: X402Plan;
|
|
205
|
+
plan: X402Plan | null;
|
|
149
206
|
}
|
|
150
207
|
/** One curated x402 service (the `discover_services` tool / `/agent/services`):
|
|
151
208
|
* where it lives, a human description, and its `accepts` PaymentRequirements. */
|
|
152
209
|
interface ServiceSummary {
|
|
153
210
|
resource: string;
|
|
154
211
|
description: string | null;
|
|
155
|
-
accepts:
|
|
212
|
+
accepts: Array<{
|
|
213
|
+
scheme: string;
|
|
214
|
+
network: string;
|
|
215
|
+
asset: string;
|
|
216
|
+
amount: string;
|
|
217
|
+
}>;
|
|
218
|
+
contract_uri?: string;
|
|
219
|
+
}
|
|
220
|
+
interface DiscoverServicesPage {
|
|
221
|
+
services: ServiceSummary[];
|
|
222
|
+
has_more: boolean;
|
|
223
|
+
next_cursor?: string;
|
|
156
224
|
}
|
|
157
225
|
/** `POST /agent/account-change` (the `request_account_change` tool): a pure
|
|
158
226
|
* launcher. Surface `manage_url` to the user — they edit this client's access
|
|
@@ -166,7 +234,9 @@ interface AccountChangeResult {
|
|
|
166
234
|
interface BuyLinkArgs {
|
|
167
235
|
/** A granted wallet credential to fund. */
|
|
168
236
|
credentialId: string;
|
|
169
|
-
/**
|
|
237
|
+
/** Exact network. Defaults to Base for EVM or Solana mainnet for Solana. */
|
|
238
|
+
destinationChain?: "eip155:8453" | "eip155:1" | "solana:mainnet";
|
|
239
|
+
/** Enabled MoonPay code matching the destination's exact network. */
|
|
170
240
|
currencyCode?: string;
|
|
171
241
|
/** Prefill amount in USD. */
|
|
172
242
|
amountUsd?: number;
|
|
@@ -177,6 +247,7 @@ interface BuyLinkResult {
|
|
|
177
247
|
url: string;
|
|
178
248
|
currency_code: string;
|
|
179
249
|
wallet_address: string;
|
|
250
|
+
network: "eip155:8453" | "eip155:1" | "solana:mainnet";
|
|
180
251
|
}
|
|
181
252
|
interface WorldMarketsArgs {
|
|
182
253
|
/** Return the events list (each event groups its markets) instead of markets. */
|
|
@@ -195,18 +266,6 @@ interface WorldPricesArgs {
|
|
|
195
266
|
endTs: number;
|
|
196
267
|
resolution?: number;
|
|
197
268
|
}
|
|
198
|
-
interface WorldTradeArgs {
|
|
199
|
-
/** A granted wallet credential (Solana). */
|
|
200
|
-
credentialId: string;
|
|
201
|
-
/** The outcome mint to trade. */
|
|
202
|
-
marketMint: string;
|
|
203
|
-
/** "buy" | "sell" trade at market; "redeem" pays out a settled position. */
|
|
204
|
-
side: "buy" | "sell" | "redeem";
|
|
205
|
-
size: string;
|
|
206
|
-
/** Ignored for redeem (no price slippage at settlement). Default 50. */
|
|
207
|
-
slippageBps?: number;
|
|
208
|
-
valueCents?: number;
|
|
209
|
-
}
|
|
210
269
|
|
|
211
270
|
declare class PayboxError extends Error {
|
|
212
271
|
readonly status: number;
|
|
@@ -227,10 +286,7 @@ interface PayboxClientOptions {
|
|
|
227
286
|
interface SignOptions {
|
|
228
287
|
/** Sign in-process when the request clears to `pending_signature`. Default true. */
|
|
229
288
|
autoSign?: boolean;
|
|
230
|
-
/**
|
|
231
|
-
* force-approved op like a World trade), wait for the user's passkey approval
|
|
232
|
-
* and then sign in-process — the SDK's headless equivalent of the signing
|
|
233
|
-
* window's post-approval sign. Default false (return the pending response). */
|
|
289
|
+
/** Wait for passkey approval and then sign in-process. Default false. */
|
|
234
290
|
waitForApproval?: boolean | {
|
|
235
291
|
intervalMs?: number;
|
|
236
292
|
timeoutMs?: number;
|
|
@@ -245,15 +301,20 @@ declare class PayboxClient {
|
|
|
245
301
|
constructor(options?: PayboxClientOptions);
|
|
246
302
|
/** Build a client from `~/.config/paybox/config.json` + env, with overrides. */
|
|
247
303
|
static fromConfig(overrides?: PayboxClientOptions): PayboxClient;
|
|
248
|
-
|
|
304
|
+
private signingCreds;
|
|
305
|
+
/** Whether in-process signing is available (a parseable `pbxk1.` key is set). */
|
|
249
306
|
get canSign(): boolean;
|
|
250
307
|
private bearer;
|
|
251
308
|
private request;
|
|
252
309
|
private readonly poster;
|
|
253
|
-
/** List
|
|
254
|
-
|
|
310
|
+
/** List granted credentials plus the `ungranted` credentials (id, name, kind,
|
|
311
|
+
* safe metadata) the user owns but hasn't granted this connector. */
|
|
312
|
+
listCredentials(): Promise<ClientCredentialList>;
|
|
255
313
|
/** Token balances across chains (the `get_portfolio` tool). */
|
|
256
314
|
getPortfolio(args: PortfolioArgs): Promise<unknown>;
|
|
315
|
+
/** Verify one confirmed Solana transaction's exact wallet/mint effect, then
|
|
316
|
+
* read the current balance at or after its slot (`verify_solana_balance`). */
|
|
317
|
+
verifySolanaBalance(args: VerifySolanaBalanceArgs$1): Promise<VerifySolanaBalanceResult>;
|
|
257
318
|
/** Charge a card credential (the `request_payment` tool). */
|
|
258
319
|
requestPayment(args: PaymentArgs): Promise<AgentResponse>;
|
|
259
320
|
/** Reveal a secret credential (the `request_secret` tool). */
|
|
@@ -261,27 +322,41 @@ declare class PayboxClient {
|
|
|
261
322
|
/** Sign with a wallet credential (the `request_wallet_sign` tool). Signs
|
|
262
323
|
* in-process and returns the completed request when a signing key is set and
|
|
263
324
|
* the request clears immediately; otherwise returns the pending response.
|
|
264
|
-
* Uses `/agent/wallet-sign`, which echoes the wallet binding
|
|
265
|
-
* need not resolve it
|
|
325
|
+
* Uses `/agent/wallet-sign`, which echoes the wallet binding only while
|
|
326
|
+
* approval or signature is pending so the signer need not resolve it
|
|
327
|
+
* separately. Terminal responses carry a null binding. */
|
|
266
328
|
requestWalletSign(args: WalletSignArgs, opts?: SignOptions): Promise<AgentResponse>;
|
|
267
329
|
/** Swap tokens from a wallet credential (the `request_swap` tool). Returns the
|
|
268
|
-
* parked response
|
|
269
|
-
*
|
|
330
|
+
* parked response and its sign-ready plan while approval or signature is
|
|
331
|
+
* pending; terminal responses carry a null plan. Signs + submits in-process
|
|
332
|
+
* when a signing key is set and the swap cleared immediately. */
|
|
270
333
|
requestSwap(args: SwapArgs, opts?: SignOptions): Promise<SwapResult>;
|
|
271
|
-
/**
|
|
272
|
-
*
|
|
273
|
-
*
|
|
274
|
-
*
|
|
275
|
-
* first, so a long approval dwell never signs stale bytes. */
|
|
334
|
+
/** Complete a swap request: optionally wait out a `pending_approval` dwell,
|
|
335
|
+
* then sign the plan in-process and submit envelopes. Signing first refreshes
|
|
336
|
+
* the parked request via `/agent/requests/{id}/refresh`, so a long approval
|
|
337
|
+
* dwell never signs stale bytes. */
|
|
276
338
|
private completeSwap;
|
|
277
339
|
/** Poll while the request sits in `pending_approval` (the user is approving
|
|
278
340
|
* with their passkey); returns the first non-approval state. */
|
|
279
341
|
private waitWhileApproval;
|
|
280
|
-
/**
|
|
281
|
-
* `
|
|
282
|
-
*
|
|
283
|
-
*
|
|
342
|
+
/** Run an operation and, if it terminates on a server-marked expiry
|
|
343
|
+
* (`retryable` on a terminal `error`/`denied`: the window elapsed and nothing
|
|
344
|
+
* was signed or spent), re-issue it exactly once (SPE-456). Never loops: the
|
|
345
|
+
* second attempt's result is returned as-is. */
|
|
346
|
+
private withExpiryRetry;
|
|
347
|
+
/** Sign a parked request; if the sign/submit call fails, reconcile against the
|
|
348
|
+
* authoritative state once (SPE-456). The server leaves a pre-broadcast
|
|
349
|
+
* completion failure recoverable — the claim is released and the row stays
|
|
350
|
+
* `pending_signature` — so re-sign a still-open request a single time; a
|
|
351
|
+
* terminal or already-broadcast row is left as-is for the caller to read (and
|
|
352
|
+
* for `withExpiryRetry` to re-issue if it is retryable). Bounded to one extra
|
|
353
|
+
* attempt: a second failure propagates. */
|
|
354
|
+
private signWithReconcile;
|
|
355
|
+
/** Discover x402 services with the original array-returning response. */
|
|
284
356
|
discoverServices(query?: string, opts?: DiscoverServicesOptions): Promise<ServiceSummary[]>;
|
|
357
|
+
/** Discover one bounded page of x402 services. Reuse the returned cursor with
|
|
358
|
+
* the same query and network while `has_more` is true. */
|
|
359
|
+
discoverServicesPage(query?: string, opts?: DiscoverServicesPageOptions): Promise<DiscoverServicesPage>;
|
|
285
360
|
/** Pay a paid x402 endpoint from a wallet credential (the `pay_x402` tool,
|
|
286
361
|
* header mode). Signs in-process when a signing key is set and the payment
|
|
287
362
|
* clears immediately — then the X-PAYMENT header is on the completed
|
|
@@ -319,14 +394,11 @@ declare class PayboxClient {
|
|
|
319
394
|
/** Filter addresses down to World outcome mints (the
|
|
320
395
|
* `world_filter_outcome_mints` tool). */
|
|
321
396
|
worldFilterOutcomeMints(addresses: string[]): Promise<unknown>;
|
|
322
|
-
/**
|
|
397
|
+
/** A wallet's World prediction-market positions: classified `positions` /
|
|
398
|
+
* `settled` entries (each with a `position_result`) plus `settlement_cash`
|
|
399
|
+
* for a settled winner's CASH cash-out (swap CASH to USDC via request_swap).
|
|
400
|
+
* The `world_positions` tool. */
|
|
323
401
|
worldPositions(address: string): Promise<unknown>;
|
|
324
|
-
/** Trade a World prediction market (the `world_buy_outcome` /
|
|
325
|
-
* `world_change_position` / `world_redeem` tools). Always parks as
|
|
326
|
-
* `pending_approval` (trades are force-approved); pass
|
|
327
|
-
* `{ waitForApproval: true }` to wait for the user's passkey approval and
|
|
328
|
-
* sign in-process. */
|
|
329
|
-
worldTrade(args: WorldTradeArgs, opts?: SignOptions): Promise<SwapResult>;
|
|
330
402
|
/** Hyperliquid spot markets (the `hyperliquid_markets` tool). */
|
|
331
403
|
hyperliquidMarkets(): Promise<unknown>;
|
|
332
404
|
/** Hyperliquid spot prices (the `hyperliquid_prices` tool). */
|
|
@@ -335,6 +407,9 @@ declare class PayboxClient {
|
|
|
335
407
|
hyperliquidToken(name: string): Promise<unknown>;
|
|
336
408
|
/** Poll a request's status (the `get_request` tool). */
|
|
337
409
|
getRequest(requestId: string): Promise<AgentResponse>;
|
|
410
|
+
/** After in-process sign, `--wait` polls through settlement/confirmation;
|
|
411
|
+
* without it, return the first snapshot (the historical no-wait contract). */
|
|
412
|
+
private requestAfterSign;
|
|
338
413
|
/** Poll until the request leaves a pending state (or the timeout elapses). */
|
|
339
414
|
waitForRequest(requestId: string, opts?: {
|
|
340
415
|
intervalMs?: number;
|
|
@@ -412,5 +487,10 @@ interface GetPortfolioArgs {
|
|
|
412
487
|
address: string;
|
|
413
488
|
network_ids?: string | null;
|
|
414
489
|
}
|
|
490
|
+
interface VerifySolanaBalanceArgs {
|
|
491
|
+
address: string;
|
|
492
|
+
token_mint: string;
|
|
493
|
+
transaction_signature: string;
|
|
494
|
+
}
|
|
415
495
|
|
|
416
|
-
export { type AccountChangeResult, type AgentResponse, type BindingResponse, type BuyLinkArgs, type BuyLinkResult, type ClientGrantSummary, type CredentialOutput, type CredentialSummary, type DiscoverServicesOptions, type GetPortfolioArgs, type Grant, type LoginOptions, type OAuthTokens, type OutputType, PayboxClient, type PayboxClientOptions, PayboxError, type PaymentArgs, type PortfolioArgs, type RequestPaymentArgs, type RequestSecretArgs, type RequestStatus, type RequestSwapArgs, type RequestWalletSignArgs, type SecretArgs, type ServiceSummary, type SignOptions, type StoredConfig, type SwapArgs, type SwapPlan, type SwapResult, type UseServiceArgs, type WalletSignArgs, type WalletSignResult, type WorldMarketsArgs, type WorldPricesArgs, type
|
|
496
|
+
export { type AccountChangeResult, type AgentResponse, type BindingResponse, type BuyLinkArgs, type BuyLinkResult, type ClientCredentialList, type ClientGrantSummary, type CredentialOutput, type CredentialSummary, type DiscoverServicesOptions, type GetPortfolioArgs, type Grant, type LoginOptions, type OAuthTokens, type OutputType, PayboxClient, type PayboxClientOptions, PayboxError, type PaymentArgs, type PortfolioArgs, type RequestPaymentArgs, type RequestSecretArgs, type RequestStatus, type RequestSwapArgs, type RequestWalletSignArgs, type SecretArgs, type ServiceSummary, type SignOptions, type StoredConfig, type SwapArgs, type SwapPlan, type SwapResult, type UngrantedCredential, type UseServiceArgs, type VerifySolanaBalanceArgs$1 as VerifySolanaBalanceArgs, type VerifySolanaBalanceResult, type VerifySolanaBalanceArgs as VerifySolanaBalanceWireArgs, type WalletSignArgs, type WalletSignResult, type WorldMarketsArgs, type WorldPricesArgs, type X402Args, type X402Plan, type X402Result, configFile, credsFromToken, loadConfig, loginLoopback, mcpResource, refreshTokens, saveConfig };
|
package/dist/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@paybox-sh/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "Typed Node SDK + `paybox` CLI for the
|
|
5
|
+
"description": "Typed Node SDK + `paybox` CLI for the PayBox agent API. Mirrors the MCP tool surface (list_credentials, request_payment, request_wallet_sign, request_secret, request_swap, get_portfolio, verify_solana_balance, get_request) over REST, with in-process non-custodial wallet signing.",
|
|
6
6
|
"license": "Apache-2.0",
|
|
7
7
|
"repository": {
|
|
8
8
|
"type": "git",
|
|
@@ -37,7 +37,8 @@
|
|
|
37
37
|
}
|
|
38
38
|
},
|
|
39
39
|
"files": [
|
|
40
|
-
"dist"
|
|
40
|
+
"dist",
|
|
41
|
+
"SKILL.md"
|
|
41
42
|
],
|
|
42
43
|
"engines": {
|
|
43
44
|
"node": ">=18"
|
|
@@ -45,12 +46,13 @@
|
|
|
45
46
|
"scripts": {
|
|
46
47
|
"build": "tsup",
|
|
47
48
|
"dev": "tsup --watch",
|
|
49
|
+
"test": "tsx --test test/*.test.ts",
|
|
48
50
|
"typecheck": "tsc --noEmit",
|
|
49
51
|
"gen": "tsx scripts/generate.ts",
|
|
50
52
|
"prepublishOnly": "pnpm build"
|
|
51
53
|
},
|
|
52
54
|
"dependencies": {
|
|
53
|
-
"@moon-x/core": "0.
|
|
55
|
+
"@moon-x/core": "0.17.0",
|
|
54
56
|
"@moon-x/evm-adapter": "0.3.0",
|
|
55
57
|
"@moon-x/solana-adapter": "0.3.0",
|
|
56
58
|
"@solana/web3.js": "1.98.4",
|
|
@@ -68,5 +70,11 @@
|
|
|
68
70
|
"tsup": "8.3.5",
|
|
69
71
|
"tsx": "4.19.2",
|
|
70
72
|
"typescript": "5.9.3"
|
|
73
|
+
},
|
|
74
|
+
"pnpm": {
|
|
75
|
+
"comment:overrides": "ASEC-8563 (GHSA-67mh-4wv8-2f99): force tsup's transitive esbuild off 0.24.2 so no flagged version remains in this lockfile. Targets 0.24.2 only; tsx's 0.23.1 is unaffected.",
|
|
76
|
+
"overrides": {
|
|
77
|
+
"esbuild@0.24.2": "0.25.0"
|
|
78
|
+
}
|
|
71
79
|
}
|
|
72
80
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/auth.ts","../src/config.ts","../node_modules/.pnpm/@paybox+mcp-app@file+..+mcp-app_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__bn.js@5.2.3_ac1e09a20c76a1143611be5dd3d4f9db/node_modules/@paybox/mcp-app/src/creds.ts","../node_modules/.pnpm/@paybox+mcp-app@file+..+mcp-app_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__bn.js@5.2.3_ac1e09a20c76a1143611be5dd3d4f9db/node_modules/@paybox/mcp-app/src/sign.ts","../src/signer.ts","../src/client.ts"],"sourcesContent":["// OAuth 2.1 + PKCE loopback login for the CLI, and refresh-token rotation.\n//\n// The server allows http://127.0.0.1:* loopback redirects, dynamic ports, public\n// (no-secret) PKCE clients, and refresh tokens for `offline_access` — so this is\n// a standard loopback flow needing no server changes. The user approves with a\n// passkey in the browser (the existing app consent flow); the CLI never sees a\n// secret to copy.\n\nimport { spawn } from \"node:child_process\";\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { createServer } from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\n\nimport type { OAuthTokens } from \"./config.js\";\n\n/** The MCP resource the access token is audience-bound to. */\nexport function mcpResource(baseUrl: string): string {\n return `${baseUrl.replace(/\\/+$/, \"\")}/mcp`;\n}\n\n/** The Paybox app origin (where signing keys are provisioned), derived from the\n * API origin by swapping the `api.` subdomain for `app.` (e.g.\n * api.paybox.sh → app.paybox.sh). Returns null when it can't be derived (e.g.\n * localhost) — pass an explicit override then. */\nexport function appBaseFrom(baseUrl: string, override?: string): string | null {\n if (override) return override.replace(/\\/+$/, \"\");\n const m = baseUrl.replace(/\\/+$/, \"\").match(/^(https?:\\/\\/)api\\.(.+)$/);\n return m ? `${m[1]}app.${m[2]}` : null;\n}\n\n/** Read the paybox agent client id (`cid`) from an OAuth access token (JWT). */\nexport function agentClientId(accessToken: string): string | null {\n const payload = accessToken.split(\".\")[1];\n if (!payload) return null;\n try {\n const claims = JSON.parse(Buffer.from(payload, \"base64url\").toString(\"utf8\")) as {\n cid?: string;\n };\n return claims.cid ?? null;\n } catch {\n return null;\n }\n}\n\ninterface AsMetadata {\n registration_endpoint: string;\n authorization_endpoint: string;\n token_endpoint: string;\n}\n\nasync function metadata(baseUrl: string): Promise<AsMetadata> {\n const url = `${baseUrl.replace(/\\/+$/, \"\")}/.well-known/oauth-authorization-server`;\n const res = await fetch(url);\n if (!res.ok) {\n throw new Error(`could not read OAuth metadata from ${url} (${res.status})`);\n }\n return (await res.json()) as AsMetadata;\n}\n\nfunction base64url(b: Buffer): string {\n return b.toString(\"base64url\");\n}\n\nfunction pkce(): { verifier: string; challenge: string } {\n const verifier = base64url(randomBytes(32));\n const challenge = base64url(createHash(\"sha256\").update(verifier).digest());\n return { verifier, challenge };\n}\n\nexport function openBrowser(url: string): void {\n // On Windows, `cmd /c start <url>` mis-parses the OAuth URL: cmd treats the\n // `&` before each query param as a command separator. rundll32 opens the\n // default browser with the URL passed verbatim, no shell parsing.\n const [cmd, args] =\n process.platform === \"darwin\"\n ? ([\"open\", [url]] as const)\n : process.platform === \"win32\"\n ? ([\"rundll32\", [\"url.dll,FileProtocolHandler\", url]] as const)\n : ([\"xdg-open\", [url]] as const);\n try {\n spawn(cmd, [...args], { stdio: \"ignore\", detached: true }).unref();\n } catch {\n /* fall back to the printed URL */\n }\n}\n\nconst CALLBACK_PAGE =\n \"<!doctype html><meta charset=utf-8><title>Paybox</title>\" +\n \"<body style=\\\"font:16px system-ui;padding:3rem;text-align:center\\\">\" +\n \"<h2>Paybox CLI connected</h2><p>You can close this tab and return to the terminal.</p>\";\n\nexport interface LoginOptions {\n scope?: string;\n clientName?: string;\n /** Sink for the \"open this URL\" prompt; defaults to console.error. */\n log?: (msg: string) => void;\n /** Abort with an error if no approval arrives in this long. Default 5 min. */\n timeoutMs?: number;\n}\n\nexport async function loginLoopback(\n baseUrl: string,\n opts: LoginOptions = {},\n): Promise<OAuthTokens> {\n const scope = opts.scope ?? \"mcp offline_access\";\n const clientName = opts.clientName ?? \"Paybox CLI\";\n const log = opts.log ?? ((m: string) => console.error(m));\n const meta = await metadata(baseUrl);\n const resource = mcpResource(baseUrl);\n\n let resolveCode: (v: { code: string; state: string | null }) => void;\n let rejectCode: (e: Error) => void;\n const codePromise = new Promise<{ code: string; state: string | null }>((res, rej) => {\n resolveCode = res;\n rejectCode = rej;\n });\n\n const server = createServer((req, res) => {\n const u = new URL(req.url ?? \"/\", \"http://127.0.0.1\");\n if (u.pathname !== \"/callback\") {\n res.writeHead(404).end();\n return;\n }\n res.writeHead(200, { \"content-type\": \"text/html\" }).end(CALLBACK_PAGE);\n const code = u.searchParams.get(\"code\");\n if (code) resolveCode({ code, state: u.searchParams.get(\"state\") });\n else rejectCode(new Error(u.searchParams.get(\"error\") ?? \"authorization failed\"));\n });\n await new Promise<void>((r) => server.listen(0, \"127.0.0.1\", r));\n const port = (server.address() as AddressInfo).port;\n const redirectUri = `http://127.0.0.1:${port}/callback`;\n\n const timeoutMs = opts.timeoutMs ?? 300_000;\n const timer = setTimeout(\n () => rejectCode(new Error(`login timed out after ${Math.round(timeoutMs / 1000)}s — no approval received`)),\n timeoutMs,\n );\n timer.unref();\n\n try {\n const reg = await fetch(meta.registration_endpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n client_name: clientName,\n redirect_uris: [redirectUri],\n token_endpoint_auth_method: \"none\",\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n }),\n });\n if (!reg.ok) throw new Error(`client registration failed (${reg.status}): ${await reg.text()}`);\n const { client_id: clientId } = (await reg.json()) as { client_id: string };\n\n const { verifier, challenge } = pkce();\n const state = base64url(randomBytes(16));\n const authUrl =\n `${meta.authorization_endpoint}?response_type=code` +\n `&client_id=${encodeURIComponent(clientId)}` +\n `&redirect_uri=${encodeURIComponent(redirectUri)}` +\n `&code_challenge=${challenge}&code_challenge_method=S256` +\n `&scope=${encodeURIComponent(scope)}` +\n `&state=${state}&resource=${encodeURIComponent(resource)}`;\n\n log(`Opening your browser to approve access:\\n ${authUrl}\\n`);\n openBrowser(authUrl);\n\n const { code, state: returnedState } = await codePromise;\n if (returnedState !== state) throw new Error(\"OAuth state mismatch — aborting\");\n\n const form = new URLSearchParams({\n grant_type: \"authorization_code\",\n code,\n redirect_uri: redirectUri,\n client_id: clientId,\n code_verifier: verifier,\n resource,\n });\n const tok = await fetch(meta.token_endpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\" },\n body: form,\n });\n if (!tok.ok) throw new Error(`token exchange failed (${tok.status}): ${await tok.text()}`);\n const t = (await tok.json()) as {\n access_token: string;\n refresh_token?: string;\n expires_in?: number;\n };\n return {\n clientId,\n accessToken: t.access_token,\n refreshToken: t.refresh_token,\n expiresAt: t.expires_in ? Date.now() + t.expires_in * 1000 : undefined,\n resource,\n };\n } finally {\n clearTimeout(timer);\n server.close();\n }\n}\n\nexport async function refreshTokens(baseUrl: string, current: OAuthTokens): Promise<OAuthTokens> {\n if (!current.refreshToken) throw new Error(\"no refresh token — run `paybox login` again\");\n const meta = await metadata(baseUrl);\n const resource = current.resource ?? mcpResource(baseUrl);\n const form = new URLSearchParams({\n grant_type: \"refresh_token\",\n refresh_token: current.refreshToken,\n client_id: current.clientId,\n resource,\n });\n const res = await fetch(meta.token_endpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\" },\n body: form,\n });\n if (!res.ok) throw new Error(`token refresh failed (${res.status}): ${await res.text()}`);\n const t = (await res.json()) as {\n access_token: string;\n refresh_token?: string;\n expires_in?: number;\n };\n return {\n ...current,\n accessToken: t.access_token,\n refreshToken: t.refresh_token ?? current.refreshToken,\n expiresAt: t.expires_in ? Date.now() + t.expires_in * 1000 : undefined,\n resource,\n };\n}\n","// On-disk config: OAuth tokens, an optional pbx_live_ key, and an optional\n// pbxk1. signing key. Stored at ~/.config/paybox/config.json, mode 0600 (the\n// signing key is as sensitive as the iframe's localStorage copy).\n\nimport { chmodSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport interface OAuthTokens {\n clientId: string;\n accessToken: string;\n refreshToken?: string;\n /** Epoch millis the access token expires. */\n expiresAt?: number;\n /** The audience the token is bound to (`<baseUrl>/mcp`). */\n resource: string;\n}\n\nexport interface StoredConfig {\n baseUrl?: string;\n /** Paybox app origin used for signing-key provisioning (derived from baseUrl\n * when unset). */\n appUrl?: string;\n apiKey?: string;\n oauth?: OAuthTokens;\n signingKey?: string;\n}\n\nexport function configDir(): string {\n if (process.env.PAYBOX_CONFIG_DIR) return process.env.PAYBOX_CONFIG_DIR;\n const base = process.env.XDG_CONFIG_HOME ?? join(homedir(), \".config\");\n return join(base, \"paybox\");\n}\n\nexport function configFile(): string {\n return join(configDir(), \"config.json\");\n}\n\nexport function loadConfig(): StoredConfig {\n try {\n return JSON.parse(readFileSync(configFile(), \"utf8\")) as StoredConfig;\n } catch {\n return {};\n }\n}\n\nexport function saveConfig(config: StoredConfig): void {\n // 0700/0600 protect the signing key + refresh token on POSIX. On Windows the\n // mode bits don't set ACLs (see README) — the file is not access-restricted.\n mkdirSync(configDir(), { recursive: true, mode: 0o700 });\n writeFileSync(configFile(), `${JSON.stringify(config, null, 2)}\\n`, { mode: 0o600 });\n // writeFileSync's mode only applies on create; chmod also re-tightens an\n // existing file on overwrite. Skip it on Windows where it's a no-op.\n if (process.platform !== \"win32\") chmodSync(configFile(), 0o600);\n}\n","// localStorage-backed credential store.\n//\n// The agent's MoonX ephemeral-signer KEYPAIR lives ONLY here, in this iframe's\n// localStorage, scoped to the server-declared stable origin (`_meta.ui.domain`).\n// It is read into memory only to produce a signature and is sent ONLY to the\n// MoonX API — never to paybox or the AI assistant.\n//\n// Note what is NOT here: the `walletId` (MoonX `provider_wallet_id`). That is\n// not secret and paybox already holds it from the granted credential, so it\n// rides the `request_wallet_sign` operation instead of the pasted key. The user\n// therefore only pastes one thing: a single token carrying the keypair.\n\nconst STORAGE_KEY = \"paybox.walletSign.creds.v2\";\n\n/** The one-string token prefix. The body is base64url(JSON{p,s}). */\nexport const TOKEN_PREFIX = \"pbxk1.\";\n\n/** The agent's MoonX ephemeral-signer keypair. */\nexport interface Creds {\n /** Ephemeral-signer API public key, hex (optional 0x prefix). */\n apiPubHex: string;\n /** Ephemeral-signer API private key, hex (optional 0x prefix). */\n apiPrivHex: string;\n /** Epoch millis the credential was saved. */\n savedAt: number;\n}\n\n/**\n * Feature-detect a usable localStorage. Some hosts sandbox the iframe with an\n * opaque origin where storage access throws; we degrade to in-session entry.\n */\nexport function hasStorage(): boolean {\n try {\n const probe = \"__paybox_probe__\";\n window.localStorage.setItem(probe, \"1\");\n window.localStorage.removeItem(probe);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Load saved creds, or null if absent / unreadable / malformed. */\nexport function load(): Creds | null {\n try {\n const raw = window.localStorage.getItem(STORAGE_KEY);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as Partial<Creds>;\n if (\n typeof parsed.apiPubHex === \"string\" &&\n typeof parsed.apiPrivHex === \"string\" &&\n parsed.apiPubHex &&\n parsed.apiPrivHex\n ) {\n return {\n apiPubHex: parsed.apiPubHex,\n apiPrivHex: parsed.apiPrivHex,\n savedAt: typeof parsed.savedAt === \"number\" ? parsed.savedAt : 0,\n };\n }\n return null;\n } catch {\n return null;\n }\n}\n\n/** Persist creds. Silently no-ops if storage is unavailable. */\nexport function save(c: Omit<Creds, \"savedAt\"> & { savedAt?: number }): void {\n try {\n const toStore: Creds = {\n apiPubHex: c.apiPubHex,\n apiPrivHex: c.apiPrivHex,\n savedAt: c.savedAt ?? Date.now(),\n };\n window.localStorage.setItem(STORAGE_KEY, JSON.stringify(toStore));\n } catch {\n /* storage unavailable — caller keeps creds in memory for this session */\n }\n}\n\n/** Forget the credential on this device. */\nexport function clear(): void {\n try {\n window.localStorage.removeItem(STORAGE_KEY);\n } catch {\n /* nothing to clear if storage is unavailable */\n }\n}\n\n/**\n * Validate a hex string (optional 0x prefix, even length, hex digits only).\n * Returns an error string for display, or null when valid.\n */\nexport function validateHex(s: string, label: string): string | null {\n const trimmed = s.trim();\n if (!trimmed) return `${label} is required`;\n const body = trimmed.startsWith(\"0x\") || trimmed.startsWith(\"0X\") ? trimmed.slice(2) : trimmed;\n if (body.length === 0) return `${label} is empty`;\n if (body.length % 2 !== 0) return `${label} must have an even number of hex digits`;\n if (!/^[0-9a-fA-F]+$/.test(body)) return `${label} must be hexadecimal`;\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// One-string token codec — the single value the user copies from the paybox\n// app (OAuth consent / Agents) and pastes here. Format:\n// pbxk1.<base64url(JSON.stringify({ p: apiPubHex, s: apiPrivHex }))>\n// It carries the keypair only — no walletId, no publishable key. It is the raw\n// secret in transit (same trust model as showing the key): it leaves the app\n// via the clipboard and is pasted here; it never goes to paybox.\n// ---------------------------------------------------------------------------\n\nfunction b64urlEncode(s: string): string {\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction b64urlDecode(s: string): string {\n let b = s.replace(/-/g, \"+\").replace(/_/g, \"/\");\n while (b.length % 4) b += \"=\";\n return atob(b);\n}\n\n/** Encode a keypair into the one-string token (mirrors the app side). */\nexport function encodeToken(c: { apiPubHex: string; apiPrivHex: string }): string {\n return TOKEN_PREFIX + b64urlEncode(JSON.stringify({ p: c.apiPubHex, s: c.apiPrivHex }));\n}\n\n/**\n * Parse a pasted token into a keypair, or null if it isn't a well-formed token\n * with two hex values. Accepts the canonical `pbxk1.` token and also tolerates\n * a bare base64url(JSON) body (in case the prefix is stripped on copy/paste).\n */\nexport function parseToken(input: string): { apiPubHex: string; apiPrivHex: string } | null {\n const t = input.trim();\n if (!t) return null;\n const body = t.startsWith(TOKEN_PREFIX) ? t.slice(TOKEN_PREFIX.length) : t;\n let obj: unknown;\n try {\n obj = JSON.parse(b64urlDecode(body));\n } catch {\n return null;\n }\n if (!obj || typeof obj !== \"object\") return null;\n const o = obj as Record<string, unknown>;\n const apiPubHex = String(o.p ?? o.apiPubHex ?? \"\").trim();\n const apiPrivHex = String(o.s ?? o.apiPrivHex ?? \"\").trim();\n if (!apiPubHex || !apiPrivHex) return null;\n if (validateHex(apiPubHex, \"key\") || validateHex(apiPrivHex, \"key\")) return null;\n return { apiPubHex, apiPrivHex };\n}\n","// The signing core: intent → MoonX ephemeral-signer signature → artifact.\n//\n// SPLIT-TRUST signing (the whole point of this design):\n// - This iframe holds the agent KEYPAIR (apiPub/apiPriv, from the pasted\n// pbxk1 token) and NOTHING ELSE. It builds the chain-specific digest, then\n// builds the MoonX request envelope and ed25519-signs it with apiPriv.\n// - It does NOT call MoonX and does NOT hold the MoonX secret key. The\n// secret-gated `/sign` HTTP call happens SERVER-SIDE, via the paybox\n// `moonx_sign` MCP tool (see `transport`). paybox adds the secret key,\n// which never reaches the browser.\n//\n// We reuse the @moon-x adapters purely for their CHAIN LOGIC (digest building +\n// signature assembly) by constructing them with a custom sign fn:\n// - EVM: new MoonXEvmSigner(ecdsaSign) — ecdsaSign: (digest) => {r,s,yParity}\n// - Solana: new MoonXSolanaSigner(ed25519Sign, address) — (bytes) => Uint8Array\n// Our custom fns build + ed25519-sign the envelope and delegate the actual\n// signing to `transport` (the moonx_sign tool). The envelope format mirrors\n// @moon-x/core's signWithEphemeralSigner exactly.\n//\n// The artifact returned is EXACTLY the old shape per op, so the paybox server\n// (which stores it via submit_signature) is unaffected.\n\nimport { Buffer } from \"buffer\";\nimport nacl from \"tweetnacl\";\nimport { MoonXEvmSigner, EvmSchemeMismatchError } from \"@moon-x/evm-adapter\";\nimport { MoonXSolanaSigner, SolanaSchemeMismatchError } from \"@moon-x/solana-adapter\";\nimport { Transaction } from \"@solana/web3.js\";\nimport { hashTypedData, keccak256, serializeTransaction } from \"viem\";\nimport type {\n Authorization,\n TransactionSerializable,\n TypedDataDefinition,\n} from \"viem\";\n\nimport type { Creds } from \"./creds.js\";\n\n// Transactions carry bigints (value/gas/fees), which JSON can't represent —\n// they arrive as decimal strings and are revived here. Mirrors the old path.\nexport interface WireTx {\n to: `0x${string}`;\n value: string;\n data?: `0x${string}`;\n chainId: number;\n gas: string;\n maxPriorityFeePerGas: string;\n maxFeePerGas: string;\n nonce: number;\n}\n\n/**\n * The intent to sign — the `op` discriminator + op-specific fields. The host\n * delivers this as `operation.intent` in the `request_wallet_sign` tool result.\n */\nexport type SignIntent =\n | { op: \"message\"; message: string }\n | { op: \"typedData\"; typedData: TypedDataDefinition }\n | { op: \"transaction\"; transaction: WireTx }\n | { op: \"authorization\"; authorization: Authorization }\n | { op: \"solanaMessage\"; address: string; message: string }\n | { op: \"solanaTransaction\"; address: string; transactionBase64: string }\n | { op: \"raw\"; rawSigningPayloadHex: string };\n\n/** The wallet's MoonX binding, supplied by paybox on the request (NOT the\n * pasted key). `keyId`/`derivationPath` are captured at provision time. */\nexport interface WalletBinding {\n walletId: string;\n keyId: string;\n derivationPath: string;\n}\n\n/** MoonX's raw `/sign` response, relayed back through the moonx_sign tool. */\nexport interface MoonxSignResult {\n scheme: string;\n signature: {\n /** ECDSA: lowercase-hex r/s (no 0x) + recovery_id 0..3. */\n r?: string;\n s?: string;\n recovery_id?: number;\n /** Ed25519: lowercase-hex 64-byte signature. */\n signature?: string;\n };\n}\n\n/**\n * Performs the secret-gated MoonX `/sign` call on the server. Given the envelope\n * this iframe built + signed, it returns MoonX's raw signature. Implemented by\n * the UI layer as a `moonx_sign` MCP tool call (the server adds the secret key\n * + the request_id/api_pub binding).\n */\nexport type MoonxSignTransport = (envelope: {\n signed_body: string;\n agent_signature: string;\n}) => Promise<MoonxSignResult>;\n\nexport type SignArtifactResult =\n | { ok: true; artifact: Record<string, unknown> }\n | { ok: false; error: string };\n\nfunction reviveTx(w: WireTx): TransactionSerializable {\n return {\n type: \"eip1559\",\n to: w.to,\n value: BigInt(w.value),\n data: w.data,\n chainId: w.chainId,\n gas: BigInt(w.gas),\n maxPriorityFeePerGas: BigInt(w.maxPriorityFeePerGas),\n maxFeePerGas: BigInt(w.maxFeePerGas),\n nonce: w.nonce,\n };\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n return new Uint8Array(Buffer.from(hex.replace(/^0x/, \"\"), \"hex\"));\n}\nfunction bytesToHex(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString(\"hex\");\n}\n\n/**\n * Build the MoonX `/sign` envelope and ed25519-sign it with the agent key.\n * Mirrors @moon-x/core `signWithEphemeralSigner` byte-for-byte: the signature\n * is over the UTF-8 JSON `{raw_signing_payload, key_id, derivation_path,\n * issued_at}` and `signed_body` is the hex of those exact bytes.\n */\nfunction buildEnvelope(\n rawSigningPayloadHex: string,\n binding: WalletBinding,\n creds: Creds,\n): { signed_body: string; agent_signature: string } {\n const signedPayload = {\n raw_signing_payload: rawSigningPayloadHex.replace(/^0x/, \"\").toLowerCase(),\n key_id: binding.keyId,\n derivation_path: binding.derivationPath,\n issued_at: new Date().toISOString(),\n };\n const signedBodyBytes = new TextEncoder().encode(JSON.stringify(signedPayload));\n // apiPrivHex is the 32-byte Ed25519 seed (64 hex chars).\n const keyPair = nacl.sign.keyPair.fromSeed(hexToBytes(creds.apiPrivHex));\n const agentSig = nacl.sign.detached(signedBodyBytes, keyPair.secretKey);\n return {\n signed_body: bytesToHex(signedBodyBytes),\n agent_signature: bytesToHex(agentSig),\n };\n}\n\n/**\n * The EIP-1559 signing hash for an unsigned tx — `keccak256` of the typed,\n * RLP-serialized unsigned transaction. Matches the server's\n * `eth_tx::signing_hash` (alloy) byte-for-byte, so the agent signature is over\n * the exact digest the server re-derives, validates, and asks MoonX to sign.\n */\nexport function eip1559SigningHash(tx: WireTx): `0x${string}` {\n return keccak256(serializeTransaction(reviveTx(tx)));\n}\n\n/**\n * The Solana signing payload (hex): the tx message — everything after the\n * zeroed signature slots in `[shortvec sig_count][sig_count × 64-byte\n * slots][message…]`. One slot on the raw path; two when a sponsoring fee payer\n * occupies slot 0 (gasless, SPE-294) — the wallet signs the same message either\n * way. MUST match the server's `solana::signing_payload` byte-for-byte.\n */\nexport function solanaSigningPayload(base64Tx: string): string {\n const raw = Buffer.from(base64Tx, \"base64\");\n // Decode the compact-u16 (\"shortvec\") signature count.\n let i = 0;\n let sigCount = 0;\n let shift = 0;\n for (;;) {\n const b = raw[i++];\n sigCount |= (b & 0x7f) << shift;\n if ((b & 0x80) === 0) break;\n shift += 7;\n }\n if (sigCount < 1) {\n throw new Error(\"solana tx has no signature slots\");\n }\n return bytesToHex(new Uint8Array(raw.subarray(i + sigCount * 64)));\n}\n\n/** One agent-signed signing envelope for the server-completes swap path. */\nexport interface TxEnvelope {\n api_pub: string;\n signed_body: string;\n agent_signature: string;\n}\n\n/** A sign-ready tx from the swap plan: an EVM `WireTx` (eip1559 fields), or a\n * base64 Solana tx string tagged `vm:\"solana\"`. */\nexport interface PlanTx {\n vm?: string;\n transaction: WireTx | string;\n}\n\n/**\n * One agent-signed envelope per parked tx for `submit_envelope` — NO tx bytes,\n * just the agent signature over each tx's payload (EVM: EIP-1559 sighash;\n * Solana: the tx message). Throws if the wallet isn't provisioned.\n */\nexport function buildSwapEnvelopes(\n txs: PlanTx[],\n binding: WalletBinding,\n creds: Creds,\n): TxEnvelope[] {\n if (!binding.walletId) {\n throw new Error(\"paybox did not supply a wallet id for this operation.\");\n }\n if (!binding.keyId || !binding.derivationPath) {\n throw new Error(\n \"This wallet isn't provisioned for signing yet (missing key binding). \" +\n \"Re-provision it in the paybox app, then retry.\",\n );\n }\n return txs.map((t) => {\n const payload =\n t.vm === \"solana\"\n ? solanaSigningPayload(t.transaction as string)\n : eip1559SigningHash(t.transaction as WireTx);\n const { signed_body, agent_signature } = buildEnvelope(payload, binding, creds);\n return { api_pub: creds.apiPubHex, signed_body, agent_signature };\n });\n}\n\n/**\n * The EIP-712 signing hash of EIP-3009 typed data — matches the server's\n * `x402::eip712_digest` byte-for-byte (both implement EIP-712), so the agent\n * envelope is over the exact digest the server re-derives, validates, and asks\n * MoonX to sign.\n */\nexport function eip712SigningHash(typedData: TypedDataDefinition): `0x${string}` {\n return hashTypedData(typedData);\n}\n\n/**\n * One agent-signed envelope for an x402 payment (the server-completes path): the\n * iframe ed25519-signs the EIP-712 digest of the EIP-3009 typed data; the server\n * re-derives + checks it, `/sign`s (MoonX), assembles the 65-byte EIP-712\n * signature, and encodes the `X-PAYMENT` header. Mirrors `buildSwapEnvelopes` —\n * NO payment bytes, only the agent signature over the digest. Throws if the\n * wallet isn't provisioned.\n */\nexport function buildX402Envelope(\n typedData: TypedDataDefinition,\n binding: WalletBinding,\n creds: Creds,\n): TxEnvelope {\n if (!binding.walletId) {\n throw new Error(\"paybox did not supply a wallet id for this payment.\");\n }\n if (!binding.keyId || !binding.derivationPath) {\n throw new Error(\n \"This wallet isn't provisioned for signing yet (missing key binding). \" +\n \"Re-provision it in the paybox app, then retry.\",\n );\n }\n const { signed_body, agent_signature } = buildEnvelope(\n eip712SigningHash(typedData),\n binding,\n creds,\n );\n return { api_pub: creds.apiPubHex, signed_body, agent_signature };\n}\n\n/** A gasless (SPE-248) prepared digest the iframe must sign: the runtime digest\n * `wallet_prepareCalls` returned (`signatureRequest.rawPayload`) plus its kind.\n * `userOp` is the ERC-4337 UserOp hash; `authorization` is the EIP-7702\n * authorization hash, present only on a wallet's first (delegating) gasless op. */\nexport interface GaslessDigest {\n kind: \"userOp\" | \"authorization\";\n /** The 32-byte digest as hex (Alchemy's `signatureRequest.rawPayload`). */\n rawPayloadHex: string;\n}\n\n/**\n * Build one agent-signed envelope per gasless digest, for the server-completes\n * gasless path (SPE-248). The UserOp hash and the EIP-7702 authorization hash\n * are produced SERVER-SIDE at runtime by Alchemy's `wallet_prepareCalls`, so —\n * unlike a raw EVM tx — the iframe can't derive them; it signs the digests\n * Alchemy already computed (`signatureRequest.rawPayload`), exactly the\n * `WalletSignIntent::Raw` mechanism (`buildEnvelope(rawSigningPayloadHex)`). The\n * server (`gasless::sign_digest`) matches each envelope to a prepared item by\n * `raw_signing_payload`, runs the secret-gated MoonX `/sign`, assembles the\n * secp256k1 `r‖s‖v`, and submits via `wallet_sendPreparedCalls`.\n *\n * Both kinds sign as a raw digest here — the server already has Alchemy's auth\n * hash, so the iframe does NOT re-derive it from an `Authorization` object (the\n * interactive `request_wallet_sign` `authorization` op does that, for an agent\n * signing a standalone 7702 auth; the gasless batch path signs the prepared\n * digest directly). `runSwap` calls this (over `plan.gasless`) instead of\n * `buildSwapEnvelopes` for a gasless-quoted swap. Throws if the wallet isn't\n * provisioned.\n */\nexport function buildGaslessEnvelopes(\n digests: GaslessDigest[],\n binding: WalletBinding,\n creds: Creds,\n): TxEnvelope[] {\n if (digests.length === 0) {\n throw new Error(\"gasless prepared calls have no signing items.\");\n }\n if (!binding.walletId) {\n throw new Error(\"paybox did not supply a wallet id for this operation.\");\n }\n if (!binding.keyId || !binding.derivationPath) {\n throw new Error(\n \"This wallet isn't provisioned for signing yet (missing key binding). \" +\n \"Re-provision it in the paybox app, then retry.\",\n );\n }\n return digests.map((d) => {\n const { signed_body, agent_signature } = buildEnvelope(d.rawPayloadHex, binding, creds);\n return { api_pub: creds.apiPubHex, signed_body, agent_signature };\n });\n}\n\n/** Resolve a wallet binding (`key_id` + `derivation_path`) the authoritative\n * way — via the server's secret-gated `/me/wallets`. Used when paybox hasn't\n * pre-captured the binding (ambiguous grant). The iframe ed25519-signs an\n * `{issued_at}` envelope; `resolve` (a `moonx_resolve_binding` tool call)\n * returns the binding for the request's wallet. */\nexport type ResolveBindingTransport = (envelope: {\n signed_body: string;\n agent_signature: string;\n}) => Promise<{ key_id?: string; derivation_path?: string }>;\n\n/**\n * Build + ed25519-sign an `{issued_at}` envelope with the agent key. Used for\n * the secret-gated tools that authenticate the signer without a chain payload —\n * `moonx_resolve_binding` and `prepare_swap`. Mirrors the server's expectation:\n * the signature is over the UTF-8 JSON `{issued_at}` and `signed_body` is its hex.\n */\nexport function buildIssuedAtEnvelope(creds: Creds): {\n signed_body: string;\n agent_signature: string;\n} {\n const signedBodyBytes = new TextEncoder().encode(\n JSON.stringify({ issued_at: new Date().toISOString() }),\n );\n const keyPair = nacl.sign.keyPair.fromSeed(hexToBytes(creds.apiPrivHex));\n const agentSig = nacl.sign.detached(signedBodyBytes, keyPair.secretKey);\n return {\n signed_body: bytesToHex(signedBodyBytes),\n agent_signature: bytesToHex(agentSig),\n };\n}\n\nexport async function resolveWalletBinding(\n creds: Creds,\n resolve: ResolveBindingTransport,\n): Promise<{ keyId: string; derivationPath: string }> {\n const res = await resolve(buildIssuedAtEnvelope(creds));\n if (!res.key_id || !res.derivation_path) {\n throw new Error(\"MoonX returned no binding for this wallet\");\n }\n return { keyId: res.key_id, derivationPath: res.derivation_path };\n}\n\n/**\n * Sign `intent` for `binding` using the agent `creds`, delegating the\n * secret-gated MoonX call to `transport` (the server). Returns the artifact —\n * exactly the old per-op shape — or an error string. Never throws; never logs\n * the key.\n */\nexport async function signIntent(\n intent: SignIntent,\n creds: Creds,\n binding: WalletBinding,\n transport: MoonxSignTransport,\n): Promise<SignArtifactResult> {\n if (!binding.walletId) {\n return { ok: false, error: \"paybox did not supply a wallet id for this operation.\" };\n }\n if (!binding.keyId || !binding.derivationPath) {\n return {\n ok: false,\n error:\n \"This wallet isn't provisioned for signing yet (missing key binding). \" +\n \"Re-provision it in the paybox app, then retry.\",\n };\n }\n\n // EVM: the adapter builds the digest + assembles the signature; we own only\n // the transport (envelope build + ed25519 + the server sign call).\n const ecdsaSign = async (digest: `0x${string}`) => {\n const result = await transport(buildEnvelope(digest, binding, creds));\n const { r, s, recovery_id } = result.signature;\n if (r == null || s == null || recovery_id == null) {\n throw new Error(\"MoonX returned an ECDSA result without {r, s, recovery_id}\");\n }\n return {\n r: `0x${r}` as `0x${string}`,\n s: `0x${s}` as `0x${string}`,\n yParity: recovery_id as 0 | 1,\n };\n };\n // Solana: sign fn takes the raw message bytes, returns the 64-byte signature.\n const ed25519Sign = async (message: Uint8Array) => {\n const result = await transport(buildEnvelope(bytesToHex(message), binding, creds));\n const sig = result.signature.signature;\n if (!sig) throw new Error(\"MoonX returned an Ed25519 result without a signature\");\n return hexToBytes(sig);\n };\n\n try {\n switch (intent.op) {\n case \"message\":\n return {\n ok: true,\n artifact: { signature: await new MoonXEvmSigner(ecdsaSign).signMessage(intent.message) },\n };\n case \"typedData\":\n return {\n ok: true,\n artifact: {\n signature: await new MoonXEvmSigner(ecdsaSign).signTypedData(intent.typedData),\n },\n };\n case \"transaction\":\n return {\n ok: true,\n artifact: {\n serializedTransaction: await new MoonXEvmSigner(ecdsaSign).signTransaction(\n reviveTx(intent.transaction),\n ),\n },\n };\n case \"authorization\":\n return {\n ok: true,\n artifact: {\n authorization: await new MoonXEvmSigner(ecdsaSign).signAuthorization(\n intent.authorization,\n ),\n },\n };\n case \"solanaMessage\": {\n const sig = await new MoonXSolanaSigner(ed25519Sign, intent.address).signMessage(\n intent.message,\n );\n return { ok: true, artifact: { signature: bytesToHex(sig) } };\n }\n case \"solanaTransaction\": {\n const tx = Transaction.from(Buffer.from(intent.transactionBase64, \"base64\"));\n const signed = await new MoonXSolanaSigner(ed25519Sign, intent.address).signTransaction(\n tx,\n );\n return {\n ok: true,\n artifact: { signedTransactionBase64: Buffer.from(signed).toString(\"base64\") },\n };\n }\n case \"raw\": {\n // No chain logic — the digest is given. Build + sign + relay directly.\n const result = await transport(buildEnvelope(intent.rawSigningPayloadHex, binding, creds));\n return { ok: true, artifact: { scheme: result.scheme, signature: result.signature } };\n }\n default:\n return { ok: false, error: `unknown op: ${(intent as { op?: string }).op}` };\n }\n } catch (err) {\n if (err instanceof EvmSchemeMismatchError || err instanceof SolanaSchemeMismatchError) {\n return { ok: false, error: err.message };\n }\n const message = err instanceof Error ? err.message : String(err);\n return { ok: false, error: message };\n }\n}\n","// In-process, non-custodial wallet signing — the SDK's replacement for the MCP\n// host iframe. The signing CORE is reused verbatim from the iframe\n// (@paybox/mcp-app/sign): it builds the chain digest, ed25519-signs the MoonX\n// envelope with the agent's pbxk1. keypair, and delegates the secret-gated MoonX\n// /sign to the server (the secret never reaches the client). Here we only swap\n// the iframe's MCP-tool transport for the SDK's REST calls.\n\nimport { parseToken } from \"@paybox/mcp-app/creds\";\nimport type { Creds } from \"@paybox/mcp-app/creds\";\nimport {\n buildIssuedAtEnvelope,\n buildSwapEnvelopes,\n buildX402Envelope,\n signIntent,\n} from \"@paybox/mcp-app/sign\";\nimport type {\n MoonxSignResult,\n SignIntent,\n TxEnvelope,\n WalletBinding,\n} from \"@paybox/mcp-app/sign\";\n\nimport type { BindingResponse, SwapPlan, X402Plan } from \"./types.js\";\n\n/** POST `{path}` (relative to the API base) with a JSON body, returning parsed\n * JSON. Supplied by the client so the signer reuses its auth + base URL. */\nexport type Poster = (path: string, body: unknown) => Promise<unknown>;\n\n/** Parse the one-string `pbxk1.` token into the agent keypair the core expects. */\nexport function credsFromToken(token: string): Creds {\n const kp = parseToken(token);\n if (!kp) {\n throw new Error(\"invalid signing key: expected a `pbxk1.` token (keypair only)\");\n }\n return { apiPubHex: kp.apiPubHex, apiPrivHex: kp.apiPrivHex, savedAt: Date.now() };\n}\n\nfunction toBinding(b: BindingResponse): WalletBinding {\n return { walletId: b.wallet_id, keyId: b.key_id ?? \"\", derivationPath: b.derivation_path ?? \"\" };\n}\n\n/** Resolve the wallet binding (key_id + derivation_path) for a parked request via\n * the server's secret-gated `/binding` route (the `moonx_resolve_binding` twin). */\nasync function resolveBinding(\n post: Poster,\n requestId: string,\n creds: Creds,\n): Promise<WalletBinding> {\n const env = buildIssuedAtEnvelope(creds);\n const r = (await post(`/agent/requests/${requestId}/binding`, {\n api_pub: creds.apiPubHex,\n signed_body: env.signed_body,\n agent_signature: env.agent_signature,\n })) as BindingResponse;\n return toBinding(r);\n}\n\n/** Sign a parked `request_wallet_sign` and submit the artifact. Uses the binding\n * the server echoed on the wallet-sign response when it's complete (avoiding an\n * extra secret-gated resolve), and only resolves when it isn't. The MoonX\n * secret call runs server-side via `/moonx-sign`; the artifact lands via\n * `/signature`. */\nexport async function signWalletRequest(\n post: Poster,\n requestId: string,\n intent: SignIntent,\n creds: Creds,\n binding?: BindingResponse | null,\n): Promise<Record<string, unknown>> {\n const resolved =\n binding && binding.key_id && binding.derivation_path\n ? toBinding(binding)\n : await resolveBinding(post, requestId, creds);\n const transport = (envelope: { signed_body: string; agent_signature: string }) =>\n post(`/agent/requests/${requestId}/moonx-sign`, {\n api_pub: creds.apiPubHex,\n ...envelope,\n }) as Promise<MoonxSignResult>;\n const result = await signIntent(intent, creds, resolved, transport);\n if (!result.ok) throw new Error(result.error);\n await post(`/agent/requests/${requestId}/signature`, { artifact: result.artifact });\n return result.artifact;\n}\n\n/** A Solana swap/prediction-trade plan pins a recent blockhash at quote time\n * that expires within ~60-90s — often before the SDK signs (especially after\n * an approval dwell), so signing the original plan broadcasts as\n * BlockhashNotFound. Mirrors the signing window's `isSolanaRefreshablePlan`\n * (clients/mcp-app/src/ui.ts): a Solana plan carrying a swap/prediction-trade\n * tx. EVM plans have no blockhash and are left untouched. */\nfunction isSolanaRefreshablePlan(plan: SwapPlan): boolean {\n const txs = plan.txs as Array<{ vm?: string; kind?: string }>;\n const solana = txs.some((t) => t.vm === \"solana\");\n return solana && txs.some((t) => t.kind === \"swap\" || t.kind === \"prediction_trade\");\n}\n\n/** Re-pin a parked Solana swap's blockhash immediately before signing, via the\n * REST twin of the iframe refresh endpoint (`POST /agent/requests/{id}/refresh`,\n * SPE-396). Returns the updated plan to sign over; only the blockhash changed. */\nasync function refreshSwapPlan(\n post: Poster,\n requestId: string,\n plan: SwapPlan,\n): Promise<SwapPlan> {\n const r = (await post(`/agent/requests/${requestId}/refresh`, {})) as { plan?: unknown };\n if (!r || typeof r.plan !== \"object\" || r.plan === null) {\n throw new Error(\"swap refresh returned no plan\");\n }\n const refreshed = r.plan as SwapPlan;\n if (!Array.isArray(refreshed.txs) || refreshed.txs.length === 0) {\n throw new Error(\"swap refresh returned a plan with no txs\");\n }\n return refreshed;\n}\n\n/** Sign every tx of a parked swap plan, in order, and submit the envelopes;\n * the server verifies, signs (secret-gated), encodes, and broadcasts. For a\n * refreshable Solana plan the blockhash is re-pinned first (SPE-396 parity with\n * the signing window) so a dwelling swap never signs a stale blockhash. */\nexport async function signSwapRequest(\n post: Poster,\n requestId: string,\n plan: SwapPlan,\n creds: Creds,\n): Promise<void> {\n const signPlan = isSolanaRefreshablePlan(plan)\n ? await refreshSwapPlan(post, requestId, plan)\n : plan;\n let binding: WalletBinding = {\n walletId: signPlan.binding.wallet_id,\n keyId: signPlan.binding.key_id ?? \"\",\n derivationPath: signPlan.binding.derivation_path ?? \"\",\n };\n if (binding.walletId && (!binding.keyId || !binding.derivationPath)) {\n binding = await resolveBinding(post, requestId, creds);\n }\n const envelopes: TxEnvelope[] = buildSwapEnvelopes(signPlan.txs, binding, creds);\n await post(`/agent/requests/${requestId}/envelopes`, { envelopes });\n}\n\n/** Sign a parked x402 payment's EIP-3009 typed data and submit the envelope; the\n * server re-derives the digest, signs (secret-gated), assembles the X-PAYMENT\n * header, and — in gateway mode — fetches the resource. Mirrors signSwapRequest\n * (one envelope, over the typed data's EIP-712 digest, not a tx sighash). */\nexport async function signX402Request(\n post: Poster,\n requestId: string,\n plan: X402Plan,\n creds: Creds,\n): Promise<void> {\n let binding: WalletBinding = {\n walletId: plan.binding.wallet_id,\n keyId: plan.binding.key_id ?? \"\",\n derivationPath: plan.binding.derivation_path ?? \"\",\n };\n if (binding.walletId && (!binding.keyId || !binding.derivationPath)) {\n binding = await resolveBinding(post, requestId, creds);\n }\n const envelope: TxEnvelope = buildX402Envelope(\n plan.typed_data as Parameters<typeof buildX402Envelope>[0],\n binding,\n creds,\n );\n await post(`/agent/requests/${requestId}/envelopes`, { envelopes: [envelope] });\n}\n","// PayboxClient — the typed REST client mirroring the MCP agent tools. Each method\n// maps to a `/agent/*` route; `request_wallet_sign` / `request_swap` additionally\n// drive in-process signing when a `pbxk1.` signing key is configured.\n\nimport { refreshTokens } from \"./auth.js\";\nimport { loadConfig, saveConfig, type OAuthTokens } from \"./config.js\";\nimport {\n credsFromToken,\n signSwapRequest,\n signWalletRequest,\n signX402Request,\n type Poster,\n} from \"./signer.js\";\nimport type {\n RequestPaymentArgs,\n RequestSecretArgs,\n RequestSwapArgs,\n RequestWalletSignArgs,\n} from \"./types.generated.js\";\nimport type {\n AccountChangeResult,\n AgentResponse,\n BuyLinkArgs,\n BuyLinkResult,\n ClientGrantSummary,\n DiscoverServicesOptions,\n PaymentArgs,\n PortfolioArgs,\n SecretArgs,\n ServiceSummary,\n SwapArgs,\n SwapResult,\n UseServiceArgs,\n WalletSignArgs,\n WalletSignResult,\n WorldMarketsArgs,\n WorldPricesArgs,\n WorldTradeArgs,\n X402Args,\n X402Result,\n} from \"./types.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.paybox.sh\";\nconst EXPIRY_SKEW_MS = 60_000;\n\nexport class PayboxError extends Error {\n constructor(\n readonly status: number,\n readonly body: string,\n context: string,\n ) {\n super(`paybox ${context} failed (${status}): ${body}`);\n this.name = \"PayboxError\";\n }\n}\n\nexport interface PayboxClientOptions {\n /** API origin (the OAuth issuer). Default `https://api.paybox.sh`. */\n baseUrl?: string;\n /** A `pbx_live_*` personal API key. */\n apiKey?: string;\n /** A raw OAuth access token (skips the stored-token path). */\n token?: string;\n /** A `pbxk1.` signing key token; enables in-process wallet/swap signing. */\n signingKey?: string;\n fetchImpl?: typeof fetch;\n}\n\nexport interface SignOptions {\n /** Sign in-process when the request clears to `pending_signature`. Default true. */\n autoSign?: boolean;\n /** When the request parks as `pending_approval` (approval-mode grant, or a\n * force-approved op like a World trade), wait for the user's passkey approval\n * and then sign in-process — the SDK's headless equivalent of the signing\n * window's post-approval sign. Default false (return the pending response). */\n waitForApproval?: boolean | { intervalMs?: number; timeoutMs?: number };\n}\n\nexport class PayboxClient {\n readonly baseUrl: string;\n private readonly opts: PayboxClientOptions;\n private readonly fetchImpl: typeof fetch;\n private oauth?: OAuthTokens;\n private configBacked = false;\n\n constructor(options: PayboxClientOptions = {}) {\n this.opts = options;\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n this.fetchImpl = options.fetchImpl ?? fetch;\n }\n\n /** Build a client from `~/.config/paybox/config.json` + env, with overrides. */\n static fromConfig(overrides: PayboxClientOptions = {}): PayboxClient {\n const cfg = loadConfig();\n const client = new PayboxClient({\n baseUrl: overrides.baseUrl ?? process.env.PAYBOX_API_URL ?? cfg.baseUrl,\n apiKey: overrides.apiKey ?? process.env.PAYBOX_API_KEY ?? cfg.apiKey,\n token: overrides.token ?? process.env.PAYBOX_ACCESS_TOKEN,\n signingKey: overrides.signingKey ?? process.env.PAYBOX_SIGNING_KEY ?? cfg.signingKey,\n fetchImpl: overrides.fetchImpl,\n });\n if (!client.opts.apiKey && !client.opts.token && cfg.oauth) {\n client.oauth = cfg.oauth;\n client.configBacked = true;\n }\n return client;\n }\n\n /** Whether in-process signing is available (a `pbxk1.` key is configured). */\n get canSign(): boolean {\n return Boolean(this.opts.signingKey);\n }\n\n private async bearer(): Promise<string> {\n if (this.opts.token) return this.opts.token;\n if (this.opts.apiKey) return this.opts.apiKey;\n if (this.oauth) {\n if (this.oauth.expiresAt && Date.now() > this.oauth.expiresAt - EXPIRY_SKEW_MS) {\n this.oauth = await refreshTokens(this.baseUrl, this.oauth);\n if (this.configBacked) {\n const cfg = loadConfig();\n cfg.oauth = this.oauth;\n saveConfig(cfg);\n }\n }\n return this.oauth.accessToken;\n }\n throw new Error(\n \"not authenticated — run `paybox login`, set PAYBOX_API_KEY, or pass { apiKey } / { token }\",\n );\n }\n\n private async request<T>(\n method: string,\n path: string,\n init: { query?: Record<string, string | undefined>; body?: unknown } = {},\n ): Promise<T> {\n const url = new URL(this.baseUrl + path);\n for (const [k, v] of Object.entries(init.query ?? {})) {\n if (v != null) url.searchParams.set(k, v);\n }\n const headers: Record<string, string> = { authorization: `Bearer ${await this.bearer()}` };\n let body: string | undefined;\n if (init.body !== undefined) {\n headers[\"content-type\"] = \"application/json\";\n body = JSON.stringify(init.body);\n }\n const res = await this.fetchImpl(url, { method, headers, body });\n const text = await res.text();\n if (!res.ok) throw new PayboxError(res.status, text, `${method} ${path}`);\n return (text ? JSON.parse(text) : undefined) as T;\n }\n\n private readonly poster: Poster = (path, body) => this.request<unknown>(\"POST\", path, { body });\n\n /** List the credentials this client may use (the `list_credentials` tool). */\n listCredentials(): Promise<ClientGrantSummary[]> {\n return this.request(\"GET\", \"/agent/grants\");\n }\n\n /** Token balances across chains (the `get_portfolio` tool). */\n getPortfolio(args: PortfolioArgs): Promise<unknown> {\n return this.request(\"GET\", \"/agent/portfolio\", {\n query: { address: args.address, network_ids: args.networkIds },\n });\n }\n\n /** Charge a card credential (the `request_payment` tool). */\n requestPayment(args: PaymentArgs): Promise<AgentResponse> {\n const operation: RequestPaymentArgs & { type: \"payment\" } = {\n type: \"payment\",\n credential_id: args.credentialId,\n merchant: args.merchant,\n merchant_url: args.merchantUrl,\n amount_cents: args.amountCents,\n currency: args.currency ?? \"USD\",\n };\n return this.request(\"POST\", \"/agent/request\", { body: { operation } });\n }\n\n /** Reveal a secret credential (the `request_secret` tool). */\n requestSecret(args: SecretArgs): Promise<AgentResponse> {\n const operation: RequestSecretArgs & { type: \"secret\" } = {\n type: \"secret\",\n credential_id: args.credentialId,\n raw: args.raw ?? false,\n purpose: args.purpose ?? null,\n };\n return this.request(\"POST\", \"/agent/request\", { body: { operation } });\n }\n\n /** Sign with a wallet credential (the `request_wallet_sign` tool). Signs\n * in-process and returns the completed request when a signing key is set and\n * the request clears immediately; otherwise returns the pending response.\n * Uses `/agent/wallet-sign`, which echoes the wallet binding so the signer\n * need not resolve it separately. */\n async requestWalletSign(args: WalletSignArgs, opts: SignOptions = {}): Promise<AgentResponse> {\n const operation: RequestWalletSignArgs & { type: \"wallet_sign\" } = {\n type: \"wallet_sign\",\n credential_id: args.credentialId,\n intent: args.intent,\n };\n const { response, binding } = await this.request<WalletSignResult>(\n \"POST\",\n \"/agent/wallet-sign\",\n { body: { operation } },\n );\n if (\n (opts.autoSign ?? true) &&\n response.status === \"pending_signature\" &&\n this.opts.signingKey\n ) {\n await signWalletRequest(\n this.poster,\n response.request_id,\n args.intent,\n credsFromToken(this.opts.signingKey),\n binding,\n );\n return this.getRequest(response.request_id);\n }\n return response;\n }\n\n /** Swap tokens from a wallet credential (the `request_swap` tool). Returns the\n * parked response + sign-ready plan; signs + submits in-process when a signing\n * key is set and the swap cleared immediately. */\n async requestSwap(args: SwapArgs, opts: SignOptions = {}): Promise<SwapResult> {\n const operation: RequestSwapArgs & { type: \"swap\" } = {\n type: \"swap\",\n credential_id: args.credentialId,\n src_chain: args.srcChain,\n dst_chain: args.dstChain ?? args.srcChain,\n src_token: args.srcToken,\n dst_token: args.dstToken,\n amount: args.amount,\n swap_direction: args.swapDirection ?? \"exact-amount-in\",\n slippage_bps: args.slippageBps ?? 50,\n recipient: args.recipient ?? null,\n value_cents: args.valueCents ?? null,\n };\n const result = await this.request<SwapResult>(\"POST\", \"/agent/swap\", { body: { operation } });\n return this.completeSwap(result, opts);\n }\n\n /** Shared completion for swap-shaped requests (`request_swap` and the World\n * trade): optionally wait out a `pending_approval` dwell, then sign the plan\n * in-process and submit envelopes. Signing re-pins a Solana plan's blockhash\n * (and re-quotes a stale World order) via `/agent/requests/{id}/refresh`\n * first, so a long approval dwell never signs stale bytes. */\n private async completeSwap(result: SwapResult, opts: SignOptions): Promise<SwapResult> {\n if (!(opts.autoSign ?? true) || !this.opts.signingKey) return result;\n let response = result.response;\n if (response.status === \"pending_approval\" && opts.waitForApproval) {\n response = await this.waitWhileApproval(response.request_id, opts.waitForApproval);\n }\n if (response.status !== \"pending_signature\") {\n return { ...result, response };\n }\n await signSwapRequest(\n this.poster,\n response.request_id,\n result.plan,\n credsFromToken(this.opts.signingKey),\n );\n return { ...result, response: await this.getRequest(response.request_id) };\n }\n\n /** Poll while the request sits in `pending_approval` (the user is approving\n * with their passkey); returns the first non-approval state. */\n private async waitWhileApproval(\n requestId: string,\n wait: boolean | { intervalMs?: number; timeoutMs?: number },\n ): Promise<AgentResponse> {\n const o = typeof wait === \"object\" ? wait : {};\n const interval = o.intervalMs ?? 2000;\n const deadline = Date.now() + (o.timeoutMs ?? 300_000);\n for (;;) {\n const r = await this.getRequest(requestId);\n if (r.status !== \"pending_approval\" || Date.now() > deadline) return r;\n await new Promise((res) => setTimeout(res, interval));\n }\n }\n\n /** Discover curated paid x402 services from the Bazaar catalog (the\n * `discover_services` tool). Pass a query to search the curated set; omit it\n * for the curated listing. Set `raw` only to inspect uncurated compact\n * Bazaar service summaries. */\n async discoverServices(\n query?: string,\n opts: DiscoverServicesOptions = {},\n ): Promise<ServiceSummary[]> {\n const r = await this.request<{ services: ServiceSummary[] }>(\"GET\", \"/agent/services\", {\n query: { query, raw: opts.raw ? \"true\" : undefined },\n });\n return r.services;\n }\n\n /** Pay a paid x402 endpoint from a wallet credential (the `pay_x402` tool,\n * header mode). Signs in-process when a signing key is set and the payment\n * clears immediately — then the X-PAYMENT header is on the completed\n * response's `output.value.x_payment` (replay it on the original request). */\n async payX402(args: X402Args, opts: SignOptions = {}): Promise<X402Result> {\n const result = await this.request<X402Result>(\"POST\", \"/agent/x402\", {\n body: {\n credential_id: args.credentialId,\n accepts: args.accepts,\n resource_url: args.resourceUrl,\n },\n });\n return this.completeX402(result, opts);\n }\n\n /** Fetch a paid x402 resource and have paybox pay for it (the `use_service`\n * tool, gateway mode): paybox probes the url, pays the 402, re-fetches with the\n * payment, and returns the resource's reply on `output.value.response`. */\n async useService(args: UseServiceArgs, opts: SignOptions = {}): Promise<X402Result> {\n const result = await this.request<X402Result>(\"POST\", \"/agent/use-service\", {\n body: {\n credential_id: args.credentialId,\n url: args.url,\n method: args.method,\n body: args.body,\n },\n });\n return this.completeX402(result, opts);\n }\n\n /** Shared completion for the two x402 entry points: optionally wait out a\n * `pending_approval` dwell, then sign the parked typed data in-process and\n * return the finished request, exactly like the swap path. */\n private async completeX402(result: X402Result, opts: SignOptions): Promise<X402Result> {\n if (!(opts.autoSign ?? true) || !this.opts.signingKey) return result;\n let response = result.response;\n if (response.status === \"pending_approval\" && opts.waitForApproval) {\n response = await this.waitWhileApproval(response.request_id, opts.waitForApproval);\n }\n if (response.status !== \"pending_signature\") {\n return { ...result, response };\n }\n await signX402Request(\n this.poster,\n response.request_id,\n result.plan,\n credsFromToken(this.opts.signingKey),\n );\n return { ...result, response: await this.getRequest(response.request_id) };\n }\n\n /** Claim the usable card credentials of an approved payment (the\n * `claim_payment_credentials` tool). One-time: the claim is consumed. */\n claimPaymentCredentials(requestId: string): Promise<Record<string, unknown>> {\n return this.request(\"POST\", `/agent/requests/${requestId}/credentials`);\n }\n\n /** Open the account-change flow (the `request_account_change` tool): returns a\n * `manage_url` deep link for the USER to open — they update this client's\n * access (or add a credential) in their own passkey-gated app session.\n * Nothing is parked or applied server-side. */\n requestAccountChange(note?: string): Promise<AccountChangeResult> {\n return this.request(\"POST\", \"/agent/account-change\", { body: { note } });\n }\n\n /** A signed MoonPay checkout URL funding a granted wallet (the `get_buy_link`\n * tool). Share the URL with the user; generating it charges nothing. */\n getBuyLink(args: BuyLinkArgs): Promise<BuyLinkResult> {\n return this.request(\"GET\", \"/agent/buy-link\", {\n query: {\n credential_id: args.credentialId,\n currency_code: args.currencyCode,\n amount_usd: args.amountUsd?.toString(),\n },\n });\n }\n\n // ---- World plugin (prediction markets) — requires the user to have enabled\n // the `world` plugin in the paybox app. Reads are discovery-only; `worldTrade`\n // parks a force-approved PredictionTrade the SDK signs in-process after the\n // user approves (pass `waitForApproval` to wait + sign headlessly). ----\n\n /** Browse World prediction markets (the `world_find_markets` tool). */\n worldMarkets(args: WorldMarketsArgs = {}): Promise<unknown> {\n return this.request(\"GET\", \"/agent/world/markets\", {\n query: {\n events: args.events ? \"true\" : undefined,\n limit: args.limit?.toString(),\n cursor: args.cursor?.toString(),\n event_ticker: args.eventTicker,\n series_ticker: args.seriesTicker,\n status: args.status,\n },\n });\n }\n\n /** One World event with its markets (the `world_get_market` tool). Nested\n * markets default on, matching the tool — they carry the outcome mint ids\n * the orderbook/trade calls need. */\n worldMarket(eventTicker: string, withNestedMarkets = true): Promise<unknown> {\n return this.request(\"GET\", \"/agent/world/market\", {\n query: {\n event_ticker: eventTicker,\n // Omit when true (the server default); send only the explicit opt-out.\n with_nested_markets: withNestedMarkets ? undefined : \"false\",\n },\n });\n }\n\n /** A World market's orderbook (the `world_orderbook` tool). */\n worldOrderbook(id: string, byMint = false): Promise<unknown> {\n return this.request(\"GET\", \"/agent/world/orderbook\", {\n query: { id, by_mint: byMint ? \"true\" : undefined },\n });\n }\n\n /** A World market's price history (the `world_market_prices` tool). */\n worldPrices(args: WorldPricesArgs): Promise<unknown> {\n return this.request(\"GET\", \"/agent/world/prices\", {\n query: {\n ticker: args.ticker,\n start_ts: args.startTs.toString(),\n end_ts: args.endTs.toString(),\n resolution: args.resolution?.toString(),\n },\n });\n }\n\n /** Filter addresses down to World outcome mints (the\n * `world_filter_outcome_mints` tool). */\n worldFilterOutcomeMints(addresses: string[]): Promise<unknown> {\n return this.request(\"POST\", \"/agent/world/filter-outcome-mints\", {\n body: { addresses },\n });\n }\n\n /** Solana token positions for an address (the `world_positions` tool). */\n worldPositions(address: string): Promise<unknown> {\n return this.request(\"GET\", \"/agent/world/positions\", { query: { address } });\n }\n\n /** Trade a World prediction market (the `world_buy_outcome` /\n * `world_change_position` / `world_redeem` tools). Always parks as\n * `pending_approval` (trades are force-approved); pass\n * `{ waitForApproval: true }` to wait for the user's passkey approval and\n * sign in-process. */\n async worldTrade(args: WorldTradeArgs, opts: SignOptions = {}): Promise<SwapResult> {\n const result = await this.request<SwapResult>(\"POST\", \"/agent/world/trade\", {\n body: {\n credential_id: args.credentialId,\n market_mint: args.marketMint,\n side: args.side,\n size: args.size,\n slippage_bps: args.slippageBps,\n value_cents: args.valueCents,\n },\n });\n return this.completeSwap(result, opts);\n }\n\n // ---- Hyperliquid plugin (read-only spot discovery) — requires the user to\n // have enabled the `hyperliquid` plugin in the paybox app. ----\n\n /** Hyperliquid spot markets (the `hyperliquid_markets` tool). */\n hyperliquidMarkets(): Promise<unknown> {\n return this.request(\"GET\", \"/agent/hyperliquid/markets\");\n }\n\n /** Hyperliquid spot prices (the `hyperliquid_prices` tool). */\n hyperliquidPrices(): Promise<unknown> {\n return this.request(\"GET\", \"/agent/hyperliquid/prices\");\n }\n\n /** Resolve one Hyperliquid token by name (the `hyperliquid_token` tool). */\n hyperliquidToken(name: string): Promise<unknown> {\n return this.request(\"GET\", \"/agent/hyperliquid/token\", { query: { name } });\n }\n\n /** Poll a request's status (the `get_request` tool). */\n getRequest(requestId: string): Promise<AgentResponse> {\n return this.request(\"GET\", `/agent/requests/${requestId}`);\n }\n\n /** Poll until the request leaves a pending state (or the timeout elapses). */\n async waitForRequest(\n requestId: string,\n opts: { intervalMs?: number; timeoutMs?: number } = {},\n ): Promise<AgentResponse> {\n const interval = opts.intervalMs ?? 2000;\n const deadline = Date.now() + (opts.timeoutMs ?? 300_000);\n for (;;) {\n const r = await this.getRequest(requestId);\n const pending =\n r.status === \"pending_approval\" ||\n r.status === \"pending_signature\" ||\n r.status === \"pending_settlement\" ||\n r.status === \"pending_confirmation\";\n if (!pending || Date.now() > deadline) return r;\n await new Promise((res) => setTimeout(res, interval));\n }\n }\n}\n"],"mappings":";AAQA,SAAS,aAAa;AACtB,SAAS,YAAY,mBAAmB;AACxC,SAAS,oBAAoB;AAMtB,SAAS,YAAY,S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