@piprail/sdk 1.3.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -3777,9 +3777,9 @@ declare function resolveChain(input: ChainInput, rpcUrlOverride?: string): Resol
3777
3777
  */
3778
3778
 
3779
3779
  /** The chain families the SDK knows about. */
3780
- type ChainFamily = 'evm' | 'solana' | 'ton' | 'stellar' | 'xrpl' | 'tron' | 'sui' | 'near' | 'aptos';
3780
+ type ChainFamily = 'evm' | 'solana' | 'ton' | 'stellar' | 'xrpl' | 'tron' | 'sui' | 'near' | 'aptos' | 'algorand';
3781
3781
  /** What chain to use: an EVM name/Chain/{id,rpcUrl}, or a non-EVM family name. */
3782
- type ChainSelector = ChainInput | 'solana' | 'ton' | 'stellar' | 'xrpl' | 'tron' | 'sui' | 'near' | 'aptos';
3782
+ type ChainSelector = ChainInput | 'solana' | 'ton' | 'stellar' | 'xrpl' | 'tron' | 'sui' | 'near' | 'aptos' | 'algorand';
3783
3783
  /** An EVM ERC-20 token, by contract address. */
3784
3784
  interface EvmToken {
3785
3785
  address: `0x${string}`;
@@ -3837,6 +3837,12 @@ interface AptosToken {
3837
3837
  decimals: number;
3838
3838
  symbol?: string;
3839
3839
  }
3840
+ /** An Algorand Standard Asset (ASA), by its numeric asset id. */
3841
+ interface AlgorandToken {
3842
+ assetId: number;
3843
+ decimals: number;
3844
+ symbol?: string;
3845
+ }
3840
3846
  /**
3841
3847
  * What to be paid in. Each driver validates the forms it accepts:
3842
3848
  * - 'native' the chain's native coin (ETH, BNB, SOL, TON, XLM, XRP)
@@ -3850,8 +3856,9 @@ interface AptosToken {
3850
3856
  * - SuiToken any coin (Sui)
3851
3857
  * - NearToken any NEP-141 (NEAR)
3852
3858
  * - AptosToken any Fungible Asset (Aptos)
3859
+ * - AlgorandToken any ASA (Algorand)
3853
3860
  */
3854
- type TokenInput = 'native' | (string & {}) | EvmToken | SolanaToken | TonToken | StellarToken | XrplToken | TronToken | SuiToken | NearToken | AptosToken;
3861
+ type TokenInput = 'native' | (string & {}) | EvmToken | SolanaToken | TonToken | StellarToken | XrplToken | TronToken | SuiToken | NearToken | AptosToken | AlgorandToken;
3855
3862
  /** What a driver resolves a TokenInput into. `asset`: 0x | base58 mint | 'native'. */
3856
3863
  interface ResolvedToken {
3857
3864
  asset: string;
@@ -3885,6 +3892,22 @@ interface CostEstimate {
3885
3892
  interface WalletHandle {
3886
3893
  readonly _native: unknown;
3887
3894
  }
3895
+ /**
3896
+ * Why a recipient can't receive an asset yet — the chain's one-time receive
3897
+ * prerequisite, when it has one. Surfaced by {@link ResolvedNetwork.recipientReady}
3898
+ * and relayed by the client's planner so an agent fixes the RECIPIENT (not its own
3899
+ * balance). Families with no prerequisite report `ready: 'n/a'` and no reason.
3900
+ */
3901
+ type RecipientReason = 'NO_TRUSTLINE' | 'NOT_REGISTERED' | 'NOT_OPTED_IN' | 'INACTIVE';
3902
+ /** What {@link ResolvedNetwork.balanceOf} returns — base-unit balances, or null per
3903
+ * field when that read was unavailable (transient/RPC), never a false 0. */
3904
+ interface WalletBalance {
3905
+ /** The payment token's balance in base units, or null if the read was unavailable. */
3906
+ token: bigint | null;
3907
+ /** The native gas coin's balance in base units, or null if unavailable. For
3908
+ * `asset === 'native'`, this equals `token`. */
3909
+ native: bigint | null;
3910
+ }
3888
3911
  interface ConfirmInfo {
3889
3912
  /** Block number (EVM) or slot (Solana) as a string — numeric-agnostic. */
3890
3913
  height: string;
@@ -3939,6 +3962,31 @@ interface ResolvedNetwork {
3939
3962
  estimateCost(accept: X402AcceptEntry, opts?: {
3940
3963
  from?: string;
3941
3964
  }): Promise<CostEstimate>;
3965
+ /**
3966
+ * Read the BOUND WALLET's own balance of the payment `asset` AND of the native
3967
+ * gas coin, in base units — what the client's `planPayment` checks affordability
3968
+ * against. RPC-read-only and NEVER throws: a field whose read was unavailable
3969
+ * (rate-limited / transient) comes back `null` (unknown), never `0` (which would
3970
+ * falsely read "broke"). For `asset === 'native'`, `token === native`.
3971
+ * Payer-side + informational — the gate never calls this. See {@link WalletBalance}.
3972
+ */
3973
+ balanceOf(wallet: WalletHandle, asset: string): Promise<WalletBalance>;
3974
+ /**
3975
+ * Can `payTo` RECEIVE `asset` on this network right now? Reports the chain's
3976
+ * one-time receive prerequisite (trustline / storage_deposit / ASA opt-in /
3977
+ * activation):
3978
+ * - `{ ready: 'n/a' }` the family has NO prerequisite (EVM, Solana, TON,
3979
+ * Tron, Sui, Aptos — and every native coin)
3980
+ * - `{ ready: true }` the prerequisite is satisfied
3981
+ * - `{ ready: false, reason }` it's missing (see {@link RecipientReason}) — fix the recipient
3982
+ * - `{ ready: 'unknown' }` the probe read failed (transient) — NEVER throws
3983
+ * Re-derives nothing from a client ref; reads only the given `payTo`. Payer-side
3984
+ * pre-flight — the gate never calls this.
3985
+ */
3986
+ recipientReady(payTo: string, asset: string): Promise<{
3987
+ ready: boolean | 'n/a' | 'unknown';
3988
+ reason?: RecipientReason;
3989
+ }>;
3942
3990
  /** Verify `ref` satisfies `accept`, RPC-only, in-process. */
3943
3991
  verify(ref: string, accept: X402AcceptEntry): Promise<VerifyResult>;
3944
3992
  }
@@ -4155,6 +4203,62 @@ interface PipRailCostQuote {
4155
4203
  /** Estimated network fee (gas) in the chain's native coin. */
4156
4204
  cost: CostEstimate;
4157
4205
  }
4206
+ /** A hard reason a rail can't be settled right now — each maps to a concrete fix. */
4207
+ type PayBlocker = 'INSUFFICIENT_TOKEN' | 'INSUFFICIENT_GAS' | 'RECIPIENT_NOT_READY' | 'OUTSIDE_POLICY';
4208
+ /** A soft flag — never blocks, always worth surfacing to the agent. */
4209
+ type PayWarning = 'SYMBOL_MISMATCH' | 'BALANCE_UNREADABLE' | 'RECIPIENT_READINESS_UNKNOWN' | 'GAS_HEURISTIC' | 'THIN_GAS_MARGIN';
4210
+ /** One offered rail, fully analysed against the bound wallet's own holdings. */
4211
+ interface PayOption {
4212
+ /** The rail this analyses (one entry from the 402's accepts[]). */
4213
+ accept: X402AcceptEntry;
4214
+ /** The priced requirement — TRUE decimals/symbol + the policy verdict. */
4215
+ quote: PipRailQuote;
4216
+ /** Estimated native-coin gas to send it (cost.basis surfaced). */
4217
+ cost: CostEstimate;
4218
+ /** The verdict for THIS rail. 'unknown' = a read failed, so payability can't be confirmed. */
4219
+ state: 'payable' | 'blocked' | 'unknown';
4220
+ /** Hard reasons it's blocked (empty when payable). */
4221
+ blockers: PayBlocker[];
4222
+ /** Soft flags (may be present even when payable). */
4223
+ warnings: PayWarning[];
4224
+ /** Live wallet holdings, human units; null = the read was unavailable (NOT zero). */
4225
+ balance: {
4226
+ token: string | null;
4227
+ native: string | null;
4228
+ };
4229
+ /** What this rail needs: the payment amount + the estimated gas, human units. */
4230
+ need: {
4231
+ token: string;
4232
+ native: string;
4233
+ };
4234
+ /** How much MORE is needed to clear a funds blocker, human units (omitted when funded). */
4235
+ shortfall?: {
4236
+ token?: string;
4237
+ native?: string;
4238
+ };
4239
+ /** Can payTo receive this asset right now, and if not, what fixes it. */
4240
+ recipient: {
4241
+ ready: boolean | 'n/a' | 'unknown';
4242
+ reason?: RecipientReason;
4243
+ fix?: string;
4244
+ };
4245
+ }
4246
+ /** The plan for ONE 402 across every rail this client can pay (its bound network). */
4247
+ interface PaymentPlan {
4248
+ url: string;
4249
+ /** The network this client is bound to (the rails it can settle). */
4250
+ network: Caip2;
4251
+ /** Top-level verdict for instant branching. */
4252
+ status: 'ready' | 'blocked' | 'unknown';
4253
+ /** True iff at least one rail is payable now (best !== null). */
4254
+ payable: boolean;
4255
+ /** The rail to use: the cheapest (within native coin) payable option, or null. */
4256
+ best: PayOption | null;
4257
+ /** Every offered+supported rail, ranked: payable → unknown → blocked. */
4258
+ options: PayOption[];
4259
+ /** When NOT payable: one human, actionable sentence on exactly what to do. */
4260
+ fundingHint: string | null;
4261
+ }
4158
4262
  interface PipRailClientOptions {
4159
4263
  /** Wallet for the chosen chain family. */
4160
4264
  wallet: WalletInput;
@@ -4193,6 +4297,16 @@ interface PipRailClientOptions {
4193
4297
  maxPaymentRetries?: number;
4194
4298
  /** Timeout (ms) for the retry leg after broadcast. Default 30_000. */
4195
4299
  retryTimeoutMs?: number;
4300
+ /**
4301
+ * Balance-aware routing: when true, `fetch()` runs `planPayment` on a 402 and
4302
+ * pays the cheapest rail the wallet can ACTUALLY settle (token + native gas +
4303
+ * recipient-ready), instead of the first policy-passing accept. If none is
4304
+ * settleable it throws {@link PaymentDeclinedError} carrying the funding hint —
4305
+ * before any send. Default **false** (defaults never change): the zero-config
4306
+ * path keeps its existing selection. Recommended for multi-rail 402s. Override
4307
+ * per call with `fetch(url, { autoRoute: true })`.
4308
+ */
4309
+ autoRoute?: boolean;
4196
4310
  /** Logger hook. Default no-op. */
4197
4311
  onEvent?: (event: PipRailEvent) => void;
4198
4312
  }
@@ -4245,6 +4359,32 @@ declare class PipRailClient {
4245
4359
  /** Aggregated snapshot of every payment this client has settled — total
4246
4360
  * count, cumulative spend per token, and the individual records. */
4247
4361
  spent(): SpendSummary;
4362
+ /**
4363
+ * Plan a payment for a gated URL — WITHOUT paying. The read-only completion of
4364
+ * the `quote()` → `estimateCost()` → **`planPayment()`** trio: it surveys every
4365
+ * rail the 402 offers on this client's chain against the wallet's OWN holdings —
4366
+ * token balance, native-coin gas, and recipient-readiness (trustline / ATA /
4367
+ * storage_deposit / ASA opt-in) — and returns, crystal-clear:
4368
+ * - `payable` + `best` — the cheapest rail the wallet can actually settle
4369
+ * - `options[]` — every rail with typed `blockers` + soft `warnings`
4370
+ * - `fundingHint` — one human sentence on exactly what to top up
4371
+ *
4372
+ * NEVER throws for a read problem (a transient/RPC failure surfaces as a rail in
4373
+ * `state: 'unknown'` + a warning, never a false "unaffordable"); returns `null`
4374
+ * when the URL isn't payment-gated (no 402); and when the 402 offers no rail on
4375
+ * this client's chain it EXPLAINS that (status `blocked` + a hint), rather than
4376
+ * throwing. Throws `InvalidEnvelopeError` only on an unparseable challenge.
4377
+ *
4378
+ * Then pay the chosen rail with `fetch(url, { autoRoute: true })`, or branch on
4379
+ * the plan yourself. No funds move.
4380
+ */
4381
+ planPayment(url: string, init?: RequestInit): Promise<PaymentPlan | null>;
4382
+ /**
4383
+ * Convenience over {@link planPayment}: can the wallet settle this URL right now?
4384
+ * `true` when at least one rail is payable — or when the URL isn't gated (a free
4385
+ * resource is trivially "affordable"). No funds move.
4386
+ */
4387
+ canAfford(url: string, init?: RequestInit): Promise<boolean>;
4248
4388
  /**
4249
4389
  * Lower-level: drive any HTTP method through the 402 flow.
4250
4390
  *
@@ -4259,6 +4399,14 @@ declare class PipRailClient {
4259
4399
  * `quote()` (read-only) and `fetch()` (which then authorises + pays).
4260
4400
  */
4261
4401
  private resolveChallenge;
4402
+ /** The candidate accepts this client could pay: our scheme, on the bound network. */
4403
+ private gatherCandidates;
4404
+ /** Build the full {@link PaymentPlan} from an already-parsed challenge + bound
4405
+ * net/wallet. Shared by `planPayment` (read-only) and `fetch`'s autoRoute. */
4406
+ private planFromChallenge;
4407
+ /** Analyse ONE rail against the wallet's holdings — quote (existing) + gas
4408
+ * (estimateCost, existing) + balanceOf + recipientReady → a {@link PayOption}. */
4409
+ private analyzeRail;
4262
4410
  /** Build the agent-facing quote for an accept: TRUE decimals/symbol (via the
4263
4411
  * driver's describeAsset) + the policy verdict + a symbol-mismatch flag. */
4264
4412
  private buildQuote;
@@ -4270,6 +4418,16 @@ declare class PipRailClient {
4270
4418
  private payAndConfirm;
4271
4419
  private retryWithProof;
4272
4420
  }
4421
+ /**
4422
+ * Plan a payment ACROSS several single-chain clients — the cross-chain brain.
4423
+ * A {@link PipRailClient} is bound to one chain (its wallet); give this one client
4424
+ * per chain the agent funds and it runs each client's {@link PipRailClient.planPayment}
4425
+ * in parallel and merges the rails into one plan, ranked payable-first. `best` is a
4426
+ * payable rail; across different native coins there's no oracle to pick the
4427
+ * fiat-cheapest, so the tiebreak is the order `clients` were given (the agent's own
4428
+ * chain preference). Returns `null` only if the URL isn't gated for any client.
4429
+ */
4430
+ declare function planAcross(clients: PipRailClient[], url: string, init?: RequestInit): Promise<PaymentPlan | null>;
4273
4431
 
4274
4432
  /** A framework-agnostic tool definition an agent runtime can register. */
4275
4433
  interface AgentTool {
@@ -4758,4 +4916,4 @@ declare function encodeXPaymentHeader(input: {
4758
4916
  x402Version?: number;
4759
4917
  }): string;
4760
4918
 
4761
- export { type AcceptOption, type AddressId, type AgentTool, type AssetId, type BuildExactParams, CHAINS, type Caip2, type ChainFamily, type ChainInput, type ChainName, type ChainPreset, type ChainSelector, type ConfirmInfo, ConfirmationTimeoutError, type CostEstimate, EIP3009_TYPES, EXACT_NETWORK_SLUGS, type EvmToken, type ExactAccept, type ExactAuthorization, type ExpressLikeMiddleware, type ExpressLikeNext, type ExpressLikeRequest, type ExpressLikeResponse, InsufficientFundsError, InvalidEnvelopeError, MaxRetriesExceededError, MissingDriverError, type NearToken, NoCompatibleAcceptError, NonReplayableBodyError, PaymentDeclinedError, type PaymentDriver, type PaymentGate, type PaymentIntent, type PaymentPolicy, PaymentTimeoutError, PipRailClient, type PipRailClientOptions, type PipRailCostQuote, PipRailError, type PipRailEvent, type PipRailQuote, type PolicyDecision, RecipientNotReadyError, type RequirePaymentOptions, type ResolveOptions, type ResolvedChain, type ResolvedNetwork, type ResolvedToken, type SolanaToken, type SpendAssetTotal, type SpendRecord, type SpendSummary, type StellarToken, type SuiToken, type TokenInfo, type TokenInput, type TonToken, type TronToken, UnknownTokenError, UnsupportedNetworkError, type VerifyErrorCode, type VerifyPaymentResult, type VerifyResult, type WalletHandle, type WalletInput, WrongChainError, WrongFamilyError, type X402AcceptEntry, type X402Challenge, type X402InvalidBody, type X402PaymentSignature, type X402Receipt, type X402ResourceObject, type XrplToken, buildChallengeHeader, buildExactAuthorization, buildReceiptHeader, buildSignatureHeader, chainIdForExactNetwork, createPaymentGate, encodeXPaymentHeader, evaluatePolicy, parseChallenge, parseExactRequirements, parseReceipt, parseSignatureHeader, paymentTools, pickAccept, registerDriver, requirePayment, resolveChain, toInsufficientFundsError, toInvalidBody };
4919
+ export { type AcceptOption, type AddressId, type AgentTool, type AlgorandToken, type AptosToken, type AssetId, type BuildExactParams, CHAINS, type Caip2, type ChainFamily, type ChainInput, type ChainName, type ChainPreset, type ChainSelector, type ConfirmInfo, ConfirmationTimeoutError, type CostEstimate, EIP3009_TYPES, EXACT_NETWORK_SLUGS, type EvmToken, type ExactAccept, type ExactAuthorization, type ExpressLikeMiddleware, type ExpressLikeNext, type ExpressLikeRequest, type ExpressLikeResponse, InsufficientFundsError, InvalidEnvelopeError, MaxRetriesExceededError, MissingDriverError, type NearToken, NoCompatibleAcceptError, NonReplayableBodyError, type PayBlocker, type PayOption, type PayWarning, PaymentDeclinedError, type PaymentDriver, type PaymentGate, type PaymentIntent, type PaymentPlan, type PaymentPolicy, PaymentTimeoutError, PipRailClient, type PipRailClientOptions, type PipRailCostQuote, PipRailError, type PipRailEvent, type PipRailQuote, type PolicyDecision, RecipientNotReadyError, type RecipientReason, type RequirePaymentOptions, type ResolveOptions, type ResolvedChain, type ResolvedNetwork, type ResolvedToken, type SolanaToken, type SpendAssetTotal, type SpendRecord, type SpendSummary, type StellarToken, type SuiToken, type TokenInfo, type TokenInput, type TonToken, type TronToken, UnknownTokenError, UnsupportedNetworkError, type VerifyErrorCode, type VerifyPaymentResult, type VerifyResult, type WalletBalance, type WalletHandle, type WalletInput, WrongChainError, WrongFamilyError, type X402AcceptEntry, type X402Challenge, type X402InvalidBody, type X402PaymentSignature, type X402Receipt, type X402ResourceObject, type XrplToken, buildChallengeHeader, buildExactAuthorization, buildReceiptHeader, buildSignatureHeader, chainIdForExactNetwork, createPaymentGate, encodeXPaymentHeader, evaluatePolicy, parseChallenge, parseExactRequirements, parseReceipt, parseSignatureHeader, paymentTools, pickAccept, planAcross, registerDriver, requirePayment, resolveChain, toInsufficientFundsError, toInvalidBody };
package/dist/index.d.ts CHANGED
@@ -3777,9 +3777,9 @@ declare function resolveChain(input: ChainInput, rpcUrlOverride?: string): Resol
3777
3777
  */
3778
3778
 
3779
3779
  /** The chain families the SDK knows about. */
3780
- type ChainFamily = 'evm' | 'solana' | 'ton' | 'stellar' | 'xrpl' | 'tron' | 'sui' | 'near' | 'aptos';
3780
+ type ChainFamily = 'evm' | 'solana' | 'ton' | 'stellar' | 'xrpl' | 'tron' | 'sui' | 'near' | 'aptos' | 'algorand';
3781
3781
  /** What chain to use: an EVM name/Chain/{id,rpcUrl}, or a non-EVM family name. */
3782
- type ChainSelector = ChainInput | 'solana' | 'ton' | 'stellar' | 'xrpl' | 'tron' | 'sui' | 'near' | 'aptos';
3782
+ type ChainSelector = ChainInput | 'solana' | 'ton' | 'stellar' | 'xrpl' | 'tron' | 'sui' | 'near' | 'aptos' | 'algorand';
3783
3783
  /** An EVM ERC-20 token, by contract address. */
3784
3784
  interface EvmToken {
3785
3785
  address: `0x${string}`;
@@ -3837,6 +3837,12 @@ interface AptosToken {
3837
3837
  decimals: number;
3838
3838
  symbol?: string;
3839
3839
  }
3840
+ /** An Algorand Standard Asset (ASA), by its numeric asset id. */
3841
+ interface AlgorandToken {
3842
+ assetId: number;
3843
+ decimals: number;
3844
+ symbol?: string;
3845
+ }
3840
3846
  /**
3841
3847
  * What to be paid in. Each driver validates the forms it accepts:
3842
3848
  * - 'native' the chain's native coin (ETH, BNB, SOL, TON, XLM, XRP)
@@ -3850,8 +3856,9 @@ interface AptosToken {
3850
3856
  * - SuiToken any coin (Sui)
3851
3857
  * - NearToken any NEP-141 (NEAR)
3852
3858
  * - AptosToken any Fungible Asset (Aptos)
3859
+ * - AlgorandToken any ASA (Algorand)
3853
3860
  */
3854
- type TokenInput = 'native' | (string & {}) | EvmToken | SolanaToken | TonToken | StellarToken | XrplToken | TronToken | SuiToken | NearToken | AptosToken;
3861
+ type TokenInput = 'native' | (string & {}) | EvmToken | SolanaToken | TonToken | StellarToken | XrplToken | TronToken | SuiToken | NearToken | AptosToken | AlgorandToken;
3855
3862
  /** What a driver resolves a TokenInput into. `asset`: 0x | base58 mint | 'native'. */
3856
3863
  interface ResolvedToken {
3857
3864
  asset: string;
@@ -3885,6 +3892,22 @@ interface CostEstimate {
3885
3892
  interface WalletHandle {
3886
3893
  readonly _native: unknown;
3887
3894
  }
3895
+ /**
3896
+ * Why a recipient can't receive an asset yet — the chain's one-time receive
3897
+ * prerequisite, when it has one. Surfaced by {@link ResolvedNetwork.recipientReady}
3898
+ * and relayed by the client's planner so an agent fixes the RECIPIENT (not its own
3899
+ * balance). Families with no prerequisite report `ready: 'n/a'` and no reason.
3900
+ */
3901
+ type RecipientReason = 'NO_TRUSTLINE' | 'NOT_REGISTERED' | 'NOT_OPTED_IN' | 'INACTIVE';
3902
+ /** What {@link ResolvedNetwork.balanceOf} returns — base-unit balances, or null per
3903
+ * field when that read was unavailable (transient/RPC), never a false 0. */
3904
+ interface WalletBalance {
3905
+ /** The payment token's balance in base units, or null if the read was unavailable. */
3906
+ token: bigint | null;
3907
+ /** The native gas coin's balance in base units, or null if unavailable. For
3908
+ * `asset === 'native'`, this equals `token`. */
3909
+ native: bigint | null;
3910
+ }
3888
3911
  interface ConfirmInfo {
3889
3912
  /** Block number (EVM) or slot (Solana) as a string — numeric-agnostic. */
3890
3913
  height: string;
@@ -3939,6 +3962,31 @@ interface ResolvedNetwork {
3939
3962
  estimateCost(accept: X402AcceptEntry, opts?: {
3940
3963
  from?: string;
3941
3964
  }): Promise<CostEstimate>;
3965
+ /**
3966
+ * Read the BOUND WALLET's own balance of the payment `asset` AND of the native
3967
+ * gas coin, in base units — what the client's `planPayment` checks affordability
3968
+ * against. RPC-read-only and NEVER throws: a field whose read was unavailable
3969
+ * (rate-limited / transient) comes back `null` (unknown), never `0` (which would
3970
+ * falsely read "broke"). For `asset === 'native'`, `token === native`.
3971
+ * Payer-side + informational — the gate never calls this. See {@link WalletBalance}.
3972
+ */
3973
+ balanceOf(wallet: WalletHandle, asset: string): Promise<WalletBalance>;
3974
+ /**
3975
+ * Can `payTo` RECEIVE `asset` on this network right now? Reports the chain's
3976
+ * one-time receive prerequisite (trustline / storage_deposit / ASA opt-in /
3977
+ * activation):
3978
+ * - `{ ready: 'n/a' }` the family has NO prerequisite (EVM, Solana, TON,
3979
+ * Tron, Sui, Aptos — and every native coin)
3980
+ * - `{ ready: true }` the prerequisite is satisfied
3981
+ * - `{ ready: false, reason }` it's missing (see {@link RecipientReason}) — fix the recipient
3982
+ * - `{ ready: 'unknown' }` the probe read failed (transient) — NEVER throws
3983
+ * Re-derives nothing from a client ref; reads only the given `payTo`. Payer-side
3984
+ * pre-flight — the gate never calls this.
3985
+ */
3986
+ recipientReady(payTo: string, asset: string): Promise<{
3987
+ ready: boolean | 'n/a' | 'unknown';
3988
+ reason?: RecipientReason;
3989
+ }>;
3942
3990
  /** Verify `ref` satisfies `accept`, RPC-only, in-process. */
3943
3991
  verify(ref: string, accept: X402AcceptEntry): Promise<VerifyResult>;
3944
3992
  }
@@ -4155,6 +4203,62 @@ interface PipRailCostQuote {
4155
4203
  /** Estimated network fee (gas) in the chain's native coin. */
4156
4204
  cost: CostEstimate;
4157
4205
  }
4206
+ /** A hard reason a rail can't be settled right now — each maps to a concrete fix. */
4207
+ type PayBlocker = 'INSUFFICIENT_TOKEN' | 'INSUFFICIENT_GAS' | 'RECIPIENT_NOT_READY' | 'OUTSIDE_POLICY';
4208
+ /** A soft flag — never blocks, always worth surfacing to the agent. */
4209
+ type PayWarning = 'SYMBOL_MISMATCH' | 'BALANCE_UNREADABLE' | 'RECIPIENT_READINESS_UNKNOWN' | 'GAS_HEURISTIC' | 'THIN_GAS_MARGIN';
4210
+ /** One offered rail, fully analysed against the bound wallet's own holdings. */
4211
+ interface PayOption {
4212
+ /** The rail this analyses (one entry from the 402's accepts[]). */
4213
+ accept: X402AcceptEntry;
4214
+ /** The priced requirement — TRUE decimals/symbol + the policy verdict. */
4215
+ quote: PipRailQuote;
4216
+ /** Estimated native-coin gas to send it (cost.basis surfaced). */
4217
+ cost: CostEstimate;
4218
+ /** The verdict for THIS rail. 'unknown' = a read failed, so payability can't be confirmed. */
4219
+ state: 'payable' | 'blocked' | 'unknown';
4220
+ /** Hard reasons it's blocked (empty when payable). */
4221
+ blockers: PayBlocker[];
4222
+ /** Soft flags (may be present even when payable). */
4223
+ warnings: PayWarning[];
4224
+ /** Live wallet holdings, human units; null = the read was unavailable (NOT zero). */
4225
+ balance: {
4226
+ token: string | null;
4227
+ native: string | null;
4228
+ };
4229
+ /** What this rail needs: the payment amount + the estimated gas, human units. */
4230
+ need: {
4231
+ token: string;
4232
+ native: string;
4233
+ };
4234
+ /** How much MORE is needed to clear a funds blocker, human units (omitted when funded). */
4235
+ shortfall?: {
4236
+ token?: string;
4237
+ native?: string;
4238
+ };
4239
+ /** Can payTo receive this asset right now, and if not, what fixes it. */
4240
+ recipient: {
4241
+ ready: boolean | 'n/a' | 'unknown';
4242
+ reason?: RecipientReason;
4243
+ fix?: string;
4244
+ };
4245
+ }
4246
+ /** The plan for ONE 402 across every rail this client can pay (its bound network). */
4247
+ interface PaymentPlan {
4248
+ url: string;
4249
+ /** The network this client is bound to (the rails it can settle). */
4250
+ network: Caip2;
4251
+ /** Top-level verdict for instant branching. */
4252
+ status: 'ready' | 'blocked' | 'unknown';
4253
+ /** True iff at least one rail is payable now (best !== null). */
4254
+ payable: boolean;
4255
+ /** The rail to use: the cheapest (within native coin) payable option, or null. */
4256
+ best: PayOption | null;
4257
+ /** Every offered+supported rail, ranked: payable → unknown → blocked. */
4258
+ options: PayOption[];
4259
+ /** When NOT payable: one human, actionable sentence on exactly what to do. */
4260
+ fundingHint: string | null;
4261
+ }
4158
4262
  interface PipRailClientOptions {
4159
4263
  /** Wallet for the chosen chain family. */
4160
4264
  wallet: WalletInput;
@@ -4193,6 +4297,16 @@ interface PipRailClientOptions {
4193
4297
  maxPaymentRetries?: number;
4194
4298
  /** Timeout (ms) for the retry leg after broadcast. Default 30_000. */
4195
4299
  retryTimeoutMs?: number;
4300
+ /**
4301
+ * Balance-aware routing: when true, `fetch()` runs `planPayment` on a 402 and
4302
+ * pays the cheapest rail the wallet can ACTUALLY settle (token + native gas +
4303
+ * recipient-ready), instead of the first policy-passing accept. If none is
4304
+ * settleable it throws {@link PaymentDeclinedError} carrying the funding hint —
4305
+ * before any send. Default **false** (defaults never change): the zero-config
4306
+ * path keeps its existing selection. Recommended for multi-rail 402s. Override
4307
+ * per call with `fetch(url, { autoRoute: true })`.
4308
+ */
4309
+ autoRoute?: boolean;
4196
4310
  /** Logger hook. Default no-op. */
4197
4311
  onEvent?: (event: PipRailEvent) => void;
4198
4312
  }
@@ -4245,6 +4359,32 @@ declare class PipRailClient {
4245
4359
  /** Aggregated snapshot of every payment this client has settled — total
4246
4360
  * count, cumulative spend per token, and the individual records. */
4247
4361
  spent(): SpendSummary;
4362
+ /**
4363
+ * Plan a payment for a gated URL — WITHOUT paying. The read-only completion of
4364
+ * the `quote()` → `estimateCost()` → **`planPayment()`** trio: it surveys every
4365
+ * rail the 402 offers on this client's chain against the wallet's OWN holdings —
4366
+ * token balance, native-coin gas, and recipient-readiness (trustline / ATA /
4367
+ * storage_deposit / ASA opt-in) — and returns, crystal-clear:
4368
+ * - `payable` + `best` — the cheapest rail the wallet can actually settle
4369
+ * - `options[]` — every rail with typed `blockers` + soft `warnings`
4370
+ * - `fundingHint` — one human sentence on exactly what to top up
4371
+ *
4372
+ * NEVER throws for a read problem (a transient/RPC failure surfaces as a rail in
4373
+ * `state: 'unknown'` + a warning, never a false "unaffordable"); returns `null`
4374
+ * when the URL isn't payment-gated (no 402); and when the 402 offers no rail on
4375
+ * this client's chain it EXPLAINS that (status `blocked` + a hint), rather than
4376
+ * throwing. Throws `InvalidEnvelopeError` only on an unparseable challenge.
4377
+ *
4378
+ * Then pay the chosen rail with `fetch(url, { autoRoute: true })`, or branch on
4379
+ * the plan yourself. No funds move.
4380
+ */
4381
+ planPayment(url: string, init?: RequestInit): Promise<PaymentPlan | null>;
4382
+ /**
4383
+ * Convenience over {@link planPayment}: can the wallet settle this URL right now?
4384
+ * `true` when at least one rail is payable — or when the URL isn't gated (a free
4385
+ * resource is trivially "affordable"). No funds move.
4386
+ */
4387
+ canAfford(url: string, init?: RequestInit): Promise<boolean>;
4248
4388
  /**
4249
4389
  * Lower-level: drive any HTTP method through the 402 flow.
4250
4390
  *
@@ -4259,6 +4399,14 @@ declare class PipRailClient {
4259
4399
  * `quote()` (read-only) and `fetch()` (which then authorises + pays).
4260
4400
  */
4261
4401
  private resolveChallenge;
4402
+ /** The candidate accepts this client could pay: our scheme, on the bound network. */
4403
+ private gatherCandidates;
4404
+ /** Build the full {@link PaymentPlan} from an already-parsed challenge + bound
4405
+ * net/wallet. Shared by `planPayment` (read-only) and `fetch`'s autoRoute. */
4406
+ private planFromChallenge;
4407
+ /** Analyse ONE rail against the wallet's holdings — quote (existing) + gas
4408
+ * (estimateCost, existing) + balanceOf + recipientReady → a {@link PayOption}. */
4409
+ private analyzeRail;
4262
4410
  /** Build the agent-facing quote for an accept: TRUE decimals/symbol (via the
4263
4411
  * driver's describeAsset) + the policy verdict + a symbol-mismatch flag. */
4264
4412
  private buildQuote;
@@ -4270,6 +4418,16 @@ declare class PipRailClient {
4270
4418
  private payAndConfirm;
4271
4419
  private retryWithProof;
4272
4420
  }
4421
+ /**
4422
+ * Plan a payment ACROSS several single-chain clients — the cross-chain brain.
4423
+ * A {@link PipRailClient} is bound to one chain (its wallet); give this one client
4424
+ * per chain the agent funds and it runs each client's {@link PipRailClient.planPayment}
4425
+ * in parallel and merges the rails into one plan, ranked payable-first. `best` is a
4426
+ * payable rail; across different native coins there's no oracle to pick the
4427
+ * fiat-cheapest, so the tiebreak is the order `clients` were given (the agent's own
4428
+ * chain preference). Returns `null` only if the URL isn't gated for any client.
4429
+ */
4430
+ declare function planAcross(clients: PipRailClient[], url: string, init?: RequestInit): Promise<PaymentPlan | null>;
4273
4431
 
4274
4432
  /** A framework-agnostic tool definition an agent runtime can register. */
4275
4433
  interface AgentTool {
@@ -4758,4 +4916,4 @@ declare function encodeXPaymentHeader(input: {
4758
4916
  x402Version?: number;
4759
4917
  }): string;
4760
4918
 
4761
- export { type AcceptOption, type AddressId, type AgentTool, type AssetId, type BuildExactParams, CHAINS, type Caip2, type ChainFamily, type ChainInput, type ChainName, type ChainPreset, type ChainSelector, type ConfirmInfo, ConfirmationTimeoutError, type CostEstimate, EIP3009_TYPES, EXACT_NETWORK_SLUGS, type EvmToken, type ExactAccept, type ExactAuthorization, type ExpressLikeMiddleware, type ExpressLikeNext, type ExpressLikeRequest, type ExpressLikeResponse, InsufficientFundsError, InvalidEnvelopeError, MaxRetriesExceededError, MissingDriverError, type NearToken, NoCompatibleAcceptError, NonReplayableBodyError, PaymentDeclinedError, type PaymentDriver, type PaymentGate, type PaymentIntent, type PaymentPolicy, PaymentTimeoutError, PipRailClient, type PipRailClientOptions, type PipRailCostQuote, PipRailError, type PipRailEvent, type PipRailQuote, type PolicyDecision, RecipientNotReadyError, type RequirePaymentOptions, type ResolveOptions, type ResolvedChain, type ResolvedNetwork, type ResolvedToken, type SolanaToken, type SpendAssetTotal, type SpendRecord, type SpendSummary, type StellarToken, type SuiToken, type TokenInfo, type TokenInput, type TonToken, type TronToken, UnknownTokenError, UnsupportedNetworkError, type VerifyErrorCode, type VerifyPaymentResult, type VerifyResult, type WalletHandle, type WalletInput, WrongChainError, WrongFamilyError, type X402AcceptEntry, type X402Challenge, type X402InvalidBody, type X402PaymentSignature, type X402Receipt, type X402ResourceObject, type XrplToken, buildChallengeHeader, buildExactAuthorization, buildReceiptHeader, buildSignatureHeader, chainIdForExactNetwork, createPaymentGate, encodeXPaymentHeader, evaluatePolicy, parseChallenge, parseExactRequirements, parseReceipt, parseSignatureHeader, paymentTools, pickAccept, registerDriver, requirePayment, resolveChain, toInsufficientFundsError, toInvalidBody };
4919
+ export { type AcceptOption, type AddressId, type AgentTool, type AlgorandToken, type AptosToken, type AssetId, type BuildExactParams, CHAINS, type Caip2, type ChainFamily, type ChainInput, type ChainName, type ChainPreset, type ChainSelector, type ConfirmInfo, ConfirmationTimeoutError, type CostEstimate, EIP3009_TYPES, EXACT_NETWORK_SLUGS, type EvmToken, type ExactAccept, type ExactAuthorization, type ExpressLikeMiddleware, type ExpressLikeNext, type ExpressLikeRequest, type ExpressLikeResponse, InsufficientFundsError, InvalidEnvelopeError, MaxRetriesExceededError, MissingDriverError, type NearToken, NoCompatibleAcceptError, NonReplayableBodyError, type PayBlocker, type PayOption, type PayWarning, PaymentDeclinedError, type PaymentDriver, type PaymentGate, type PaymentIntent, type PaymentPlan, type PaymentPolicy, PaymentTimeoutError, PipRailClient, type PipRailClientOptions, type PipRailCostQuote, PipRailError, type PipRailEvent, type PipRailQuote, type PolicyDecision, RecipientNotReadyError, type RecipientReason, type RequirePaymentOptions, type ResolveOptions, type ResolvedChain, type ResolvedNetwork, type ResolvedToken, type SolanaToken, type SpendAssetTotal, type SpendRecord, type SpendSummary, type StellarToken, type SuiToken, type TokenInfo, type TokenInput, type TonToken, type TronToken, UnknownTokenError, UnsupportedNetworkError, type VerifyErrorCode, type VerifyPaymentResult, type VerifyResult, type WalletBalance, type WalletHandle, type WalletInput, WrongChainError, WrongFamilyError, type X402AcceptEntry, type X402Challenge, type X402InvalidBody, type X402PaymentSignature, type X402Receipt, type X402ResourceObject, type XrplToken, buildChallengeHeader, buildExactAuthorization, buildReceiptHeader, buildSignatureHeader, chainIdForExactNetwork, createPaymentGate, encodeXPaymentHeader, evaluatePolicy, parseChallenge, parseExactRequirements, parseReceipt, parseSignatureHeader, paymentTools, pickAccept, planAcross, registerDriver, requirePayment, resolveChain, toInsufficientFundsError, toInvalidBody };