@dexterai/x402 3.15.0 → 3.16.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.
@@ -1,164 +1,15 @@
1
+ import { P as PayAndFetchOptions, a as PayResult, b as PaymentStrategy, N as NetworkRef, c as PaymentChallenge, C as ChallengeOption } from '../types-ZjcxOAbW.js';
1
2
  import { W as WalletSet, S as SettlementProbe, a as SolanaWallet, E as EvmWallet, A as AccessPassClientConfig, P as PaymentAccept } from '../types-xQu1U4xk.js';
2
3
  export { e as AccessPassInfo, d as AccessPassTier, C as ChainAdapter, X as X402Error, b as createEvmAdapter, c as createSolanaAdapter } from '../types-xQu1U4xk.js';
3
- import { T as Tab } from '../types-DEnVPFxF.js';
4
4
  import { SIWxSigner } from '@x402/extensions/sign-in-with-x';
5
5
  import { Keypair } from '@solana/web3.js';
6
6
  export { P as PaymentReceipt, d as X402Client, X as X402ClientConfig, c as createX402Client, f as fireImpressionBeacon, b as getPaymentReceipt, a as getSponsoredAccessInfo, g as getSponsoredRecommendations } from '../x402-client-Ug0vrj74.js';
7
7
  export { FormattedResource as CapabilityAPI, CapabilitySearchOptions, CapabilitySearchResult, NoMatchReason, capabilitySearch } from '@dexterai/x402-core';
8
8
  export { B as BASE_MAINNET, D as DEXTER_FACILITATOR_URL, S as SOLANA_MAINNET, U as USDC_MINT } from '../constants-D41hDAG6.js';
9
9
  export { SponsoredAccessSettlementInfo, SponsoredRecommendation } from '@dexterai/x402-ads-types';
10
+ import '../types-DEnVPFxF.js';
10
11
  import '@dexterai/vault/types';
11
12
 
12
- /**
13
- * Shared contract for the x402 version seam. Both the v1 and v2 strategy
14
- * modules implement PaymentStrategy. Callers depend ONLY on this file —
15
- * never on a specific version module.
16
- */
17
-
18
- /** A network reference, kept in BOTH forms so neither version loses info. */
19
- interface NetworkRef {
20
- /** CAIP-2 form, e.g. "eip155:8453", "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp". */
21
- caip2: string;
22
- /** Bare form, e.g. "base", "solana". */
23
- bare: string;
24
- /** "evm" | "svm" — which signer family. */
25
- family: 'evm' | 'svm';
26
- }
27
- /** One payment option parsed from a 402 challenge, version-normalised. */
28
- interface ChallengeOption {
29
- scheme: string;
30
- network: NetworkRef;
31
- /** Atomic amount as a string (e.g. "2000"). */
32
- amount: string;
33
- asset: string;
34
- payTo: string;
35
- /** Optional — v1 challenges may omit it; a strategy supplies a default when absent. */
36
- maxTimeoutSeconds?: number;
37
- /** Scheme-specific extras, passed through verbatim from the merchant. */
38
- extra?: Record<string, unknown>;
39
- }
40
- /** A 402 challenge, normalised across v1 and v2. */
41
- interface PaymentChallenge {
42
- x402Version: 1 | 2;
43
- options: ChallengeOption[];
44
- resourceUrl?: string;
45
- }
46
- /**
47
- * Result of a paid fetch. Never throws for an expected failure.
48
- *
49
- * The `ok: true` branch is further discriminated by `paid`:
50
- * - `paid: true` — the endpoint demanded payment and we paid; `amountPaid`
51
- * and `network` are present, `txSignature` optional.
52
- * `response` is usually the merchant's response, but is
53
- * `undefined` when the payment settled and the merchant
54
- * never delivered a response before the deadline (a
55
- * confirmed-but-unanswered payment — see `payment_unconfirmed`
56
- * below for the unconfirmed counterpart).
57
- * - `paid: false` — the endpoint returned a non-402 directly; no payment
58
- * was attempted. Only `response` is present, because no
59
- * payment-related fields are meaningful in that case.
60
- *
61
- * Callers should narrow on `paid` before reading payment fields. Previously
62
- * (3.8.x and earlier) the dispatcher returned a phantom `network` placeholder
63
- * on the unpaid branch; the discriminator forces a correct read.
64
- */
65
- type PayResult = {
66
- ok: true;
67
- paid: true;
68
- /**
69
- * The merchant's response. `undefined` when the payment was confirmed
70
- * settled but the merchant did not respond before the deadline — you
71
- * paid, the merchant never answered. Always check before use.
72
- */
73
- response: Response | undefined;
74
- /** Atomic amount actually paid. */
75
- amountPaid: string;
76
- network: NetworkRef;
77
- txSignature?: string;
78
- } | {
79
- ok: true;
80
- paid: false;
81
- response: Response;
82
- } | {
83
- ok: false;
84
- reason: 'unsupported_network' | 'insufficient_funds'
85
- /** The merchant rejected the payment itself — bad/declined payload,
86
- * failed verification. Our side: check the payment. */
87
- | 'merchant_rejected'
88
- /** The merchant ACCEPTED the payment shape but their own settlement
89
- * failed (their facilitator errored). Not our payload — a
90
- * merchant-side defect. `detail` carries their verbatim error. */
91
- | 'settlement_failed' | 'no_payment_options'
92
- /** No payment was sent before the deadline — the unpaid probe (or
93
- * build/sign) ran past the pre-payment timeout. No money moved;
94
- * safe to retry. */
95
- | 'timeout'
96
- /** The payment authorization WAS sent to the merchant, the merchant
97
- * did not respond before the deadline, and settlement could not be
98
- * confirmed. The payment MAY have settled on-chain. DO NOT
99
- * blind-retry — a retry signs a fresh authorization and can pay
100
- * again. `detail` explains the state. */
101
- | 'payment_unconfirmed' | 'budget_exceeded' | 'error';
102
- detail?: string;
103
- };
104
-
105
- /** Options for a paid fetch. */
106
- interface PayAndFetchOptions {
107
- /** Max total atomic spend for this call. */
108
- maxAmountAtomic?: string;
109
- /**
110
- * Pre-payment timeout in ms — the deadline for the unpaid probe and the
111
- * build/sign step, i.e. everything BEFORE the payment authorization is
112
- * sent. Exceeding it yields `reason: 'timeout'` (no money moved, safe to
113
- * retry). Default 15000.
114
- *
115
- * This does NOT bound the wait for the merchant's response once payment
116
- * has been dispatched — see `responseTimeoutMs`. The two phases have
117
- * separate deadlines on purpose: once the payment is out the door,
118
- * aborting the wait does not un-spend the money.
119
- */
120
- timeoutMs?: number;
121
- /**
122
- * Post-payment timeout in ms — the deadline for the merchant's response
123
- * AFTER the payment authorization has been sent. Exceeding it does not
124
- * yield `'timeout'`; it yields `'payment_unconfirmed'` (or, once on-chain
125
- * confirmation lands, a confirmed `paid: true`). Default 120000.
126
- *
127
- * Generous by design: research / scout / agent endpoints routinely take
128
- * tens of seconds, and the money is already committed once this phase
129
- * begins — there is no benefit to a tight deadline here.
130
- */
131
- responseTimeoutMs?: number;
132
- /**
133
- * Solana RPC endpoint for v1 SVM payment signing. v1 Solana `exact`
134
- * signing builds a real transaction and needs RPC access (mint lookup,
135
- * recent blockhash). Ignored for EVM-only flows. Defaults to the public
136
- * Solana RPC when omitted — callers should pass their own for
137
- * reliability.
138
- */
139
- solanaRpcUrl?: string;
140
- /**
141
- * An open spend-tab to pay `tab`-scheme accepts entries with. Used only
142
- * when the 402 offers scheme "tab" AND the option's payTo matches the
143
- * counterparty this tab was opened against — otherwise ignored and the
144
- * normal exact/batch path runs.
145
- */
146
- tab?: Tab;
147
- }
148
- /**
149
- * The contract each version module implements.
150
- *
151
- * parseChallenge: given a raw 402 Response, extract the challenge — or
152
- * null if this strategy does not recognise it as its version.
153
- * pay: given a parsed challenge, sign + send the paid request, return
154
- * the merchant's response.
155
- */
156
- interface PaymentStrategy {
157
- readonly version: 1 | 2;
158
- parseChallenge(res: Response): Promise<PaymentChallenge | null>;
159
- pay(url: string, requestInit: RequestInit, challenge: PaymentChallenge, wallets: WalletSet, opts: PayAndFetchOptions): Promise<PayResult>;
160
- }
161
-
162
13
  /**
163
14
  * The x402 version dispatcher — the ONLY code in the stack that decides
164
15
  * v1 vs v2. It probes the endpoint once; if the response is a 402, it
@@ -565,4 +416,4 @@ interface BudgetAccount {
565
416
  */
566
417
  declare function createBudgetAccount(config: BudgetAccountConfig): BudgetAccount;
567
418
 
568
- export { AccessPassClientConfig, type BudgetAccount, type BudgetAccountConfig, type BudgetConfig, type ChallengeOption, KEYPAIR_SYMBOL, type KeypairWallet, type NetworkRef, type PayAndFetchOptions, type PayResult, type PaymentChallenge, type PaymentRecord, type PaymentStrategy, type V1HeaderResult, WalletSet, type WrapFetchOptions, buildV1PaymentHeader, createBudgetAccount, createEvmKeypairWallet, createKeypairWallet, detectStrategy, isEvmKeypairWallet, isKeypairWallet, payAndFetch, toNetworkRef, toSiwxSigner, wrapFetch };
419
+ export { AccessPassClientConfig, type BudgetAccount, type BudgetAccountConfig, type BudgetConfig, ChallengeOption, KEYPAIR_SYMBOL, type KeypairWallet, NetworkRef, PayAndFetchOptions, PayResult, PaymentChallenge, type PaymentRecord, PaymentStrategy, type V1HeaderResult, WalletSet, type WrapFetchOptions, buildV1PaymentHeader, createBudgetAccount, createEvmKeypairWallet, createKeypairWallet, detectStrategy, isEvmKeypairWallet, isKeypairWallet, payAndFetch, toNetworkRef, toSiwxSigner, wrapFetch };
@@ -1 +1 @@
1
- var Ut=Object.defineProperty;var ut=(n,e)=>()=>(n&&(e=n(n=0)),e);var Bt=(n,e)=>{for(var t in e)Ut(n,t,{get:e[t],enumerable:!0})};function sn(n){if(n.length>=255)throw new TypeError("Alphabet too long");let e=new Uint8Array(256);for(let s=0;s<e.length;s++)e[s]=255;for(let s=0;s<n.length;s++){let p=n.charAt(s),f=p.charCodeAt(0);if(e[f]!==255)throw new TypeError(p+" is ambiguous");e[f]=s}let t=n.length,r=n.charAt(0),o=Math.log(t)/Math.log(256),a=Math.log(256)/Math.log(t);function i(s){if(s instanceof Uint8Array||(ArrayBuffer.isView(s)?s=new Uint8Array(s.buffer,s.byteOffset,s.byteLength):Array.isArray(s)&&(s=Uint8Array.from(s))),!(s instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(s.length===0)return"";let p=0,f=0,g=0,w=s.length;for(;g!==w&&s[g]===0;)g++,p++;let u=(w-g)*a+1>>>0,A=new Uint8Array(u);for(;g!==w;){let y=s[g],S=0;for(let P=u-1;(y!==0||S<f)&&P!==-1;P--,S++)y+=256*A[P]>>>0,A[P]=y%t>>>0,y=y/t>>>0;if(y!==0)throw new Error("Non-zero carry");f=S,g++}let m=u-f;for(;m!==u&&A[m]===0;)m++;let h=r.repeat(p);for(;m<u;++m)h+=n.charAt(A[m]);return h}function c(s){if(typeof s!="string")throw new TypeError("Expected String");if(s.length===0)return new Uint8Array;let p=0,f=0,g=0;for(;s[p]===r;)f++,p++;let w=(s.length-p)*o+1>>>0,u=new Uint8Array(w);for(;p<s.length;){let y=s.charCodeAt(p);if(y>255)return;let S=e[y];if(S===255)return;let P=0;for(let k=w-1;(S!==0||P<g)&&k!==-1;k--,P++)S+=t*u[k]>>>0,u[k]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");g=P,p++}let A=w-g;for(;A!==w&&u[A]===0;)A++;let m=new Uint8Array(f+(w-A)),h=f;for(;A!==w;)m[h++]=u[A++];return m}function l(s){let p=c(s);if(p)return p;throw new Error("Non-base"+t+" character")}return{encode:i,decodeUnsafe:c,decode:l}}var Rt,vt=ut(()=>{"use strict";Rt=sn});var Ct={};Bt(Ct,{default:()=>ln});var cn,ln,_t=ut(()=>{"use strict";vt();cn="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ln=Rt(cn)});var pt=[{caip2:"eip155:8453",bare:"base",family:"evm"},{caip2:"eip155:1",bare:"ethereum",family:"evm"},{caip2:"eip155:137",bare:"polygon",family:"evm"},{caip2:"eip155:42161",bare:"arbitrum",family:"evm"},{caip2:"eip155:10",bare:"optimism",family:"evm"},{caip2:"eip155:43114",bare:"avalanche",family:"evm"},{caip2:"eip155:56",bare:"bsc",family:"evm"},{caip2:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",bare:"solana",family:"svm"}],Dt=new Map(pt.map(n=>[n.caip2.toLowerCase(),n])),Mt=new Map(pt.map(n=>[n.bare.toLowerCase(),n]));function le(n){if(!n)return null;let e=n.toLowerCase(),t=Dt.get(e)||Mt.get(e);return t?{caip2:t.caip2,bare:t.bare,family:t.family}:null}var be="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",$e="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Ke="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",X=be,xe=$e,Ee=Ke,ee="eip155:8453",ue="eip155:84532",pe="eip155:42161",me="eip155:137",de="eip155:10",fe="eip155:43114",ge="eip155:56",ye="eip155:1187947933",he="eip155:324705682",Ae="eip155:1",z=ee,We=ue,Te=pe,Pe=me,Re=de,ve=fe,Ce=ge,_e=ye,Ie=he,Ne=Ae,Le="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",mt="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",dt="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",et="0x55d398326f99059fF775485246999027B3197955",Ve="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",Fe={[ge]:Ve,[ee]:dt,[ue]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[pe]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[me]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[de]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[fe]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[ye]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[he]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[Ae]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},qe={[et]:{symbol:"USDT",decimals:18},[Ve]:{symbol:"USDC",decimals:18}};var Y="0x000000000022D473030F116dDEE9F6B43aC78BA3",ke="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",Oe={[ge]:56,[ee]:8453,[ue]:84532,[pe]:42161,[me]:137,[de]:10,[fe]:43114,[ye]:1187947933,[he]:324705682,[Ae]:1},te={[be]:"https://api.dexter.cash/api/solana/rpc",[$e]:"https://api.devnet.solana.com",[Ke]:"https://api.testnet.solana.com"},U={[ge]:"https://api.dexter.cash/api/evm/bsc/rpc",[ee]:"https://api.dexter.cash/api/base/rpc",[ue]:"https://sepolia.base.org",[pe]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[me]:"https://api.dexter.cash/api/evm/polygon/rpc",[de]:"https://api.dexter.cash/api/evm/optimism/rpc",[fe]:"https://api.dexter.cash/api/evm/avalanche/rpc",[ye]:"https://skale-base.skalenodes.com/v1/base",[he]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[Ae]:"https://eth.llamarpc.com"},ft="https://x402.dexter.cash";var C=class n extends Error{code;details;constructor(e,t,r){super(t),this.name="X402Error",this.code=e,this.details=r,Object.setPrototypeOf(this,n.prototype)}};import{PublicKey as ne,Connection as tt,TransactionMessage as $t,VersionedTransaction as Kt,ComputeBudgetProgram as gt}from"@solana/web3.js";import{getAssociatedTokenAddress as nt,getAccount as Wt,createTransferCheckedInstruction as Lt,getMint as Vt,TOKEN_PROGRAM_ID as yt,TOKEN_2022_PROGRAM_ID as He}from"@solana/spl-token";var Ft=12e3,qt=1;function re(n){if(!n||typeof n!="object")return!1;let e=n;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var je=class{name="Solana";networks=[X,xe,Ee];config;log;constructor(e={}){this.config=e,this.log=e.verbose?console.log.bind(console,"[x402:solana]"):()=>{}}canHandle(e){return!!(this.networks.includes(e)||e==="solana"||e==="solana-devnet"||e==="solana-testnet"||e.startsWith("solana:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:te[e]?te[e]:e==="solana"?te[X]:e==="solana-devnet"?te[xe]:e==="solana-testnet"?te[Ee]:te[X]}getAddress(e){return re(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return re(e)?e.publicKey!==null:!1}async getBalance(e,t,r){if(!re(t)||!t.publicKey)return 0;let o=r||this.getDefaultRpcUrl(e.network),a=new tt(o,"confirmed"),i=new ne(t.publicKey.toBase58()),c=new ne(e.asset);try{let s=(await a.getAccountInfo(c,"confirmed"))?.owner.toBase58()===He.toBase58()?He:yt,p=await nt(c,i,!1,s),f=await Wt(a,p,void 0,s),g=e.extra?.decimals??6;return Number(f.amount)/Math.pow(10,g)}catch(l){if(l&&typeof l=="object"&&"name"in l&&(l.name==="TokenAccountNotFoundError"||l.name==="TokenInvalidAccountOwnerError"))return 0;throw l}}async buildTransaction(e,t,r){if(!re(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let o=r||this.getDefaultRpcUrl(e.network),a=new tt(o,"confirmed"),i=new ne(t.publicKey.toBase58()),{payTo:c,asset:l,extra:s}=e,p=e.amount??e.maxAmountRequired;if(!p)throw new Error("Missing amount in payment requirements");if(!s?.feePayer)throw new Error("Missing feePayer in payment requirements");let f=new ne(s.feePayer),g=new ne(l),w=new ne(c);this.log("Building transaction:",{from:i.toBase58(),to:c,amount:p,asset:l,feePayer:s.feePayer});let u=[];u.push(gt.setComputeUnitLimit({units:Ft})),u.push(gt.setComputeUnitPrice({microLamports:qt}));let A=await a.getAccountInfo(g,"confirmed");if(!A)throw new Error(`Token mint ${l} not found`);let m=A.owner.toBase58()===He.toBase58()?He:yt,h=await Vt(a,g,void 0,m);typeof s?.decimals=="number"&&h.decimals!==s.decimals&&this.log(`Decimals mismatch: requirements say ${s.decimals}, mint says ${h.decimals}`);let y=await nt(g,i,!1,m),S=await nt(g,w,!0,m);if(!await a.getAccountInfo(y,"confirmed"))throw new Error(`No token account found for ${l}. Please ensure you have USDC in your wallet.`);if(!await a.getAccountInfo(S,"confirmed"))throw new Error(`Seller token account not found. The seller (${c}) must have a USDC account.`);let F=BigInt(p);u.push(Lt(y,g,S,i,F,h.decimals,[],m));let{blockhash:K}=await a.getLatestBlockhash("confirmed"),G=new $t({payerKey:f,recentBlockhash:K,instructions:u}).compileToV0Message(),D=new Kt(G),b=await t.signTransaction(D);return this.log("Transaction signed successfully"),{serialized:Buffer.from(b.serialize()).toString("base64"),settlementProbe:{kind:"solana",sourceAta:y.toBase58(),destinationAta:S.toBase58(),asset:l,amount:p,blockhash:K}}}async confirmSettlement(e,t){if(e.kind!=="solana")throw new Error(`SolanaAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`);let r=new tt(t,"confirmed"),o=new ne(e.destinationAta),a=await r.getSignaturesForAddress(o,{limit:25});if(a.length===0)return{settled:!1};let i=BigInt(e.amount);for(let c of a){if(c.err)continue;let l=await r.getTransaction(c.signature,{commitment:"confirmed",maxSupportedTransactionVersion:0});if(!l?.meta)continue;let s=l.transaction.message.getAccountKeys().keySegments().flat(),p=l.meta.preTokenBalances??[],f=l.meta.postTokenBalances??[];for(let g of f){if(g.mint!==e.asset)continue;let w=s[g.accountIndex];if(!w||!w.equals(o))continue;let u=p.find(h=>h.accountIndex===g.accountIndex),A=BigInt(u?.uiTokenAmount.amount??"0");if(BigInt(g.uiTokenAmount.amount??"0")-A===i)return{settled:!0,txSignature:c.signature}}}return{settled:!1}}};function L(n){return new je(n)}var Ht={PermitWitnessTransferFrom:[{name:"permitted",type:"TokenPermissions"},{name:"spender",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"witness",type:"Witness"}],TokenPermissions:[{name:"token",type:"address"},{name:"amount",type:"uint256"}],Witness:[{name:"to",type:"address"},{name:"validAfter",type:"uint256"}]},ht=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function oe(n){if(!n||typeof n!="object")return!1;let e=n;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var Je=class{name="EVM";networks=[Ce,z,We,Ne,Te,Pe,Re,ve,_e,Ie];config;log;constructor(e={}){this.config=e,this.log=e.verbose?console.log.bind(console,"[x402:evm]"):()=>{}}canHandle(e){return!!(this.networks.includes(e)||e==="base"||e==="bsc"||e==="ethereum"||e==="arbitrum"||e==="polygon"||e==="optimism"||e==="avalanche"||e==="skale-base"||e==="skale-base-sepolia"||e.startsWith("eip155:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:U[e]?U[e]:e==="base"?U[z]:e==="bsc"?U[Ce]:e==="ethereum"?U[Ne]:e==="arbitrum"?U[Te]:e==="polygon"?U[Pe]:e==="optimism"?U[Re]:e==="avalanche"?U[ve]:e==="skale-base"?U[_e]:e==="skale-base-sepolia"?U[Ie]:U[z]}getAddress(e){return oe(e)?e.address:null}isConnected(e){return oe(e)?!!e.address:!1}getChainId(e){if(Oe[e])return Oe[e];if(e.startsWith("eip155:")){let t=e.split(":")[1];return parseInt(t,10)}return e==="base"?8453:e==="bsc"?56:e==="ethereum"?1:e==="arbitrum"?42161:8453}async getBalance(e,t,r){if(!oe(t)||!t.address)return 0;let o=r||this.getDefaultRpcUrl(e.network);try{let a=this.encodeBalanceOf(t.address),i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:e.asset,data:a},"latest"]})});if(!i.ok)throw new Error(`RPC request failed: ${i.status}`);let c=await i.json();if(c.error)throw new Error(`RPC error: ${JSON.stringify(c.error)}`);if(!c.result||c.result==="0x")return 0;let l=BigInt(c.result),s=e.extra?.decimals??6;return Number(l)/Math.pow(10,s)}catch(a){throw a}}encodeBalanceOf(e){let t="0x70a08231",r=e.slice(2).toLowerCase().padStart(64,"0");return t+r}async confirmSettlement(e,t){if(e.kind==="eip3009"){let r="0xe94a0102",o=e.from.slice(2).toLowerCase().padStart(64,"0"),a=e.nonce.slice(2).toLowerCase().padStart(64,"0"),i=r+o+a,c=await this.ethCall(t,e.asset,i);return{settled:BigInt(c)!==0n}}if(e.kind==="permit2"){let r="0x4fe02b44",o=BigInt(e.nonce),a=o>>8n,i=o&0xffn,c=e.from.slice(2).toLowerCase().padStart(64,"0"),l=a.toString(16).padStart(64,"0"),s=r+c+l,p=await this.ethCall(t,Y,s);return{settled:(BigInt(p)>>i&1n)===1n}}throw new Error(`EvmAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`)}async ethCall(e,t,r){let o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:r},"latest"]})});if(!o.ok)throw new Error(`RPC request failed: ${o.status}`);let a=await o.json();if(a.error)throw new Error(`RPC error: ${JSON.stringify(a.error)}`);if(!a.result||a.result==="0x")throw new Error("RPC returned an empty result");return a.result}async buildTransaction(e,t,r){if(!oe(t))throw new Error("Invalid EVM wallet");if(!t.address)throw new Error("Wallet not connected");if(e.scheme==="exact-approval")return this.buildApprovalTransaction(e,t,r);if(e.extra?.assetTransferMethod==="permit2")return this.buildPermit2Transaction(e,t,r);let{payTo:o,asset:a,extra:i}=e,c=e.amount??e.maxAmountRequired;if(!c)throw new Error("Missing amount in payment requirements");this.log("Building EVM transaction:",{from:t.address,to:o,amount:c,asset:a,network:e.network});let l=this.getChainId(e.network),s={name:i?.name??"USD Coin",version:i?.version??"2",chainId:BigInt(l),verifyingContract:a},p={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},f=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(f);let g="0x"+[...f].map(y=>y.toString(16).padStart(2,"0")).join(""),w=Math.floor(Date.now()/1e3),u={from:t.address,to:o,value:c,validAfter:String(w-600),validBefore:String(w+(e.maxTimeoutSeconds||60)),nonce:g},A={from:t.address,to:o,value:BigInt(c),validAfter:BigInt(w-600),validBefore:BigInt(w+(e.maxTimeoutSeconds||60)),nonce:g};if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let m=await t.signTypedData({domain:s,types:p,primaryType:"TransferWithAuthorization",message:A});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:u,signature:m}),signature:m,settlementProbe:{kind:"eip3009",from:t.address,nonce:g,asset:a,chainId:l}}}async buildApprovalTransaction(e,t,r){let{payTo:o,asset:a,extra:i}=e,c=e.amount??e.maxAmountRequired;if(!c)throw new Error("Missing amount in payment requirements");let l=i?.facilitatorContract;if(!l)throw new Error("exact-approval scheme requires extra.facilitatorContract from the facilitator. The /supported endpoint should provide this.");if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");this.log("Building approval-based transaction:",{from:t.address,to:o,amount:c,asset:a,network:e.network,facilitatorContract:l});let s=r||this.getDefaultRpcUrl(e.network),p=i?.fee??"0",f=BigInt(c)+BigInt(p),g=await this.readAllowance(s,a,t.address,l);if(g<f){if(!t.sendTransaction)throw new Error("BSC payments require a wallet that supports sendTransaction for the one-time token approval. Use createEvmKeypairWallet() or a browser wallet with transaction support.");let D=this.calculateApprovalAmount(c,p,i?.approvalStrategy);this.log(`Approving ${D} for ${l} (current allowance: ${g})`);let b=await t.sendTransaction({to:a,data:this.encodeApprove(l,D),value:0n});this.log(`Approval tx sent: ${b}`),await this.waitForReceipt(s,b),this.log("Approval confirmed")}else this.log("Sufficient allowance, skipping approval");let w=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(w);let u=[...w].reduce((D,b)=>D*256n+BigInt(b),0n).toString(),A=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(A);let m="0x"+[...A].map(D=>D.toString(16).padStart(2,"0")).join(""),y=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),S=i?.eip712Domain,P=S?{name:S.name,version:S.version,chainId:BigInt(S.chainId),verifyingContract:S.verifyingContract}:{name:"DexterBSCFacilitator",version:"1",chainId:BigInt(this.getChainId(e.network)),verifyingContract:l},k=i?.eip712Types??{Payment:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"token",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"paymentId",type:"bytes32"}]},F={from:t.address,to:o,token:a,amount:BigInt(c),fee:BigInt(p),nonce:BigInt(u),deadline:BigInt(y),paymentId:m},K=await t.signTypedData({domain:P,types:k,primaryType:"Payment",message:F});this.log("EIP-712 Payment signature obtained");let G={from:t.address,to:o,token:a,amount:c,fee:p,nonce:u,deadline:y,paymentId:m,signature:K};return{serialized:JSON.stringify(G),signature:K}}async buildPermit2Transaction(e,t,r){let{payTo:o,asset:a}=e,i=e.amount??e.maxAmountRequired;if(!i)throw new Error("Missing amount in payment requirements");if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");this.log("Building Permit2 transaction:",{from:t.address,to:o,amount:i,asset:a,network:e.network});let c=r||this.getDefaultRpcUrl(e.network),l=await this.readAllowance(c,a,t.address,Y),s;if(l<BigInt(i)){let P=this.encodeApprove(Y,ht);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${l})`);let k=this.getChainId(e.network),F=await this.readGasPrice(c),K=await this.readNonce(c,t.address),G=await t.signTransaction({to:a,data:P,chainId:k,gas:50000n,gasPrice:F,nonce:K});s={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:a,spender:Y,amount:ht.toString(),signedTransaction:G,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${l})`);let k=await t.sendTransaction({to:a,data:P,value:0n});this.log(`Permit2 approval tx sent: ${k}`),await this.waitForReceipt(c,k),this.log("Permit2 approval confirmed")}else throw new Error("Permit2 payments require a wallet that supports signTransaction or sendTransaction for the one-time Permit2 approval. Use createEvmKeypairWallet() or a browser wallet with transaction support.")}else this.log("Sufficient Permit2 allowance, skipping approval");let p=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(p);let f=[...p].reduce((P,k)=>P*256n+BigInt(k),0n),g=Math.floor(Date.now()/1e3),w=g-600,u=g+(e.maxTimeoutSeconds||300),A=this.getChainId(e.network),m={name:"Permit2",chainId:BigInt(A),verifyingContract:Y},h={permitted:{token:a,amount:BigInt(i)},spender:ke,nonce:f,deadline:BigInt(u),witness:{to:o,validAfter:BigInt(w)}},y=await t.signTypedData({domain:m,types:Ht,primaryType:"PermitWitnessTransferFrom",message:h});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let S={signature:y,permit2Authorization:{from:t.address,permitted:{token:a,amount:i},spender:ke,nonce:f.toString(),deadline:String(u),witness:{to:o,validAfter:String(w)}}};return{serialized:JSON.stringify(S),signature:y,extensions:s,settlementProbe:{kind:"permit2",from:t.address,nonce:f.toString(),chainId:A}}}async readAllowance(e,t,r,o){let a="0xdd62ed3e",i=r.slice(2).toLowerCase().padStart(64,"0"),c=o.slice(2).toLowerCase().padStart(64,"0"),l=a+i+c;try{let p=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:l},"latest"]})})).json();return p.error||!p.result||p.result==="0x"?0n:BigInt(p.result)}catch{return 0n}}encodeApprove(e,t){let r="0x095ea7b3",o=e.slice(2).toLowerCase().padStart(64,"0"),a=t.toString(16).padStart(64,"0");return r+o+a}async waitForReceipt(e,t,r=3e4){let o=Date.now();for(;Date.now()-o<r;){try{let i=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionReceipt",params:[t]})})).json();if(i.result){if(i.result.status==="0x0")throw new Error(`Approval transaction reverted: ${t}`);return}}catch(a){if(a instanceof Error&&a.message.includes("reverted"))throw a}await new Promise(a=>setTimeout(a,2e3))}throw new Error(`Approval transaction receipt timeout after ${r}ms: ${t}`)}async readGasPrice(e){try{let r=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_gasPrice",params:[]})})).json();return r.result?BigInt(r.result):50000000n}catch{return 50000000n}}async readNonce(e,t){try{let o=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionCount",params:[t,"latest"]})})).json();return o.result?parseInt(o.result,16):0}catch{return 0}}calculateApprovalAmount(e,t,r){let o=BigInt(e)+BigInt(t);if(!r||r.mode==="exact")return o;let a=BigInt(r.defaultMultiple??10),i=o*a;if(r.maxCapUsd){let c=this.inferDecimals(e),l=BigInt(Math.floor(r.maxCapUsd*Math.pow(10,c)));if(i>l)return l}if(r.exactAboveUsd){let c=this.inferDecimals(e),l=BigInt(Math.floor(r.exactAboveUsd*Math.pow(10,c)));if(BigInt(e)>l)return o}return i}inferDecimals(e){return e.length>12?18:6}};function ae(n){return new Je(n)}function rt(n){if(n===Le||n===mt)return!0;let e=n.toLowerCase();for(let t of Object.values(Fe))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(qe))if(t.toLowerCase()===e)return!0;return!1}function jt(n){return{[be]:"Solana",[$e]:"Solana Devnet",[Ke]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[ee]:"Base",[ue]:"Base Sepolia",[Ae]:"Ethereum",[pe]:"Arbitrum",[me]:"Polygon",[de]:"Optimism",[fe]:"Avalanche",[ge]:"BSC",[ye]:"SKALE Base",[he]:"SKALE Base Sepolia",base:"Base","base-sepolia":"Base Sepolia",ethereum:"Ethereum",arbitrum:"Arbitrum",polygon:"Polygon",optimism:"Optimism",avalanche:"Avalanche",bsc:"BSC","skale-base":"SKALE Base","skale-base-sepolia":"SKALE Base Sepolia"}[n]||n}function At(n,e){let t=jt(n);return t===n?e:t}async function Jt(n,e){if(typeof n=="string")return[n,e];if(n instanceof URL)return[n.href,e];let t=n,r=new Headers(t.headers);e?.headers&&new Headers(e.headers).forEach((i,c)=>r.set(c,i));let o={method:e?.method??t.method,headers:r,signal:e?.signal??t.signal,redirect:e?.redirect??t.redirect,credentials:e?.credentials??t.credentials},a=(o.method??"GET").toUpperCase();return e&&"body"in e?o.body=e.body:a!=="GET"&&a!=="HEAD"&&t.body&&(o.body=await t.arrayBuffer()),[t.url,o]}var St=new WeakMap;function ot(n){return St.get(n)}function Ue(n){let{adapters:e=[L({verbose:n.verbose}),ae({verbose:n.verbose})],wallets:t,wallet:r,preferredNetwork:o,rpcUrls:a={},maxAmountAtomic:i,fetch:c=globalThis.fetch,verbose:l=!1,accessPass:s,onPaymentRequired:p,onPaymentDispatched:f,maxRetries:g=0,retryDelayMs:w=500}=n,u=l?console.log.bind(console,"[x402]"):()=>{};async function A(b,T){let R;for(let x=0;x<=g;x++)try{let v=await c(b,T);if(v.status>=502&&v.status<=504&&x<g){u(`Retry ${x+1}/${g}: server returned ${v.status}`),await new Promise(_=>setTimeout(_,w*Math.pow(2,x)));continue}return v}catch(v){R=v,x<g&&(u(`Retry ${x+1}/${g}: ${v instanceof Error?v.message:"network error"}`),await new Promise(_=>setTimeout(_,w*Math.pow(2,x))))}throw R}let m=new Map;function h(b){try{let T=new URL(b).host,R=m.get(T);if(R&&R.expiresAt>Date.now()/1e3+10)return R.jwt;R&&m.delete(T)}catch{}return null}function y(b,T){try{let R=new URL(b).host,x=T.split(".");if(x.length===3){let v=JSON.parse(atob(x[1].replace(/-/g,"+").replace(/_/g,"/"))),_=Math.floor(Date.now()/1e3),I=_+86400,M=Math.min(typeof v.exp=="number"?v.exp:_,I);m.set(R,{jwt:T,expiresAt:M}),u("Access pass cached for",R,"| expires:",new Date(M*1e3).toISOString())}}catch{u("Failed to cache access pass")}}let S=t||{};r&&!S.solana&&re(r)&&(S.solana=r),r&&!S.evm&&oe(r)&&(S.evm=r);function P(b){let T=[];for(let R of b){let x=R.scheme??"exact";if(x!=="exact"&&x!=="exact-approval")continue;let v=e.find(I=>I.canHandle(R.network));if(!v)continue;let _;v.name==="Solana"?_=S.solana:v.name==="EVM"&&(_=S.evm),_&&v.isConnected(_)&&T.push({accept:R,adapter:v,wallet:_})}if(T.length===0)return null;if(o){let R=T.find(x=>x.accept.network===o);if(R)return R}return T[0]}function k(b,T){return At(b,T)}function F(b,T){return a[b]||T.getDefaultRpcUrl(b)}async function K(b,T,R,x,v){let _="";if(s?.preferTier&&x.tiers){let d=x.tiers.find(E=>E.id===s.preferTier);if(d){if(s.maxSpend&&parseFloat(d.price)>parseFloat(s.maxSpend))throw new C("access_pass_exceeds_max_spend",`Access pass tier "${d.id}" costs $${d.price}, exceeds max spend $${s.maxSpend}`);_=`tier=${d.id}`}}else if(s?.preferDuration&&x.ratePerHour)_=`duration=${s.preferDuration}`;else if(x.tiers&&x.tiers.length>0){let d=x.tiers[0];if(s?.maxSpend&&parseFloat(d.price)>parseFloat(s.maxSpend))throw new C("access_pass_exceeds_max_spend",`Cheapest access pass costs $${d.price}, exceeds max spend $${s?.maxSpend}`);_=`tier=${d.id}`}let I=_?v.includes("?")?`${v}&${_}`:`${v}?${_}`:v;u("Purchasing access pass:",_||"default tier");let M=R.headers.get("PAYMENT-REQUIRED");if(!M)return null;let B;try{B=JSON.parse(atob(M))}catch{return null}let O=P(B.accepts);if(!O)return null;let{accept:N,adapter:W,wallet:se}=O;if(W.name==="Solana"&&!N.extra?.feePayer)return null;let q=N.extra?.decimals??(rt(N.asset)?6:void 0);if(typeof q!="number")return null;let we=N.amount??N.maxAmountRequired;if(!we)return null;let H=F(N.network,W);try{let d=await W.getBalance(N,se,H),E=Number(we)/Math.pow(10,q);if(d<E){let Ze=k(N.network,W.name);throw new C("insufficient_balance",`Insufficient balance for access pass on ${Ze}. Have $${d.toFixed(4)}, need $${E.toFixed(4)}`)}}catch(d){if(d instanceof C)throw d}let j=await W.buildTransaction(N,se,H),ie;W.name==="EVM"?ie=JSON.parse(j.serialized):ie={transaction:j.serialized};let Q=typeof b=="string"?b:b instanceof URL?b.href:b.url,ce=B.resource;if(typeof B.resource=="string")try{let d=new URL(B.resource,Q);["http:","https:"].includes(d.protocol)&&(ce=d.toString())}catch{}else if(B.resource&&typeof B.resource=="object"&&"url"in B.resource){let d=B.resource;try{let E=new URL(d.url,Q);["http:","https:"].includes(E.protocol)&&(ce={...d,url:E.toString()})}catch{}}let Me={x402Version:N.x402Version??2,resource:ce,accepted:N,payload:ie};j.extensions&&(Me.extensions=j.extensions);let J=btoa(JSON.stringify(Me)),Z=await c(I,{...T,method:"POST",headers:{...T?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":J}});if(!Z.ok)return u("Pass purchase failed:",Z.status),null;let $=Z.headers.get("ACCESS-PASS");return $&&(y(v,$),u("Access pass purchased and cached")),Z}async function G(b,T){let R=b;if(u("Making request:",R),s){let d=h(R);if(d){u("Using cached access pass");let E=await c(b,{...T,headers:{...T?.headers||{},Authorization:`Bearer ${d}`}});if(E.status!==401&&E.status!==402)return E;u("Cached pass rejected (status",E.status,"), purchasing new pass");try{m.delete(new URL(R).host)}catch{}}}let x=await A(b,T);if(x.status!==402)return x;u("Received 402 Payment Required");let v=x.headers.get("X-ACCESS-PASS-TIERS");if(s&&v){u("Server offers access passes, purchasing...");try{let d=JSON.parse(atob(v)),E=await K(b,T,x,d,R);if(E)return E}catch(d){u("Access pass purchase failed, falling back to per-request payment:",d)}}let _=x.headers.get("PAYMENT-REQUIRED");if(!_)throw new C("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let I;try{let d=atob(_);I=JSON.parse(d)}catch{throw new C("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}u("Payment requirements:",I);let M=x.headers.get("X-Quote-Hash");M&&u("Quote hash received:",M);let B=P(I.accepts);if(!B){let d=I.accepts.map(E=>E.network).join(", ");throw new C("no_matching_payment_option",`No connected wallet for any available network: ${d}`)}let{accept:O,adapter:N,wallet:W}=B;if(u(`Using ${N.name} for ${O.network}`),N.name==="Solana"&&!O.extra?.feePayer)throw new C("missing_fee_payer","Solana payment option missing feePayer in extra");let se=O.extra?.decimals??(rt(O.asset)?6:void 0);if(typeof se!="number")throw new C("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let q=O.amount??O.maxAmountRequired;if(!q)throw new C("missing_amount","Payment option missing amount");if(i&&BigInt(q)>BigInt(i))throw new C("amount_exceeds_max",`Payment amount ${q} exceeds maximum ${i}`);let we=F(O.network,N);u("Checking balance...");try{let d=await N.getBalance(O,W,we),E=Number(q)/Math.pow(10,se);if(d<E){let Ze=k(O.network,N.name);throw new C("insufficient_balance",`Insufficient balance on ${Ze}. Have $${d.toFixed(4)}, need $${E.toFixed(4)}`)}u(`Balance OK: $${d.toFixed(4)} >= $${E.toFixed(4)}`)}catch(d){if(d instanceof C)throw d;u("Balance check failed (RPC error), proceeding with transaction attempt")}if(p&&!await p(O))throw new C("payment_rejected","Payment rejected by onPaymentRequired callback");u("Building transaction...");let H=await N.buildTransaction(O,W,we);u("Transaction signed");let j;N.name==="EVM"?j=JSON.parse(H.serialized):j={transaction:H.serialized};let ie=b,Q=I.resource;if(typeof I.resource=="string")try{let d=new URL(I.resource,ie).toString();d!==I.resource&&u("Resolved relative resource URL:",I.resource,"\u2192",d),Q=d}catch{Q=I.resource}else if(I.resource&&typeof I.resource=="object"&&"url"in I.resource){let d=I.resource;try{let E=new URL(d.url,ie).toString();E!==d.url&&(u("Resolved relative resource URL:",d.url,"\u2192",E),Q={...d,url:E})}catch{}}let ce={x402Version:O.x402Version??2,resource:Q,accepted:O,payload:j};H.extensions&&(ce.extensions=H.extensions);let Me=btoa(JSON.stringify(ce));if(f)try{f(O,H.settlementProbe)}catch{}u("Retrying request with payment...");let J=await A(b,{...T,headers:{...T?.headers||{},"PAYMENT-SIGNATURE":Me,...M?{"X-Quote-Hash":M}:{}}});if(u("Retry response status:",J.status),J.status===402){let d="unknown";try{let E=await J.clone().json();d=String(E.error||E.message||JSON.stringify(E)),u("Rejection reason:",d)}catch{}throw new C("payment_rejected",`Payment was rejected by the server: ${d}`)}let Z=J.headers.get("PAYMENT-RESPONSE"),$;if(Z)try{$=JSON.parse(atob(Z))}catch{}return $??={},$.amountAtomic=q,$.assetDecimals=se,St.set(J,$),$.extensions&&u("Settlement extensions:",Object.keys($.extensions).join(", ")),J}async function D(b,T){let[R,x]=await Jt(b,T);return G(R,x)}return{fetch:D}}import{PublicKey as cr}from"@solana/web3.js";import{bytesToHex as at}from"@noble/hashes/utils";import Qn from"tweetnacl";import{sessionRegisterMessage as Xn,sessionRevokeMessage as zn,voucherPayloadMessage as Xt,buildVoucherMessage as Yn}from"@dexterai/vault/messages";import{sha256 as tr}from"@noble/hashes/sha256";function wt(n){return Buffer.from(JSON.stringify({payload:n.payload,sessionPublicKey:at(n.sessionPublicKey),sessionRegistration:at(n.sessionRegistration),sessionSignature:at(n.sessionSignature)}),"utf8").toString("base64")}function V(n){if(n instanceof Error){if(n.message&&n.message.length>0)return n.message;if(n.name&&n.name.length>0)return n.name}let e=String(n);return e.length>0?e:"unknown error"}async function Be(n){let e="";try{e=(await n.clone().text()).slice(0,600)}catch{}let t=e.toLowerCase(),r=t.includes("settle")||t.includes("facilitator"),o=e;try{let a=JSON.parse(e),i=[a.error,a.detail,a.message].filter(c=>typeof c=="string"&&c.length>0);i.length>0&&(o=i.join(" \u2014 "))}catch{}return o||(o=`HTTP ${n.status}`),{reason:r?"settlement_failed":"merchant_rejected",detail:`merchant HTTP ${n.status}: ${o}`}}var Xe="Payment authorization was sent, but the merchant did not respond within the timeout. ",ze=" Do not retry without checking \u2014 inspect the funding wallet for a transfer to the merchant before attempting payment again.";async function Ye(n,e,t){if(!n)return{confirmed:!1,detail:Xe+"This payment scheme has no on-chain confirmation check, so the SDK cannot verify whether it settled."+ze};try{if(n.kind==="solana"){let i=L(),c=t??i.getDefaultRpcUrl(e.caip2);if(!i.confirmSettlement)return xt();let l=await i.confirmSettlement(n,c);return l.settled?{confirmed:!0,txSignature:l.txSignature}:bt()}let r=ae(),o=r.getDefaultRpcUrl(e.caip2);if(!r.confirmSettlement)return xt();let a=await r.confirmSettlement(n,o);return a.settled?{confirmed:!0,txSignature:a.txSignature}:bt()}catch(r){return{confirmed:!1,detail:Xe+`On-chain confirmation could not be completed (${V(r)}).`+ze}}}function bt(){return{confirmed:!1,detail:Xe+"On-chain confirmation found no matching settlement yet \u2014 the payment may still be pending, or may not have settled."+ze}}function xt(){return{confirmed:!1,detail:Xe+"The chain adapter does not support on-chain confirmation."+ze}}var zt=new Set(["exact","exact-approval"]);async function Yt(n,e,t,r){let o;try{o=await r.signNextVoucher(t.amount)}catch{return null}let a=new Headers(e.headers??void 0);a.set("X-Tab-Voucher",wt(o));let i={method:e.method??"GET",headers:a};e.signal&&(i.signal=e.signal),typeof e.body=="string"&&(i.body=e.body);let c;try{c=await fetch(n,i)}catch(l){return{ok:!1,reason:"error",detail:l?.message??String(l)}}return c.status===402?(r.rollbackVoucher?.call(r,o),null):c.ok?{ok:!0,paid:!0,response:c,amountPaid:t.amount,network:t.network}:{ok:!1,...await Be(c)}}function Et(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-(e.length%4||4))%4);return JSON.parse(Buffer.from(t,"base64").toString("utf8"))}function Gt(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,o=le(String(r.network??""));o&&e.push({scheme:String(r.scheme??"exact"),network:o,amount:String(r.amount??r.maxAmountRequired??"0"),asset:String(r.asset??""),payTo:String(r.payTo??""),maxTimeoutSeconds:typeof r.maxTimeoutSeconds=="number"?r.maxTimeoutSeconds:void 0,extra:r.extra&&typeof r.extra=="object"?r.extra:void 0})}return e}var Tt={version:2,async parseChallenge(n){let e=n.headers.get("payment-required");if(!e)return null;let t;try{t=Et(e)}catch{return null}let r=Array.isArray(t.accepts)?t.accepts:[];return r.length===0?null:{x402Version:2,options:Gt(r),resourceUrl:t.resource&&typeof t.resource=="object"?String(t.resource.url??""):void 0}},async pay(n,e,t,r,o){if(o.tab){let h=t.options.find(y=>y.scheme==="tab"&&y.network.family==="svm"&&y.payTo===o.tab.counterparty);if(h){let y=await Yt(n,e,h,o.tab);if(y)return y}}let a=t.options.filter(h=>zt.has(h.scheme));if(a.length===0)return{ok:!1,reason:"no_payment_options",detail:`no generically payable scheme offered (got: ${t.options.map(h=>h.scheme).join(", ")})`};let i=a.find(h=>h.network.family==="evm"?!!r.evm:h.network.family==="svm"?!!r.solana:!1);if(!i)return{ok:!1,reason:"unsupported_network"};let c=o.timeoutMs??15e3,l=o.responseTimeoutMs??12e4,s=new AbortController,p=setTimeout(()=>s.abort(),c),f=!1,g,w=(h,y)=>{f=!0,g=y,clearTimeout(p),p=setTimeout(()=>s.abort(),l)},u=Ue({wallets:r,preferredNetwork:i.network.caip2,maxAmountAtomic:o.maxAmountAtomic,fetch:globalThis.fetch,onPaymentDispatched:w}),A=e.signal?AbortSignal.any([e.signal,s.signal]):s.signal,m={method:e.method??"GET",headers:e.headers,signal:A};typeof e.body=="string"&&(m.body=e.body);try{let h=await u.fetch(n,m);if(clearTimeout(p),!h.ok)return{ok:!1,...await Be(h)};let y,S=h.headers.get("PAYMENT-RESPONSE");if(S)try{let P=Et(S);P&&typeof P.transaction=="string"&&(y=P.transaction)}catch{}return{ok:!0,paid:!0,response:h,amountPaid:i.amount,network:i.network,txSignature:y}}catch(h){clearTimeout(p);let y=h;if(y?.name==="AbortError"){if(!f)return{ok:!1,reason:"timeout"};let S=await Ye(g,i.network,o.solanaRpcUrl);return S.confirmed?{ok:!0,paid:!0,response:void 0,amountPaid:i.amount,network:i.network,txSignature:S.txSignature}:{ok:!1,reason:"payment_unconfirmed",detail:S.detail}}return{ok:!1,reason:"error",detail:y?.message??String(h)}}}};import{getAddress as Qt}from"viem";var Zt={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]};async function en(){let n=globalThis.crypto??(await import("crypto")).webcrypto,e=new Uint8Array(32);return n.getRandomValues(e),"0x"+Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}async function tn(n,e,t){if(typeof n.signTypedData!="function")throw new Error("EVM wallet does not support signTypedData");let r=Math.floor(Date.now()/1e3),o=String(r-600),a=String(r+(e.maxTimeoutSeconds??60)),i={from:n.address,to:e.payTo,value:e.amount,validAfter:o,validBefore:a,nonce:await en()},c=Oe[e.network.caip2];if(c===void 0)throw new Error(`unknown chain id for network ${e.network.caip2}`);let l=e.extra,s=await n.signTypedData({domain:{name:l.name,version:l.version,chainId:c,verifyingContract:Qt(e.asset)},types:Zt,primaryType:"TransferWithAuthorization",message:i});return{payment:{x402Version:1,scheme:e.scheme,network:t,payload:{signature:s,authorization:i}},settlementProbe:{kind:"eip3009",from:i.from,nonce:i.nonce,asset:e.asset,chainId:c}}}async function Ge(n,e,t){try{let r;for(let o of n.options){let a=o.network.family==="evm"&&!!e.evm||o.network.family==="svm"&&!!e.solana;if(o.scheme!=="exact"){a&&(r=o.scheme);continue}if(o.network.family==="evm"&&e.evm){let i=await e.evm;return await nn(o,i,t)}if(o.network.family==="svm"&&e.solana){let i=await e.solana;return await rn(o,i,t)}}return r!==void 0?{ok:!1,reason:"merchant_rejected",detail:`v1 supports only the 'exact' scheme, got '${r}'`}:{ok:!1,reason:"unsupported_network"}}catch(r){return{ok:!1,reason:"error",detail:V(r)}}}async function nn(n,e,t){if(t.maxAmountAtomic!==void 0&&BigInt(n.amount)>BigInt(t.maxAmountAtomic))return{ok:!1,reason:"budget_exceeded"};let r=n.extra??{},o=r.name,a=r.version;if(typeof o!="string"||o.length===0||typeof a!="string"||a.length===0)return{ok:!1,reason:"merchant_rejected",detail:"v1 challenge missing exact-scheme EIP-712 domain (extra.name / extra.version)"};let i=n.network.bare,{payment:c,settlementProbe:l}=await tn(e,n,i);return{ok:!0,headerValue:Buffer.from(JSON.stringify(c),"utf8").toString("base64"),option:n,settlementProbe:l}}async function rn(n,e,t){if(t.maxAmountAtomic!==void 0&&BigInt(n.amount)>BigInt(t.maxAmountAtomic))return{ok:!1,reason:"budget_exceeded"};if(n.scheme!=="exact")return{ok:!1,reason:"merchant_rejected",detail:`v1 SVM supports only the 'exact' scheme, got '${n.scheme}'`};let r=n.extra??{};if(typeof r.feePayer!="string"||r.feePayer.length===0)return{ok:!1,reason:"merchant_rejected",detail:"v1 SVM challenge missing extra.feePayer (required as the transaction fee payer)"};let o=n.network.bare,a={x402Version:1,scheme:n.scheme,network:o,asset:n.asset,payTo:n.payTo,amount:n.amount,maxAmountRequired:n.amount,maxTimeoutSeconds:n.maxTimeoutSeconds??60,extra:r},c=await L().buildTransaction(a,e,t.solanaRpcUrl),l={x402Version:1,scheme:n.scheme,network:o,payload:{transaction:c.serialized}};return{ok:!0,headerValue:Buffer.from(JSON.stringify(l),"utf8").toString("base64"),option:n,settlementProbe:c.settlementProbe}}function on(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,o=le(String(r.network??""));o&&e.push({scheme:String(r.scheme??"exact"),network:o,amount:String(r.maxAmountRequired??r.amount??"0"),asset:String(r.asset??""),payTo:String(r.payTo??""),maxTimeoutSeconds:typeof r.maxTimeoutSeconds=="number"?r.maxTimeoutSeconds:void 0,extra:r.extra&&typeof r.extra=="object"?r.extra:void 0})}return e}var Pt={version:1,async parseChallenge(n){if(n.headers.get("payment-required"))return null;let e;try{e=await n.clone().json()}catch{return null}let t=Array.isArray(e.accepts)?e.accepts:[];if(t.length===0)return null;let r=on(t);return r.length===0?null:{x402Version:1,options:r}},async pay(n,e,t,r,o){let a,i=new AbortController,c=!1,l,s;try{let p=o.timeoutMs??15e3;a=setTimeout(()=>i.abort(),p);let f=await Ge(t,r,o);if(!f.ok)return{ok:!1,reason:f.reason,detail:f.detail};let g=f.headerValue,w=f.option;s=w,l=f.settlementProbe;let u=new Headers(e.headers??void 0);u.set("X-PAYMENT",g);let A=e.signal!=null?AbortSignal.any([e.signal,i.signal]):i.signal,m={method:e.method,headers:u,signal:A};typeof e.body=="string"&&(m.body=e.body),c=!0,clearTimeout(a);let h=o.responseTimeoutMs??12e4;a=setTimeout(()=>i.abort(),h);let y=await fetch(n,m);return y.ok?{ok:!0,paid:!0,response:y,amountPaid:w.amount,network:w.network,txSignature:an(y)}:{ok:!1,...await Be(y)}}catch(p){if(p instanceof Error&&p.name==="AbortError"){if(!c)return{ok:!1,reason:"timeout"};let f=await Ye(l,s.network,o.solanaRpcUrl);return f.confirmed?{ok:!0,paid:!0,response:void 0,amountPaid:s.amount,network:s.network,txSignature:f.txSignature}:{ok:!1,reason:"payment_unconfirmed",detail:f.detail}}return{ok:!1,reason:"error",detail:V(p)}}finally{a!==void 0&&clearTimeout(a)}}};function an(n){let e=n.headers.get("x-payment-response")??n.headers.get("X-PAYMENT-RESPONSE");if(e)try{let t=JSON.parse(Buffer.from(e,"base64").toString("utf8")),r=t.transaction??t.txHash??t.transactionHash;return typeof r=="string"?r:void 0}catch{return}}import*as It from"tweetnacl";import{Keypair as De,VersionedTransaction as un,Transaction as pn}from"@solana/web3.js";var Se=Symbol.for("x402:keypair");async function st(n){let e;if(typeof n=="string"){let t;try{let r=await Promise.resolve().then(()=>(_t(),Ct)),o=r.decode??r.default?.decode;if(!o)throw new Error("decode not found");t=o}catch{throw new Error('The "bs58" package is required for base58 private keys. Install it with: npm install bs58')}try{let r=t(n);e=De.fromSecretKey(r)}catch{try{let o=JSON.parse(n);if(Array.isArray(o))e=De.fromSecretKey(Uint8Array.from(o));else throw new Error("Invalid private key format")}catch{throw new Error("Invalid private key. Expected base58 string or JSON array of bytes.")}}}else if(Array.isArray(n))e=De.fromSecretKey(Uint8Array.from(n));else if(n instanceof Uint8Array)e=De.fromSecretKey(n);else throw new Error("Invalid private key type. Expected string, number[], or Uint8Array.");return{publicKey:{toBase58:()=>e.publicKey.toBase58()},signTransaction:async t=>{if(t instanceof un)return t.sign([e]),t;if(t instanceof pn)return t.sign(e),t;throw new Error("Unknown transaction type")},[Se]:e}}function mn(n){if(!n||typeof n!="object")return!1;let e=n;return Se in e&&e[Se]instanceof De&&"publicKey"in e&&"signTransaction"in e}function Qe(n){let e=n.evm;if(e&&typeof e.signMessage=="function"&&typeof e.address=="string")return{address:e.address,signMessage:e.signMessage};let t=n.solana;if(t){let r=t[Se];if(r&&r.secretKey&&r.publicKey)return{publicKey:r.publicKey,signMessage:async o=>It.sign.detached(o,r.secretKey)}}return null}var Nt=[Tt,Pt];async function kt(n){for(let e of Nt)if(await e.parseChallenge(n.clone()))return e;return null}async function dn(n){let e=Qe(n);if(!e)return fetch;try{return(await import("@x402/extensions/sign-in-with-x")).wrapFetchWithSIWx(fetch,e)}catch(t){return console.warn(`[x402] SIW-X unavailable \u2014 @x402/extensions failed to load; SIW-X merchants will not authenticate. ${V(t)}`),fetch}}async function Ot(n,e,t,r){if(e.body!==void 0&&e.body!==null&&typeof e.body!="string")return{ok:!1,reason:"error",detail:"payAndFetch requires a string body; non-string bodies (Buffer, FormData, URLSearchParams, ReadableStream) cannot be safely re-sent on the paid retry"};let o;try{o=await(await dn(t))(n,{...e})}catch(a){return{ok:!1,reason:"error",detail:V(a)}}if(o.status!==402)return{ok:!0,paid:!1,response:o};for(let a of Nt){let i=await a.parseChallenge(o.clone());if(i)return a.pay(n,e,i,t,r)}return{ok:!1,reason:"no_payment_options"}}async function it(n){let e;try{e=(await import("viem/accounts")).privateKeyToAccount}catch{throw new Error("EVM wallet support requires viem as a peer dependency. Install with: npm install viem")}let t=n.startsWith("0x")?n:`0x${n}`,r=e(t);return{address:r.address,signTypedData:o=>r.signTypedData(o),signTransaction:o=>r.signTransaction({to:o.to,data:o.data,chainId:o.chainId,gas:o.gas,gasPrice:o.gasPrice,nonce:o.nonce,type:"legacy"}),signMessage:o=>r.signMessage({message:o.message})}}function fn(n){if(!n||typeof n!="object")return!1;let e=n;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")&&"signTypedData"in e&&typeof e.signTypedData=="function"}function ct(n){let e=ot(n);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function gn(n){let e=ct(n);if(e?.recommendations?.length)return e.recommendations}async function yn(n){let t=ct(n)?.tracking?.impressionBeacon;if(!t)return!1;try{await fetch(t,{method:"GET"})}catch{}return!0}function lt(n,e){let{walletPrivateKey:t,evmPrivateKey:r,preferredNetwork:o,rpcUrls:a,maxAmountAtomic:i,verbose:c,accessPass:l,onPaymentRequired:s}=e;if(!t&&!r)throw new Error("At least one wallet private key is required (walletPrivateKey or evmPrivateKey)");let p={},f=[];t&&f.push(st(t).then(m=>{p.solana=m}).catch(m=>{console.warn(`[x402] Solana wallet init failed: ${m.message}`)})),r&&f.push(it(r).then(m=>{p.evm=m}).catch(m=>{console.warn(`[x402] EVM wallet init failed: ${m.message}`)}));let g=f.length>0?Promise.all(f):null,u=Ue({wallets:p,preferredNetwork:o,rpcUrls:a,maxAmountAtomic:i,fetch:n,verbose:c,accessPass:l,onPaymentRequired:s}),A=u.fetch.bind(u);return g?(async(m,h)=>(await g,A(m,h))):A}function hn(n){let{budget:e,allowedDomains:t,onPaymentRequired:r,...o}=n,a=parseFloat(e.total),i=e.perRequest?parseFloat(e.perRequest):1/0,c=e.perHour?parseFloat(e.perHour):1/0;if(isNaN(a)||a<=0)throw new Error("budget.total must be a positive number");let l=[],s=0;function p(){return l.reduce((u,A)=>u+A.amount,0)}function f(){let u=Date.now()-36e5;return l.filter(A=>A.timestamp>=u).reduce((A,m)=>A+m.amount,0)}let g=lt(fetch,{...o,onPaymentRequired:async u=>{let A=u.extra?.decimals??6,m=Number(u.amount)/Math.pow(10,A);if(m>i)throw new C("amount_exceeds_max",`$${m.toFixed(4)} exceeds per-request limit of $${i.toFixed(2)}`);let h=p();if(h+m>a)throw new C("amount_exceeds_max",`Budget exceeded. Spent $${h.toFixed(2)} of $${a.toFixed(2)}, payment: $${m.toFixed(4)}`);let y=f();if(y+m>c)throw new C("amount_exceeds_max",`Hourly limit ($${c.toFixed(2)}) exceeded. Spent $${y.toFixed(2)} this hour`);return s=m,r?r(u):!0}});return{fetch:(async(u,A)=>{let m=typeof u=="string"?u:u instanceof URL?u.href:u.url,h="unknown";try{h=new URL(m).hostname}catch{}if(t&&!t.some(S=>h===S||h.endsWith(`.${S}`)))throw new C("payment_rejected",`Domain "${h}" not in allowed domains`);s=0;let y=await g(u,A);if(s>0){let S="unknown",P=y.headers.get("PAYMENT-RESPONSE");if(P)try{S=JSON.parse(atob(P)).network||S}catch{}l.push({amount:s,domain:h,network:S,timestamp:Date.now()}),s=0}return y}),get spent(){return`$${p().toFixed(2)}`},get remaining(){return`$${(a-p()).toFixed(2)}`},get payments(){return l.length},get spentAmount(){return p()},get remainingAmount(){return a-p()},get ledger(){return l},get hourlySpend(){return f()},reset(){l=[]}}}import{capabilitySearch as An}from"@dexterai/x402-core";export{z as BASE_MAINNET,ft as DEXTER_FACILITATOR_URL,Se as KEYPAIR_SYMBOL,X as SOLANA_MAINNET,Le as USDC_MINT,C as X402Error,Ge as buildV1PaymentHeader,An as capabilitySearch,hn as createBudgetAccount,ae as createEvmAdapter,it as createEvmKeypairWallet,st as createKeypairWallet,L as createSolanaAdapter,Ue as createX402Client,kt as detectStrategy,yn as fireImpressionBeacon,ot as getPaymentReceipt,ct as getSponsoredAccessInfo,gn as getSponsoredRecommendations,fn as isEvmKeypairWallet,mn as isKeypairWallet,Ot as payAndFetch,le as toNetworkRef,Qe as toSiwxSigner,lt as wrapFetch};
1
+ var Bt=Object.defineProperty;var pt=(n,e)=>()=>(n&&(e=n(n=0)),e);var Dt=(n,e)=>{for(var t in e)Bt(n,t,{get:e[t],enumerable:!0})};function cn(n){if(n.length>=255)throw new TypeError("Alphabet too long");let e=new Uint8Array(256);for(let s=0;s<e.length;s++)e[s]=255;for(let s=0;s<n.length;s++){let p=n.charAt(s),f=p.charCodeAt(0);if(e[f]!==255)throw new TypeError(p+" is ambiguous");e[f]=s}let t=n.length,r=n.charAt(0),o=Math.log(t)/Math.log(256),a=Math.log(256)/Math.log(t);function i(s){if(s instanceof Uint8Array||(ArrayBuffer.isView(s)?s=new Uint8Array(s.buffer,s.byteOffset,s.byteLength):Array.isArray(s)&&(s=Uint8Array.from(s))),!(s instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(s.length===0)return"";let p=0,f=0,g=0,w=s.length;for(;g!==w&&s[g]===0;)g++,p++;let u=(w-g)*a+1>>>0,A=new Uint8Array(u);for(;g!==w;){let y=s[g],S=0;for(let P=u-1;(y!==0||S<f)&&P!==-1;P--,S++)y+=256*A[P]>>>0,A[P]=y%t>>>0,y=y/t>>>0;if(y!==0)throw new Error("Non-zero carry");f=S,g++}let m=u-f;for(;m!==u&&A[m]===0;)m++;let h=r.repeat(p);for(;m<u;++m)h+=n.charAt(A[m]);return h}function c(s){if(typeof s!="string")throw new TypeError("Expected String");if(s.length===0)return new Uint8Array;let p=0,f=0,g=0;for(;s[p]===r;)f++,p++;let w=(s.length-p)*o+1>>>0,u=new Uint8Array(w);for(;p<s.length;){let y=s.charCodeAt(p);if(y>255)return;let S=e[y];if(S===255)return;let P=0;for(let k=w-1;(S!==0||P<g)&&k!==-1;k--,P++)S+=t*u[k]>>>0,u[k]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");g=P,p++}let A=w-g;for(;A!==w&&u[A]===0;)A++;let m=new Uint8Array(f+(w-A)),h=f;for(;A!==w;)m[h++]=u[A++];return m}function l(s){let p=c(s);if(p)return p;throw new Error("Non-base"+t+" character")}return{encode:i,decodeUnsafe:c,decode:l}}var vt,Ct=pt(()=>{"use strict";vt=cn});var _t={};Dt(_t,{default:()=>un});var ln,un,It=pt(()=>{"use strict";Ct();ln="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",un=vt(ln)});var be="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",$e="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Ke="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",X=be,xe=$e,Ee=Ke,ee="eip155:8453",le="eip155:84532",ue="eip155:42161",pe="eip155:137",me="eip155:10",de="eip155:43114",fe="eip155:56",ge="eip155:1187947933",ye="eip155:324705682",he="eip155:1",z=ee,We=le,Te=ue,Pe=pe,Re=me,ve=de,Ce=fe,_e=ge,Ie=ye,Ne=he,Le="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",mt="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",dt="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",et="0x55d398326f99059fF775485246999027B3197955",Ve="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",Fe={[fe]:Ve,[ee]:dt,[le]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[ue]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[pe]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[me]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[de]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[ge]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[ye]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[he]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},qe={[et]:{symbol:"USDT",decimals:18},[Ve]:{symbol:"USDC",decimals:18}};var Y="0x000000000022D473030F116dDEE9F6B43aC78BA3",ke="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",Oe={[fe]:56,[ee]:8453,[le]:84532,[ue]:42161,[pe]:137,[me]:10,[de]:43114,[ge]:1187947933,[ye]:324705682,[he]:1},te={[be]:"https://api.dexter.cash/api/solana/rpc",[$e]:"https://api.devnet.solana.com",[Ke]:"https://api.testnet.solana.com"},U={[fe]:"https://api.dexter.cash/api/evm/bsc/rpc",[ee]:"https://api.dexter.cash/api/base/rpc",[le]:"https://sepolia.base.org",[ue]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[pe]:"https://api.dexter.cash/api/evm/polygon/rpc",[me]:"https://api.dexter.cash/api/evm/optimism/rpc",[de]:"https://api.dexter.cash/api/evm/avalanche/rpc",[ge]:"https://skale-base.skalenodes.com/v1/base",[ye]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[he]:"https://eth.llamarpc.com"},ft="https://x402.dexter.cash";var C=class n extends Error{code;details;constructor(e,t,r){super(t),this.name="X402Error",this.code=e,this.details=r,Object.setPrototypeOf(this,n.prototype)}};import{PublicKey as ne,Connection as tt,TransactionMessage as Mt,VersionedTransaction as $t,ComputeBudgetProgram as gt}from"@solana/web3.js";import{getAssociatedTokenAddress as nt,getAccount as Kt,createTransferCheckedInstruction as Wt,getMint as Lt,TOKEN_PROGRAM_ID as yt,TOKEN_2022_PROGRAM_ID as He}from"@solana/spl-token";var Vt=12e3,Ft=1;function re(n){if(!n||typeof n!="object")return!1;let e=n;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var je=class{name="Solana";networks=[X,xe,Ee];config;log;constructor(e={}){this.config=e,this.log=e.verbose?console.log.bind(console,"[x402:solana]"):()=>{}}canHandle(e){return!!(this.networks.includes(e)||e==="solana"||e==="solana-devnet"||e==="solana-testnet"||e.startsWith("solana:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:te[e]?te[e]:e==="solana"?te[X]:e==="solana-devnet"?te[xe]:e==="solana-testnet"?te[Ee]:te[X]}getAddress(e){return re(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return re(e)?e.publicKey!==null:!1}async getBalance(e,t,r){if(!re(t)||!t.publicKey)return 0;let o=r||this.getDefaultRpcUrl(e.network),a=new tt(o,"confirmed"),i=new ne(t.publicKey.toBase58()),c=new ne(e.asset);try{let s=(await a.getAccountInfo(c,"confirmed"))?.owner.toBase58()===He.toBase58()?He:yt,p=await nt(c,i,!1,s),f=await Kt(a,p,void 0,s),g=e.extra?.decimals??6;return Number(f.amount)/Math.pow(10,g)}catch(l){if(l&&typeof l=="object"&&"name"in l&&(l.name==="TokenAccountNotFoundError"||l.name==="TokenInvalidAccountOwnerError"))return 0;throw l}}async buildTransaction(e,t,r){if(!re(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let o=r||this.getDefaultRpcUrl(e.network),a=new tt(o,"confirmed"),i=new ne(t.publicKey.toBase58()),{payTo:c,asset:l,extra:s}=e,p=e.amount??e.maxAmountRequired;if(!p)throw new Error("Missing amount in payment requirements");if(!s?.feePayer)throw new Error("Missing feePayer in payment requirements");let f=new ne(s.feePayer),g=new ne(l),w=new ne(c);this.log("Building transaction:",{from:i.toBase58(),to:c,amount:p,asset:l,feePayer:s.feePayer});let u=[];u.push(gt.setComputeUnitLimit({units:Vt})),u.push(gt.setComputeUnitPrice({microLamports:Ft}));let A=await a.getAccountInfo(g,"confirmed");if(!A)throw new Error(`Token mint ${l} not found`);let m=A.owner.toBase58()===He.toBase58()?He:yt,h=await Lt(a,g,void 0,m);typeof s?.decimals=="number"&&h.decimals!==s.decimals&&this.log(`Decimals mismatch: requirements say ${s.decimals}, mint says ${h.decimals}`);let y=await nt(g,i,!1,m),S=await nt(g,w,!0,m);if(!await a.getAccountInfo(y,"confirmed"))throw new Error(`No token account found for ${l}. Please ensure you have USDC in your wallet.`);if(!await a.getAccountInfo(S,"confirmed"))throw new Error(`Seller token account not found. The seller (${c}) must have a USDC account.`);let F=BigInt(p);u.push(Wt(y,g,S,i,F,h.decimals,[],m));let{blockhash:K}=await a.getLatestBlockhash("confirmed"),G=new Mt({payerKey:f,recentBlockhash:K,instructions:u}).compileToV0Message(),D=new $t(G),b=await t.signTransaction(D);return this.log("Transaction signed successfully"),{serialized:Buffer.from(b.serialize()).toString("base64"),settlementProbe:{kind:"solana",sourceAta:y.toBase58(),destinationAta:S.toBase58(),asset:l,amount:p,blockhash:K}}}async confirmSettlement(e,t){if(e.kind!=="solana")throw new Error(`SolanaAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`);let r=new tt(t,"confirmed"),o=new ne(e.destinationAta),a=await r.getSignaturesForAddress(o,{limit:25});if(a.length===0)return{settled:!1};let i=BigInt(e.amount);for(let c of a){if(c.err)continue;let l=await r.getTransaction(c.signature,{commitment:"confirmed",maxSupportedTransactionVersion:0});if(!l?.meta)continue;let s=l.transaction.message.getAccountKeys().keySegments().flat(),p=l.meta.preTokenBalances??[],f=l.meta.postTokenBalances??[];for(let g of f){if(g.mint!==e.asset)continue;let w=s[g.accountIndex];if(!w||!w.equals(o))continue;let u=p.find(h=>h.accountIndex===g.accountIndex),A=BigInt(u?.uiTokenAmount.amount??"0");if(BigInt(g.uiTokenAmount.amount??"0")-A===i)return{settled:!0,txSignature:c.signature}}}return{settled:!1}}};function L(n){return new je(n)}var qt={PermitWitnessTransferFrom:[{name:"permitted",type:"TokenPermissions"},{name:"spender",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"witness",type:"Witness"}],TokenPermissions:[{name:"token",type:"address"},{name:"amount",type:"uint256"}],Witness:[{name:"to",type:"address"},{name:"validAfter",type:"uint256"}]},ht=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function oe(n){if(!n||typeof n!="object")return!1;let e=n;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var Je=class{name="EVM";networks=[Ce,z,We,Ne,Te,Pe,Re,ve,_e,Ie];config;log;constructor(e={}){this.config=e,this.log=e.verbose?console.log.bind(console,"[x402:evm]"):()=>{}}canHandle(e){return!!(this.networks.includes(e)||e==="base"||e==="bsc"||e==="ethereum"||e==="arbitrum"||e==="polygon"||e==="optimism"||e==="avalanche"||e==="skale-base"||e==="skale-base-sepolia"||e.startsWith("eip155:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:U[e]?U[e]:e==="base"?U[z]:e==="bsc"?U[Ce]:e==="ethereum"?U[Ne]:e==="arbitrum"?U[Te]:e==="polygon"?U[Pe]:e==="optimism"?U[Re]:e==="avalanche"?U[ve]:e==="skale-base"?U[_e]:e==="skale-base-sepolia"?U[Ie]:U[z]}getAddress(e){return oe(e)?e.address:null}isConnected(e){return oe(e)?!!e.address:!1}getChainId(e){if(Oe[e])return Oe[e];if(e.startsWith("eip155:")){let t=e.split(":")[1];return parseInt(t,10)}return e==="base"?8453:e==="bsc"?56:e==="ethereum"?1:e==="arbitrum"?42161:8453}async getBalance(e,t,r){if(!oe(t)||!t.address)return 0;let o=r||this.getDefaultRpcUrl(e.network);try{let a=this.encodeBalanceOf(t.address),i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:e.asset,data:a},"latest"]})});if(!i.ok)throw new Error(`RPC request failed: ${i.status}`);let c=await i.json();if(c.error)throw new Error(`RPC error: ${JSON.stringify(c.error)}`);if(!c.result||c.result==="0x")return 0;let l=BigInt(c.result),s=e.extra?.decimals??6;return Number(l)/Math.pow(10,s)}catch(a){throw a}}encodeBalanceOf(e){let t="0x70a08231",r=e.slice(2).toLowerCase().padStart(64,"0");return t+r}async confirmSettlement(e,t){if(e.kind==="eip3009"){let r="0xe94a0102",o=e.from.slice(2).toLowerCase().padStart(64,"0"),a=e.nonce.slice(2).toLowerCase().padStart(64,"0"),i=r+o+a,c=await this.ethCall(t,e.asset,i);return{settled:BigInt(c)!==0n}}if(e.kind==="permit2"){let r="0x4fe02b44",o=BigInt(e.nonce),a=o>>8n,i=o&0xffn,c=e.from.slice(2).toLowerCase().padStart(64,"0"),l=a.toString(16).padStart(64,"0"),s=r+c+l,p=await this.ethCall(t,Y,s);return{settled:(BigInt(p)>>i&1n)===1n}}throw new Error(`EvmAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`)}async ethCall(e,t,r){let o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:r},"latest"]})});if(!o.ok)throw new Error(`RPC request failed: ${o.status}`);let a=await o.json();if(a.error)throw new Error(`RPC error: ${JSON.stringify(a.error)}`);if(!a.result||a.result==="0x")throw new Error("RPC returned an empty result");return a.result}async buildTransaction(e,t,r){if(!oe(t))throw new Error("Invalid EVM wallet");if(!t.address)throw new Error("Wallet not connected");if(e.scheme==="exact-approval")return this.buildApprovalTransaction(e,t,r);if(e.extra?.assetTransferMethod==="permit2")return this.buildPermit2Transaction(e,t,r);let{payTo:o,asset:a,extra:i}=e,c=e.amount??e.maxAmountRequired;if(!c)throw new Error("Missing amount in payment requirements");this.log("Building EVM transaction:",{from:t.address,to:o,amount:c,asset:a,network:e.network});let l=this.getChainId(e.network),s={name:i?.name??"USD Coin",version:i?.version??"2",chainId:BigInt(l),verifyingContract:a},p={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},f=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(f);let g="0x"+[...f].map(y=>y.toString(16).padStart(2,"0")).join(""),w=Math.floor(Date.now()/1e3),u={from:t.address,to:o,value:c,validAfter:String(w-600),validBefore:String(w+(e.maxTimeoutSeconds||60)),nonce:g},A={from:t.address,to:o,value:BigInt(c),validAfter:BigInt(w-600),validBefore:BigInt(w+(e.maxTimeoutSeconds||60)),nonce:g};if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let m=await t.signTypedData({domain:s,types:p,primaryType:"TransferWithAuthorization",message:A});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:u,signature:m}),signature:m,settlementProbe:{kind:"eip3009",from:t.address,nonce:g,asset:a,chainId:l}}}async buildApprovalTransaction(e,t,r){let{payTo:o,asset:a,extra:i}=e,c=e.amount??e.maxAmountRequired;if(!c)throw new Error("Missing amount in payment requirements");let l=i?.facilitatorContract;if(!l)throw new Error("exact-approval scheme requires extra.facilitatorContract from the facilitator. The /supported endpoint should provide this.");if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");this.log("Building approval-based transaction:",{from:t.address,to:o,amount:c,asset:a,network:e.network,facilitatorContract:l});let s=r||this.getDefaultRpcUrl(e.network),p=i?.fee??"0",f=BigInt(c)+BigInt(p),g=await this.readAllowance(s,a,t.address,l);if(g<f){if(!t.sendTransaction)throw new Error("BSC payments require a wallet that supports sendTransaction for the one-time token approval. Use createEvmKeypairWallet() or a browser wallet with transaction support.");let D=this.calculateApprovalAmount(c,p,i?.approvalStrategy);this.log(`Approving ${D} for ${l} (current allowance: ${g})`);let b=await t.sendTransaction({to:a,data:this.encodeApprove(l,D),value:0n});this.log(`Approval tx sent: ${b}`),await this.waitForReceipt(s,b),this.log("Approval confirmed")}else this.log("Sufficient allowance, skipping approval");let w=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(w);let u=[...w].reduce((D,b)=>D*256n+BigInt(b),0n).toString(),A=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(A);let m="0x"+[...A].map(D=>D.toString(16).padStart(2,"0")).join(""),y=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),S=i?.eip712Domain,P=S?{name:S.name,version:S.version,chainId:BigInt(S.chainId),verifyingContract:S.verifyingContract}:{name:"DexterBSCFacilitator",version:"1",chainId:BigInt(this.getChainId(e.network)),verifyingContract:l},k=i?.eip712Types??{Payment:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"token",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"paymentId",type:"bytes32"}]},F={from:t.address,to:o,token:a,amount:BigInt(c),fee:BigInt(p),nonce:BigInt(u),deadline:BigInt(y),paymentId:m},K=await t.signTypedData({domain:P,types:k,primaryType:"Payment",message:F});this.log("EIP-712 Payment signature obtained");let G={from:t.address,to:o,token:a,amount:c,fee:p,nonce:u,deadline:y,paymentId:m,signature:K};return{serialized:JSON.stringify(G),signature:K}}async buildPermit2Transaction(e,t,r){let{payTo:o,asset:a}=e,i=e.amount??e.maxAmountRequired;if(!i)throw new Error("Missing amount in payment requirements");if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");this.log("Building Permit2 transaction:",{from:t.address,to:o,amount:i,asset:a,network:e.network});let c=r||this.getDefaultRpcUrl(e.network),l=await this.readAllowance(c,a,t.address,Y),s;if(l<BigInt(i)){let P=this.encodeApprove(Y,ht);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${l})`);let k=this.getChainId(e.network),F=await this.readGasPrice(c),K=await this.readNonce(c,t.address),G=await t.signTransaction({to:a,data:P,chainId:k,gas:50000n,gasPrice:F,nonce:K});s={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:a,spender:Y,amount:ht.toString(),signedTransaction:G,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${l})`);let k=await t.sendTransaction({to:a,data:P,value:0n});this.log(`Permit2 approval tx sent: ${k}`),await this.waitForReceipt(c,k),this.log("Permit2 approval confirmed")}else throw new Error("Permit2 payments require a wallet that supports signTransaction or sendTransaction for the one-time Permit2 approval. Use createEvmKeypairWallet() or a browser wallet with transaction support.")}else this.log("Sufficient Permit2 allowance, skipping approval");let p=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(p);let f=[...p].reduce((P,k)=>P*256n+BigInt(k),0n),g=Math.floor(Date.now()/1e3),w=g-600,u=g+(e.maxTimeoutSeconds||300),A=this.getChainId(e.network),m={name:"Permit2",chainId:BigInt(A),verifyingContract:Y},h={permitted:{token:a,amount:BigInt(i)},spender:ke,nonce:f,deadline:BigInt(u),witness:{to:o,validAfter:BigInt(w)}},y=await t.signTypedData({domain:m,types:qt,primaryType:"PermitWitnessTransferFrom",message:h});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let S={signature:y,permit2Authorization:{from:t.address,permitted:{token:a,amount:i},spender:ke,nonce:f.toString(),deadline:String(u),witness:{to:o,validAfter:String(w)}}};return{serialized:JSON.stringify(S),signature:y,extensions:s,settlementProbe:{kind:"permit2",from:t.address,nonce:f.toString(),chainId:A}}}async readAllowance(e,t,r,o){let a="0xdd62ed3e",i=r.slice(2).toLowerCase().padStart(64,"0"),c=o.slice(2).toLowerCase().padStart(64,"0"),l=a+i+c;try{let p=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:l},"latest"]})})).json();return p.error||!p.result||p.result==="0x"?0n:BigInt(p.result)}catch{return 0n}}encodeApprove(e,t){let r="0x095ea7b3",o=e.slice(2).toLowerCase().padStart(64,"0"),a=t.toString(16).padStart(64,"0");return r+o+a}async waitForReceipt(e,t,r=3e4){let o=Date.now();for(;Date.now()-o<r;){try{let i=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionReceipt",params:[t]})})).json();if(i.result){if(i.result.status==="0x0")throw new Error(`Approval transaction reverted: ${t}`);return}}catch(a){if(a instanceof Error&&a.message.includes("reverted"))throw a}await new Promise(a=>setTimeout(a,2e3))}throw new Error(`Approval transaction receipt timeout after ${r}ms: ${t}`)}async readGasPrice(e){try{let r=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_gasPrice",params:[]})})).json();return r.result?BigInt(r.result):50000000n}catch{return 50000000n}}async readNonce(e,t){try{let o=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionCount",params:[t,"latest"]})})).json();return o.result?parseInt(o.result,16):0}catch{return 0}}calculateApprovalAmount(e,t,r){let o=BigInt(e)+BigInt(t);if(!r||r.mode==="exact")return o;let a=BigInt(r.defaultMultiple??10),i=o*a;if(r.maxCapUsd){let c=this.inferDecimals(e),l=BigInt(Math.floor(r.maxCapUsd*Math.pow(10,c)));if(i>l)return l}if(r.exactAboveUsd){let c=this.inferDecimals(e),l=BigInt(Math.floor(r.exactAboveUsd*Math.pow(10,c)));if(BigInt(e)>l)return o}return i}inferDecimals(e){return e.length>12?18:6}};function ae(n){return new Je(n)}function rt(n){if(n===Le||n===mt)return!0;let e=n.toLowerCase();for(let t of Object.values(Fe))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(qe))if(t.toLowerCase()===e)return!0;return!1}function Ht(n){return{[be]:"Solana",[$e]:"Solana Devnet",[Ke]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[ee]:"Base",[le]:"Base Sepolia",[he]:"Ethereum",[ue]:"Arbitrum",[pe]:"Polygon",[me]:"Optimism",[de]:"Avalanche",[fe]:"BSC",[ge]:"SKALE Base",[ye]:"SKALE Base Sepolia",base:"Base","base-sepolia":"Base Sepolia",ethereum:"Ethereum",arbitrum:"Arbitrum",polygon:"Polygon",optimism:"Optimism",avalanche:"Avalanche",bsc:"BSC","skale-base":"SKALE Base","skale-base-sepolia":"SKALE Base Sepolia"}[n]||n}function At(n,e){let t=Ht(n);return t===n?e:t}async function jt(n,e){if(typeof n=="string")return[n,e];if(n instanceof URL)return[n.href,e];let t=n,r=new Headers(t.headers);e?.headers&&new Headers(e.headers).forEach((i,c)=>r.set(c,i));let o={method:e?.method??t.method,headers:r,signal:e?.signal??t.signal,redirect:e?.redirect??t.redirect,credentials:e?.credentials??t.credentials},a=(o.method??"GET").toUpperCase();return e&&"body"in e?o.body=e.body:a!=="GET"&&a!=="HEAD"&&t.body&&(o.body=await t.arrayBuffer()),[t.url,o]}var St=new WeakMap;function ot(n){return St.get(n)}function Ue(n){let{adapters:e=[L({verbose:n.verbose}),ae({verbose:n.verbose})],wallets:t,wallet:r,preferredNetwork:o,rpcUrls:a={},maxAmountAtomic:i,fetch:c=globalThis.fetch,verbose:l=!1,accessPass:s,onPaymentRequired:p,onPaymentDispatched:f,maxRetries:g=0,retryDelayMs:w=500}=n,u=l?console.log.bind(console,"[x402]"):()=>{};async function A(b,T){let R;for(let x=0;x<=g;x++)try{let v=await c(b,T);if(v.status>=502&&v.status<=504&&x<g){u(`Retry ${x+1}/${g}: server returned ${v.status}`),await new Promise(_=>setTimeout(_,w*Math.pow(2,x)));continue}return v}catch(v){R=v,x<g&&(u(`Retry ${x+1}/${g}: ${v instanceof Error?v.message:"network error"}`),await new Promise(_=>setTimeout(_,w*Math.pow(2,x))))}throw R}let m=new Map;function h(b){try{let T=new URL(b).host,R=m.get(T);if(R&&R.expiresAt>Date.now()/1e3+10)return R.jwt;R&&m.delete(T)}catch{}return null}function y(b,T){try{let R=new URL(b).host,x=T.split(".");if(x.length===3){let v=JSON.parse(atob(x[1].replace(/-/g,"+").replace(/_/g,"/"))),_=Math.floor(Date.now()/1e3),I=_+86400,M=Math.min(typeof v.exp=="number"?v.exp:_,I);m.set(R,{jwt:T,expiresAt:M}),u("Access pass cached for",R,"| expires:",new Date(M*1e3).toISOString())}}catch{u("Failed to cache access pass")}}let S=t||{};r&&!S.solana&&re(r)&&(S.solana=r),r&&!S.evm&&oe(r)&&(S.evm=r);function P(b){let T=[];for(let R of b){let x=R.scheme??"exact";if(x!=="exact"&&x!=="exact-approval")continue;let v=e.find(I=>I.canHandle(R.network));if(!v)continue;let _;v.name==="Solana"?_=S.solana:v.name==="EVM"&&(_=S.evm),_&&v.isConnected(_)&&T.push({accept:R,adapter:v,wallet:_})}if(T.length===0)return null;if(o){let R=T.find(x=>x.accept.network===o);if(R)return R}return T[0]}function k(b,T){return At(b,T)}function F(b,T){return a[b]||T.getDefaultRpcUrl(b)}async function K(b,T,R,x,v){let _="";if(s?.preferTier&&x.tiers){let d=x.tiers.find(E=>E.id===s.preferTier);if(d){if(s.maxSpend&&parseFloat(d.price)>parseFloat(s.maxSpend))throw new C("access_pass_exceeds_max_spend",`Access pass tier "${d.id}" costs $${d.price}, exceeds max spend $${s.maxSpend}`);_=`tier=${d.id}`}}else if(s?.preferDuration&&x.ratePerHour)_=`duration=${s.preferDuration}`;else if(x.tiers&&x.tiers.length>0){let d=x.tiers[0];if(s?.maxSpend&&parseFloat(d.price)>parseFloat(s.maxSpend))throw new C("access_pass_exceeds_max_spend",`Cheapest access pass costs $${d.price}, exceeds max spend $${s?.maxSpend}`);_=`tier=${d.id}`}let I=_?v.includes("?")?`${v}&${_}`:`${v}?${_}`:v;u("Purchasing access pass:",_||"default tier");let M=R.headers.get("PAYMENT-REQUIRED");if(!M)return null;let B;try{B=JSON.parse(atob(M))}catch{return null}let O=P(B.accepts);if(!O)return null;let{accept:N,adapter:W,wallet:se}=O;if(W.name==="Solana"&&!N.extra?.feePayer)return null;let q=N.extra?.decimals??(rt(N.asset)?6:void 0);if(typeof q!="number")return null;let we=N.amount??N.maxAmountRequired;if(!we)return null;let H=F(N.network,W);try{let d=await W.getBalance(N,se,H),E=Number(we)/Math.pow(10,q);if(d<E){let Ze=k(N.network,W.name);throw new C("insufficient_balance",`Insufficient balance for access pass on ${Ze}. Have $${d.toFixed(4)}, need $${E.toFixed(4)}`)}}catch(d){if(d instanceof C)throw d}let j=await W.buildTransaction(N,se,H),ie;W.name==="EVM"?ie=JSON.parse(j.serialized):ie={transaction:j.serialized};let Q=typeof b=="string"?b:b instanceof URL?b.href:b.url,ce=B.resource;if(typeof B.resource=="string")try{let d=new URL(B.resource,Q);["http:","https:"].includes(d.protocol)&&(ce=d.toString())}catch{}else if(B.resource&&typeof B.resource=="object"&&"url"in B.resource){let d=B.resource;try{let E=new URL(d.url,Q);["http:","https:"].includes(E.protocol)&&(ce={...d,url:E.toString()})}catch{}}let Me={x402Version:N.x402Version??2,resource:ce,accepted:N,payload:ie};j.extensions&&(Me.extensions=j.extensions);let J=btoa(JSON.stringify(Me)),Z=await c(I,{...T,method:"POST",headers:{...T?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":J}});if(!Z.ok)return u("Pass purchase failed:",Z.status),null;let $=Z.headers.get("ACCESS-PASS");return $&&(y(v,$),u("Access pass purchased and cached")),Z}async function G(b,T){let R=b;if(u("Making request:",R),s){let d=h(R);if(d){u("Using cached access pass");let E=await c(b,{...T,headers:{...T?.headers||{},Authorization:`Bearer ${d}`}});if(E.status!==401&&E.status!==402)return E;u("Cached pass rejected (status",E.status,"), purchasing new pass");try{m.delete(new URL(R).host)}catch{}}}let x=await A(b,T);if(x.status!==402)return x;u("Received 402 Payment Required");let v=x.headers.get("X-ACCESS-PASS-TIERS");if(s&&v){u("Server offers access passes, purchasing...");try{let d=JSON.parse(atob(v)),E=await K(b,T,x,d,R);if(E)return E}catch(d){u("Access pass purchase failed, falling back to per-request payment:",d)}}let _=x.headers.get("PAYMENT-REQUIRED");if(!_)throw new C("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let I;try{let d=atob(_);I=JSON.parse(d)}catch{throw new C("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}u("Payment requirements:",I);let M=x.headers.get("X-Quote-Hash");M&&u("Quote hash received:",M);let B=P(I.accepts);if(!B){let d=I.accepts.map(E=>E.network).join(", ");throw new C("no_matching_payment_option",`No connected wallet for any available network: ${d}`)}let{accept:O,adapter:N,wallet:W}=B;if(u(`Using ${N.name} for ${O.network}`),N.name==="Solana"&&!O.extra?.feePayer)throw new C("missing_fee_payer","Solana payment option missing feePayer in extra");let se=O.extra?.decimals??(rt(O.asset)?6:void 0);if(typeof se!="number")throw new C("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let q=O.amount??O.maxAmountRequired;if(!q)throw new C("missing_amount","Payment option missing amount");if(i&&BigInt(q)>BigInt(i))throw new C("amount_exceeds_max",`Payment amount ${q} exceeds maximum ${i}`);let we=F(O.network,N);u("Checking balance...");try{let d=await N.getBalance(O,W,we),E=Number(q)/Math.pow(10,se);if(d<E){let Ze=k(O.network,N.name);throw new C("insufficient_balance",`Insufficient balance on ${Ze}. Have $${d.toFixed(4)}, need $${E.toFixed(4)}`)}u(`Balance OK: $${d.toFixed(4)} >= $${E.toFixed(4)}`)}catch(d){if(d instanceof C)throw d;u("Balance check failed (RPC error), proceeding with transaction attempt")}if(p&&!await p(O))throw new C("payment_rejected","Payment rejected by onPaymentRequired callback");u("Building transaction...");let H=await N.buildTransaction(O,W,we);u("Transaction signed");let j;N.name==="EVM"?j=JSON.parse(H.serialized):j={transaction:H.serialized};let ie=b,Q=I.resource;if(typeof I.resource=="string")try{let d=new URL(I.resource,ie).toString();d!==I.resource&&u("Resolved relative resource URL:",I.resource,"\u2192",d),Q=d}catch{Q=I.resource}else if(I.resource&&typeof I.resource=="object"&&"url"in I.resource){let d=I.resource;try{let E=new URL(d.url,ie).toString();E!==d.url&&(u("Resolved relative resource URL:",d.url,"\u2192",E),Q={...d,url:E})}catch{}}let ce={x402Version:O.x402Version??2,resource:Q,accepted:O,payload:j};H.extensions&&(ce.extensions=H.extensions);let Me=btoa(JSON.stringify(ce));if(f)try{f(O,H.settlementProbe)}catch{}u("Retrying request with payment...");let J=await A(b,{...T,headers:{...T?.headers||{},"PAYMENT-SIGNATURE":Me,...M?{"X-Quote-Hash":M}:{}}});if(u("Retry response status:",J.status),J.status===402){let d="unknown";try{let E=await J.clone().json();d=String(E.error||E.message||JSON.stringify(E)),u("Rejection reason:",d)}catch{}throw new C("payment_rejected",`Payment was rejected by the server: ${d}`)}let Z=J.headers.get("PAYMENT-RESPONSE"),$;if(Z)try{$=JSON.parse(atob(Z))}catch{}return $??={},$.amountAtomic=q,$.assetDecimals=se,St.set(J,$),$.extensions&&u("Settlement extensions:",Object.keys($.extensions).join(", ")),J}async function D(b,T){let[R,x]=await jt(b,T);return G(R,x)}return{fetch:D}}import{PublicKey as cr}from"@solana/web3.js";import{bytesToHex as at}from"@noble/hashes/utils";import Qn from"tweetnacl";import{sessionRegisterMessage as Xn,sessionRevokeMessage as zn,voucherPayloadMessage as Jt,buildVoucherMessage as Yn}from"@dexterai/vault/messages";import{sha256 as tr}from"@noble/hashes/sha256";function wt(n){return Buffer.from(JSON.stringify({payload:n.payload,sessionPublicKey:at(n.sessionPublicKey),sessionRegistration:at(n.sessionRegistration),sessionSignature:at(n.sessionSignature)}),"utf8").toString("base64")}function V(n){if(n instanceof Error){if(n.message&&n.message.length>0)return n.message;if(n.name&&n.name.length>0)return n.name}let e=String(n);return e.length>0?e:"unknown error"}async function Be(n){let e="";try{e=(await n.clone().text()).slice(0,600)}catch{}let t=e.toLowerCase(),r=t.includes("settle")||t.includes("facilitator"),o=e;try{let a=JSON.parse(e),i=[a.error,a.detail,a.message].filter(c=>typeof c=="string"&&c.length>0);i.length>0&&(o=i.join(" \u2014 "))}catch{}return o||(o=`HTTP ${n.status}`),{reason:r?"settlement_failed":"merchant_rejected",detail:`merchant HTTP ${n.status}: ${o}`}}var Xe="Payment authorization was sent, but the merchant did not respond within the timeout. ",ze=" Do not retry without checking \u2014 inspect the funding wallet for a transfer to the merchant before attempting payment again.";async function Ye(n,e,t){if(!n)return{confirmed:!1,detail:Xe+"This payment scheme has no on-chain confirmation check, so the SDK cannot verify whether it settled."+ze};try{if(n.kind==="solana"){let i=L(),c=t??i.getDefaultRpcUrl(e.caip2);if(!i.confirmSettlement)return xt();let l=await i.confirmSettlement(n,c);return l.settled?{confirmed:!0,txSignature:l.txSignature}:bt()}let r=ae(),o=r.getDefaultRpcUrl(e.caip2);if(!r.confirmSettlement)return xt();let a=await r.confirmSettlement(n,o);return a.settled?{confirmed:!0,txSignature:a.txSignature}:bt()}catch(r){return{confirmed:!1,detail:Xe+`On-chain confirmation could not be completed (${V(r)}).`+ze}}}function bt(){return{confirmed:!1,detail:Xe+"On-chain confirmation found no matching settlement yet \u2014 the payment may still be pending, or may not have settled."+ze}}function xt(){return{confirmed:!1,detail:Xe+"The chain adapter does not support on-chain confirmation."+ze}}var Et=[{caip2:"eip155:8453",bare:"base",family:"evm"},{caip2:"eip155:1",bare:"ethereum",family:"evm"},{caip2:"eip155:137",bare:"polygon",family:"evm"},{caip2:"eip155:42161",bare:"arbitrum",family:"evm"},{caip2:"eip155:10",bare:"optimism",family:"evm"},{caip2:"eip155:43114",bare:"avalanche",family:"evm"},{caip2:"eip155:56",bare:"bsc",family:"evm"},{caip2:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",bare:"solana",family:"svm"}],Xt=new Map(Et.map(n=>[n.caip2.toLowerCase(),n])),zt=new Map(Et.map(n=>[n.bare.toLowerCase(),n]));function Ae(n){if(!n)return null;let e=n.toLowerCase(),t=Xt.get(e)||zt.get(e);return t?{caip2:t.caip2,bare:t.bare,family:t.family}:null}function st(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-(e.length%4||4))%4);return JSON.parse(Buffer.from(t,"base64").toString("utf8"))}function Yt(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,o=Ae(String(r.network??""));o&&e.push({scheme:String(r.scheme??"exact"),network:o,amount:String(r.amount??r.maxAmountRequired??"0"),asset:String(r.asset??""),payTo:String(r.payTo??""),maxTimeoutSeconds:typeof r.maxTimeoutSeconds=="number"?r.maxTimeoutSeconds:void 0,extra:r.extra&&typeof r.extra=="object"?r.extra:void 0})}return e}async function Tt(n){let e=n.headers.get("payment-required");if(!e)return null;let t;try{t=st(e)}catch{return null}let r=Array.isArray(t.accepts)?t.accepts:[];return r.length===0?null:{x402Version:2,options:Yt(r),resourceUrl:t.resource&&typeof t.resource=="object"?String(t.resource.url??""):void 0}}var Gt=new Set(["exact","exact-approval"]);async function Qt(n,e,t,r){let o;try{o=await r.signNextVoucher(t.amount)}catch{return null}let a=new Headers(e.headers??void 0);a.set("X-Tab-Voucher",wt(o));let i={method:e.method??"GET",headers:a};e.signal&&(i.signal=e.signal),typeof e.body=="string"&&(i.body=e.body);let c;try{c=await fetch(n,i)}catch(l){return{ok:!1,reason:"error",detail:l?.message??String(l)}}return c.status===402?(r.rollbackVoucher?.call(r,o),null):c.ok?{ok:!0,paid:!0,response:c,amountPaid:t.amount,network:t.network}:{ok:!1,...await Be(c)}}var Pt={version:2,async parseChallenge(n){return Tt(n)},async pay(n,e,t,r,o){if(o.tab){let h=t.options.find(y=>y.scheme==="tab"&&y.network.family==="svm"&&y.payTo===o.tab.counterparty);if(h){let y=await Qt(n,e,h,o.tab);if(y)return y}}let a=t.options.filter(h=>Gt.has(h.scheme));if(a.length===0)return{ok:!1,reason:"no_payment_options",detail:`no generically payable scheme offered (got: ${t.options.map(h=>h.scheme).join(", ")})`};let i=a.find(h=>h.network.family==="evm"?!!r.evm:h.network.family==="svm"?!!r.solana:!1);if(!i)return{ok:!1,reason:"unsupported_network"};let c=o.timeoutMs??15e3,l=o.responseTimeoutMs??12e4,s=new AbortController,p=setTimeout(()=>s.abort(),c),f=!1,g,w=(h,y)=>{f=!0,g=y,clearTimeout(p),p=setTimeout(()=>s.abort(),l)},u=Ue({wallets:r,preferredNetwork:i.network.caip2,maxAmountAtomic:o.maxAmountAtomic,fetch:globalThis.fetch,onPaymentDispatched:w}),A=e.signal?AbortSignal.any([e.signal,s.signal]):s.signal,m={method:e.method??"GET",headers:e.headers,signal:A};typeof e.body=="string"&&(m.body=e.body);try{let h=await u.fetch(n,m);if(clearTimeout(p),!h.ok)return{ok:!1,...await Be(h)};let y,S=h.headers.get("PAYMENT-RESPONSE");if(S)try{let P=st(S);P&&typeof P.transaction=="string"&&(y=P.transaction)}catch{}return{ok:!0,paid:!0,response:h,amountPaid:i.amount,network:i.network,txSignature:y}}catch(h){clearTimeout(p);let y=h;if(y?.name==="AbortError"){if(!f)return{ok:!1,reason:"timeout"};let S=await Ye(g,i.network,o.solanaRpcUrl);return S.confirmed?{ok:!0,paid:!0,response:void 0,amountPaid:i.amount,network:i.network,txSignature:S.txSignature}:{ok:!1,reason:"payment_unconfirmed",detail:S.detail}}return{ok:!1,reason:"error",detail:y?.message??String(h)}}}};import{getAddress as Zt}from"viem";var en={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]};async function tn(){let n=globalThis.crypto??(await import("crypto")).webcrypto,e=new Uint8Array(32);return n.getRandomValues(e),"0x"+Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}async function nn(n,e,t){if(typeof n.signTypedData!="function")throw new Error("EVM wallet does not support signTypedData");let r=Math.floor(Date.now()/1e3),o=String(r-600),a=String(r+(e.maxTimeoutSeconds??60)),i={from:n.address,to:e.payTo,value:e.amount,validAfter:o,validBefore:a,nonce:await tn()},c=Oe[e.network.caip2];if(c===void 0)throw new Error(`unknown chain id for network ${e.network.caip2}`);let l=e.extra,s=await n.signTypedData({domain:{name:l.name,version:l.version,chainId:c,verifyingContract:Zt(e.asset)},types:en,primaryType:"TransferWithAuthorization",message:i});return{payment:{x402Version:1,scheme:e.scheme,network:t,payload:{signature:s,authorization:i}},settlementProbe:{kind:"eip3009",from:i.from,nonce:i.nonce,asset:e.asset,chainId:c}}}async function Ge(n,e,t){try{let r;for(let o of n.options){let a=o.network.family==="evm"&&!!e.evm||o.network.family==="svm"&&!!e.solana;if(o.scheme!=="exact"){a&&(r=o.scheme);continue}if(o.network.family==="evm"&&e.evm){let i=await e.evm;return await rn(o,i,t)}if(o.network.family==="svm"&&e.solana){let i=await e.solana;return await on(o,i,t)}}return r!==void 0?{ok:!1,reason:"merchant_rejected",detail:`v1 supports only the 'exact' scheme, got '${r}'`}:{ok:!1,reason:"unsupported_network"}}catch(r){return{ok:!1,reason:"error",detail:V(r)}}}async function rn(n,e,t){if(t.maxAmountAtomic!==void 0&&BigInt(n.amount)>BigInt(t.maxAmountAtomic))return{ok:!1,reason:"budget_exceeded"};let r=n.extra??{},o=r.name,a=r.version;if(typeof o!="string"||o.length===0||typeof a!="string"||a.length===0)return{ok:!1,reason:"merchant_rejected",detail:"v1 challenge missing exact-scheme EIP-712 domain (extra.name / extra.version)"};let i=n.network.bare,{payment:c,settlementProbe:l}=await nn(e,n,i);return{ok:!0,headerValue:Buffer.from(JSON.stringify(c),"utf8").toString("base64"),option:n,settlementProbe:l}}async function on(n,e,t){if(t.maxAmountAtomic!==void 0&&BigInt(n.amount)>BigInt(t.maxAmountAtomic))return{ok:!1,reason:"budget_exceeded"};if(n.scheme!=="exact")return{ok:!1,reason:"merchant_rejected",detail:`v1 SVM supports only the 'exact' scheme, got '${n.scheme}'`};let r=n.extra??{};if(typeof r.feePayer!="string"||r.feePayer.length===0)return{ok:!1,reason:"merchant_rejected",detail:"v1 SVM challenge missing extra.feePayer (required as the transaction fee payer)"};let o=n.network.bare,a={x402Version:1,scheme:n.scheme,network:o,asset:n.asset,payTo:n.payTo,amount:n.amount,maxAmountRequired:n.amount,maxTimeoutSeconds:n.maxTimeoutSeconds??60,extra:r},c=await L().buildTransaction(a,e,t.solanaRpcUrl),l={x402Version:1,scheme:n.scheme,network:o,payload:{transaction:c.serialized}};return{ok:!0,headerValue:Buffer.from(JSON.stringify(l),"utf8").toString("base64"),option:n,settlementProbe:c.settlementProbe}}function an(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,o=Ae(String(r.network??""));o&&e.push({scheme:String(r.scheme??"exact"),network:o,amount:String(r.maxAmountRequired??r.amount??"0"),asset:String(r.asset??""),payTo:String(r.payTo??""),maxTimeoutSeconds:typeof r.maxTimeoutSeconds=="number"?r.maxTimeoutSeconds:void 0,extra:r.extra&&typeof r.extra=="object"?r.extra:void 0})}return e}var Rt={version:1,async parseChallenge(n){if(n.headers.get("payment-required"))return null;let e;try{e=await n.clone().json()}catch{return null}let t=Array.isArray(e.accepts)?e.accepts:[];if(t.length===0)return null;let r=an(t);return r.length===0?null:{x402Version:1,options:r}},async pay(n,e,t,r,o){let a,i=new AbortController,c=!1,l,s;try{let p=o.timeoutMs??15e3;a=setTimeout(()=>i.abort(),p);let f=await Ge(t,r,o);if(!f.ok)return{ok:!1,reason:f.reason,detail:f.detail};let g=f.headerValue,w=f.option;s=w,l=f.settlementProbe;let u=new Headers(e.headers??void 0);u.set("X-PAYMENT",g);let A=e.signal!=null?AbortSignal.any([e.signal,i.signal]):i.signal,m={method:e.method,headers:u,signal:A};typeof e.body=="string"&&(m.body=e.body),c=!0,clearTimeout(a);let h=o.responseTimeoutMs??12e4;a=setTimeout(()=>i.abort(),h);let y=await fetch(n,m);return y.ok?{ok:!0,paid:!0,response:y,amountPaid:w.amount,network:w.network,txSignature:sn(y)}:{ok:!1,...await Be(y)}}catch(p){if(p instanceof Error&&p.name==="AbortError"){if(!c)return{ok:!1,reason:"timeout"};let f=await Ye(l,s.network,o.solanaRpcUrl);return f.confirmed?{ok:!0,paid:!0,response:void 0,amountPaid:s.amount,network:s.network,txSignature:f.txSignature}:{ok:!1,reason:"payment_unconfirmed",detail:f.detail}}return{ok:!1,reason:"error",detail:V(p)}}finally{a!==void 0&&clearTimeout(a)}}};function sn(n){let e=n.headers.get("x-payment-response")??n.headers.get("X-PAYMENT-RESPONSE");if(e)try{let t=JSON.parse(Buffer.from(e,"base64").toString("utf8")),r=t.transaction??t.txHash??t.transactionHash;return typeof r=="string"?r:void 0}catch{return}}import*as Nt from"tweetnacl";import{Keypair as De,VersionedTransaction as pn,Transaction as mn}from"@solana/web3.js";var Se=Symbol.for("x402:keypair");async function it(n){let e;if(typeof n=="string"){let t;try{let r=await Promise.resolve().then(()=>(It(),_t)),o=r.decode??r.default?.decode;if(!o)throw new Error("decode not found");t=o}catch{throw new Error('The "bs58" package is required for base58 private keys. Install it with: npm install bs58')}try{let r=t(n);e=De.fromSecretKey(r)}catch{try{let o=JSON.parse(n);if(Array.isArray(o))e=De.fromSecretKey(Uint8Array.from(o));else throw new Error("Invalid private key format")}catch{throw new Error("Invalid private key. Expected base58 string or JSON array of bytes.")}}}else if(Array.isArray(n))e=De.fromSecretKey(Uint8Array.from(n));else if(n instanceof Uint8Array)e=De.fromSecretKey(n);else throw new Error("Invalid private key type. Expected string, number[], or Uint8Array.");return{publicKey:{toBase58:()=>e.publicKey.toBase58()},signTransaction:async t=>{if(t instanceof pn)return t.sign([e]),t;if(t instanceof mn)return t.sign(e),t;throw new Error("Unknown transaction type")},[Se]:e}}function dn(n){if(!n||typeof n!="object")return!1;let e=n;return Se in e&&e[Se]instanceof De&&"publicKey"in e&&"signTransaction"in e}function Qe(n){let e=n.evm;if(e&&typeof e.signMessage=="function"&&typeof e.address=="string")return{address:e.address,signMessage:e.signMessage};let t=n.solana;if(t){let r=t[Se];if(r&&r.secretKey&&r.publicKey)return{publicKey:r.publicKey,signMessage:async o=>Nt.sign.detached(o,r.secretKey)}}return null}var kt=[Pt,Rt];async function Ot(n){for(let e of kt)if(await e.parseChallenge(n.clone()))return e;return null}async function fn(n){let e=Qe(n);if(!e)return fetch;try{return(await import("@x402/extensions/sign-in-with-x")).wrapFetchWithSIWx(fetch,e)}catch(t){return console.warn(`[x402] SIW-X unavailable \u2014 @x402/extensions failed to load; SIW-X merchants will not authenticate. ${V(t)}`),fetch}}async function Ut(n,e,t,r){if(e.body!==void 0&&e.body!==null&&typeof e.body!="string")return{ok:!1,reason:"error",detail:"payAndFetch requires a string body; non-string bodies (Buffer, FormData, URLSearchParams, ReadableStream) cannot be safely re-sent on the paid retry"};let o;try{o=await(await fn(t))(n,{...e})}catch(a){return{ok:!1,reason:"error",detail:V(a)}}if(o.status!==402)return{ok:!0,paid:!1,response:o};for(let a of kt){let i=await a.parseChallenge(o.clone());if(i)return a.pay(n,e,i,t,r)}return{ok:!1,reason:"no_payment_options"}}async function ct(n){let e;try{e=(await import("viem/accounts")).privateKeyToAccount}catch{throw new Error("EVM wallet support requires viem as a peer dependency. Install with: npm install viem")}let t=n.startsWith("0x")?n:`0x${n}`,r=e(t);return{address:r.address,signTypedData:o=>r.signTypedData(o),signTransaction:o=>r.signTransaction({to:o.to,data:o.data,chainId:o.chainId,gas:o.gas,gasPrice:o.gasPrice,nonce:o.nonce,type:"legacy"}),signMessage:o=>r.signMessage({message:o.message})}}function gn(n){if(!n||typeof n!="object")return!1;let e=n;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")&&"signTypedData"in e&&typeof e.signTypedData=="function"}function lt(n){let e=ot(n);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function yn(n){let e=lt(n);if(e?.recommendations?.length)return e.recommendations}async function hn(n){let t=lt(n)?.tracking?.impressionBeacon;if(!t)return!1;try{await fetch(t,{method:"GET"})}catch{}return!0}function ut(n,e){let{walletPrivateKey:t,evmPrivateKey:r,preferredNetwork:o,rpcUrls:a,maxAmountAtomic:i,verbose:c,accessPass:l,onPaymentRequired:s}=e;if(!t&&!r)throw new Error("At least one wallet private key is required (walletPrivateKey or evmPrivateKey)");let p={},f=[];t&&f.push(it(t).then(m=>{p.solana=m}).catch(m=>{console.warn(`[x402] Solana wallet init failed: ${m.message}`)})),r&&f.push(ct(r).then(m=>{p.evm=m}).catch(m=>{console.warn(`[x402] EVM wallet init failed: ${m.message}`)}));let g=f.length>0?Promise.all(f):null,u=Ue({wallets:p,preferredNetwork:o,rpcUrls:a,maxAmountAtomic:i,fetch:n,verbose:c,accessPass:l,onPaymentRequired:s}),A=u.fetch.bind(u);return g?(async(m,h)=>(await g,A(m,h))):A}function An(n){let{budget:e,allowedDomains:t,onPaymentRequired:r,...o}=n,a=parseFloat(e.total),i=e.perRequest?parseFloat(e.perRequest):1/0,c=e.perHour?parseFloat(e.perHour):1/0;if(isNaN(a)||a<=0)throw new Error("budget.total must be a positive number");let l=[],s=0;function p(){return l.reduce((u,A)=>u+A.amount,0)}function f(){let u=Date.now()-36e5;return l.filter(A=>A.timestamp>=u).reduce((A,m)=>A+m.amount,0)}let g=ut(fetch,{...o,onPaymentRequired:async u=>{let A=u.extra?.decimals??6,m=Number(u.amount)/Math.pow(10,A);if(m>i)throw new C("amount_exceeds_max",`$${m.toFixed(4)} exceeds per-request limit of $${i.toFixed(2)}`);let h=p();if(h+m>a)throw new C("amount_exceeds_max",`Budget exceeded. Spent $${h.toFixed(2)} of $${a.toFixed(2)}, payment: $${m.toFixed(4)}`);let y=f();if(y+m>c)throw new C("amount_exceeds_max",`Hourly limit ($${c.toFixed(2)}) exceeded. Spent $${y.toFixed(2)} this hour`);return s=m,r?r(u):!0}});return{fetch:(async(u,A)=>{let m=typeof u=="string"?u:u instanceof URL?u.href:u.url,h="unknown";try{h=new URL(m).hostname}catch{}if(t&&!t.some(S=>h===S||h.endsWith(`.${S}`)))throw new C("payment_rejected",`Domain "${h}" not in allowed domains`);s=0;let y=await g(u,A);if(s>0){let S="unknown",P=y.headers.get("PAYMENT-RESPONSE");if(P)try{S=JSON.parse(atob(P)).network||S}catch{}l.push({amount:s,domain:h,network:S,timestamp:Date.now()}),s=0}return y}),get spent(){return`$${p().toFixed(2)}`},get remaining(){return`$${(a-p()).toFixed(2)}`},get payments(){return l.length},get spentAmount(){return p()},get remainingAmount(){return a-p()},get ledger(){return l},get hourlySpend(){return f()},reset(){l=[]}}}import{capabilitySearch as Sn}from"@dexterai/x402-core";export{z as BASE_MAINNET,ft as DEXTER_FACILITATOR_URL,Se as KEYPAIR_SYMBOL,X as SOLANA_MAINNET,Le as USDC_MINT,C as X402Error,Ge as buildV1PaymentHeader,Sn as capabilitySearch,An as createBudgetAccount,ae as createEvmAdapter,ct as createEvmKeypairWallet,it as createKeypairWallet,L as createSolanaAdapter,Ue as createX402Client,Ot as detectStrategy,hn as fireImpressionBeacon,ot as getPaymentReceipt,lt as getSponsoredAccessInfo,yn as getSponsoredRecommendations,gn as isEvmKeypairWallet,dn as isKeypairWallet,Ut as payAndFetch,Ae as toNetworkRef,Qe as toSiwxSigner,ut as wrapFetch};