@dexterai/x402 3.17.0 → 3.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +126 -455
- package/dist/client/index.d.cts +2 -2
- package/dist/client/index.d.ts +2 -2
- package/dist/tab/adapters/solana/index.d.cts +1 -1
- package/dist/tab/adapters/solana/index.d.ts +1 -1
- package/dist/tab/index.cjs +1 -1
- package/dist/tab/index.d.cts +9 -7
- package/dist/tab/index.d.ts +9 -7
- package/dist/tab/index.js +1 -1
- package/dist/tab/seller/index.cjs +4 -4
- package/dist/tab/seller/index.d.cts +174 -8
- package/dist/tab/seller/index.d.ts +174 -8
- package/dist/tab/seller/index.js +4 -4
- package/dist/{types-ZjcxOAbW.d.ts → types-BL9QW1gf.d.ts} +1 -1
- package/dist/{types-B1wGPP7B.d.cts → types-DMzS_Rh2.d.cts} +1 -1
- package/dist/{types-DEnVPFxF.d.cts → types-DuoL3s8n.d.cts} +1 -1
- package/dist/{types-DEnVPFxF.d.ts → types-DuoL3s8n.d.ts} +1 -1
- package/package.json +1 -1
package/dist/client/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as PayAndFetchOptions, a as PayResult, b as PaymentStrategy, N as NetworkRef, c as PaymentChallenge, C as ChallengeOption } from '../types-
|
|
1
|
+
import { P as PayAndFetchOptions, a as PayResult, b as PaymentStrategy, N as NetworkRef, c as PaymentChallenge, C as ChallengeOption } from '../types-DMzS_Rh2.cjs';
|
|
2
2
|
import { W as WalletSet, S as SettlementProbe, a as SolanaWallet, E as EvmWallet, A as AccessPassClientConfig, P as PaymentAccept } from '../types-xQu1U4xk.cjs';
|
|
3
3
|
export { e as AccessPassInfo, d as AccessPassTier, C as ChainAdapter, X as X402Error, b as createEvmAdapter, c as createSolanaAdapter } from '../types-xQu1U4xk.cjs';
|
|
4
4
|
import { SIWxSigner } from '@x402/extensions/sign-in-with-x';
|
|
@@ -7,7 +7,7 @@ export { P as PaymentReceipt, d as X402Client, X as X402ClientConfig, c as creat
|
|
|
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.cjs';
|
|
9
9
|
export { SponsoredAccessSettlementInfo, SponsoredRecommendation } from '@dexterai/x402-ads-types';
|
|
10
|
-
import '../types-
|
|
10
|
+
import '../types-DuoL3s8n.cjs';
|
|
11
11
|
import '@dexterai/vault/types';
|
|
12
12
|
|
|
13
13
|
/**
|
package/dist/client/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as PayAndFetchOptions, a as PayResult, b as PaymentStrategy, N as NetworkRef, c as PaymentChallenge, C as ChallengeOption } from '../types-
|
|
1
|
+
import { P as PayAndFetchOptions, a as PayResult, b as PaymentStrategy, N as NetworkRef, c as PaymentChallenge, C as ChallengeOption } from '../types-BL9QW1gf.js';
|
|
2
2
|
import { W as WalletSet, S as SettlementProbe, a as SolanaWallet, E as EvmWallet, A as AccessPassClientConfig, P as PaymentAccept } from '../types-xQu1U4xk.js';
|
|
3
3
|
export { e as AccessPassInfo, d as AccessPassTier, C as ChainAdapter, X as X402Error, b as createEvmAdapter, c as createSolanaAdapter } from '../types-xQu1U4xk.js';
|
|
4
4
|
import { SIWxSigner } from '@x402/extensions/sign-in-with-x';
|
|
@@ -7,7 +7,7 @@ export { P as PaymentReceipt, d as X402Client, X as X402ClientConfig, c as creat
|
|
|
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-
|
|
10
|
+
import '../types-DuoL3s8n.js';
|
|
11
11
|
import '@dexterai/vault/types';
|
|
12
12
|
|
|
13
13
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as _solana_web3_js from '@solana/web3.js';
|
|
2
2
|
import { PublicKey, Connection, Signer, ConfirmOptions } from '@solana/web3.js';
|
|
3
|
-
import { V as VaultAdapter } from '../../../types-
|
|
3
|
+
import { V as VaultAdapter } from '../../../types-DuoL3s8n.cjs';
|
|
4
4
|
import '@dexterai/vault/types';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as _solana_web3_js from '@solana/web3.js';
|
|
2
2
|
import { PublicKey, Connection, Signer, ConfirmOptions } from '@solana/web3.js';
|
|
3
|
-
import { V as VaultAdapter } from '../../../types-
|
|
3
|
+
import { V as VaultAdapter } from '../../../types-DuoL3s8n.js';
|
|
4
4
|
import '@dexterai/vault/types';
|
|
5
5
|
|
|
6
6
|
/**
|
package/dist/tab/index.cjs
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
`))!==-1;){let i=r.slice(0,o);r=r.slice(o+2);let c=tn(i);if(c.eventName==="end")return;if(c.data!==null){let l=c.data.replace(/\\n/g,`
|
|
4
4
|
`);yield new TextEncoder().encode(l)}}}}finally{e.releaseLock()}}function tn(n){let e=null,t=[];for(let r of n.split(`
|
|
5
5
|
`))r.startsWith("event:")?e=r.slice(6).trim():r.startsWith("data:")&&t.push(r.slice(5).trimStart());return{eventName:e,data:t.length?t.join(`
|
|
6
|
-
`):null}}var vt=require("@solana/web3.js");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"}],nn=new Map(Pt.map(n=>[n.caip2.toLowerCase(),n])),rn=new Map(Pt.map(n=>[n.bare.toLowerCase(),n]));function Ne(n){if(!n)return null;let e=n.toLowerCase(),t=nn.get(e)||rn.get(e);return t?{caip2:t.caip2,bare:t.bare,family:t.family}:null}function dt(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 sn(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,s=Ne(String(r.network??""));s&&e.push({scheme:String(r.scheme??"exact"),network:s,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 Qe(n){let e=n.headers.get("payment-required");if(!e)return null;let t;try{t=dt(e)}catch{return null}let r=Array.isArray(t.accepts)?t.accepts:[];return r.length===0?null:{x402Version:2,options:sn(r),resourceUrl:t.resource&&typeof t.resource=="object"?String(t.resource.url??""):void 0}}async function Ae(n,e={},t=fetch){let r={method:e.method??"GET",headers:e.headers};typeof e.body=="string"&&(r.body=e.body);let s;try{s=await t(n,r)}catch(i){return{kind:"error",detail:`probe failed: ${i?.message??String(i)}`}}if(s.status!==402)return s.ok?{kind:"free",response:s}:{kind:"error",detail:`probe returned HTTP ${s.status}`};let a=await Qe(s);if(!a)return{kind:"error",detail:"the 402 carries no x402 v2 PAYMENT-REQUIRED challenge"};let o=a.options.find(i=>i.scheme==="tab"&&i.network.family==="svm");if(!o)return{kind:"no_tab",schemesOffered:a.options.map(i=>i.scheme)};try{new vt.PublicKey(o.payTo)}catch{return{kind:"error",detail:`tab option payTo is not a valid Solana pubkey: "${o.payTo}"`}}return{kind:"offer",offer:{payTo:o.payTo,amountAtomic:o.amount,asset:o.asset,networkCaip2:o.network.caip2,resourceUrl:a.resourceUrl}}}var Oe="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Ze="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",et="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",le=Oe,Ue=Ze,Be=et,ue="eip155:8453",be="eip155:84532",we="eip155:42161",Te="eip155:137",xe="eip155:10",Ee="eip155:43114",Re="eip155:56",Pe="eip155:1187947933",ve="eip155:324705682",_e="eip155:1",pe=ue,tt=be,De=we,Me=Te,$e=xe,Le=Ee,Ve=Re,Ke=Pe,We=ve,qe=_e,He="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",_t="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",Ct="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",ft="0x55d398326f99059fF775485246999027B3197955",nt="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",rt={[Re]:nt,[ue]:Ct,[be]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[we]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[Te]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[xe]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[Ee]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[Pe]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[ve]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[_e]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},st={[ft]:{symbol:"USDT",decimals:18},[nt]:{symbol:"USDC",decimals:18}};var te="0x000000000022D473030F116dDEE9F6B43aC78BA3",Fe="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",je={[Re]:56,[ue]:8453,[be]:84532,[we]:42161,[Te]:137,[xe]:10,[Ee]:43114,[Pe]:1187947933,[ve]:324705682,[_e]:1},me={[Oe]:"https://api.dexter.cash/api/solana/rpc",[Ze]:"https://api.devnet.solana.com",[et]:"https://api.testnet.solana.com"},D={[Re]:"https://api.dexter.cash/api/evm/bsc/rpc",[ue]:"https://api.dexter.cash/api/base/rpc",[be]:"https://sepolia.base.org",[we]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[Te]:"https://api.dexter.cash/api/evm/polygon/rpc",[xe]:"https://api.dexter.cash/api/evm/optimism/rpc",[Ee]:"https://api.dexter.cash/api/evm/avalanche/rpc",[Pe]:"https://skale-base.skalenodes.com/v1/base",[ve]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[_e]:"https://eth.llamarpc.com"};var k=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)}};var I=require("@solana/web3.js"),N=require("@solana/spl-token");var an=12e3,on=1;function de(n){if(!n||typeof n!="object")return!1;let e=n;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var at=class{name="Solana";networks=[le,Ue,Be];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]:me[e]?me[e]:e==="solana"?me[le]:e==="solana-devnet"?me[Ue]:e==="solana-testnet"?me[Be]:me[le]}getAddress(e){return de(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return de(e)?e.publicKey!==null:!1}async getBalance(e,t,r){if(!de(t)||!t.publicKey)return 0;let s=r||this.getDefaultRpcUrl(e.network),a=new I.Connection(s,"confirmed"),o=new I.PublicKey(t.publicKey.toBase58()),i=new I.PublicKey(e.asset);try{let l=(await a.getAccountInfo(i,"confirmed"))?.owner.toBase58()===N.TOKEN_2022_PROGRAM_ID.toBase58()?N.TOKEN_2022_PROGRAM_ID:N.TOKEN_PROGRAM_ID,m=await(0,N.getAssociatedTokenAddress)(i,o,!1,l),f=await(0,N.getAccount)(a,m,void 0,l),d=e.extra?.decimals??6;return Number(f.amount)/Math.pow(10,d)}catch(c){if(c&&typeof c=="object"&&"name"in c&&(c.name==="TokenAccountNotFoundError"||c.name==="TokenInvalidAccountOwnerError"))return 0;throw c}}async buildTransaction(e,t,r){if(!de(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let s=r||this.getDefaultRpcUrl(e.network),a=new I.Connection(s,"confirmed"),o=new I.PublicKey(t.publicKey.toBase58()),{payTo:i,asset:c,extra:l}=e,m=e.amount??e.maxAmountRequired;if(!m)throw new Error("Missing amount in payment requirements");if(!l?.feePayer)throw new Error("Missing feePayer in payment requirements");let f=new I.PublicKey(l.feePayer),d=new I.PublicKey(c),E=new I.PublicKey(i);this.log("Building transaction:",{from:o.toBase58(),to:i,amount:m,asset:c,feePayer:l.feePayer});let p=[];p.push(I.ComputeBudgetProgram.setComputeUnitLimit({units:an})),p.push(I.ComputeBudgetProgram.setComputeUnitPrice({microLamports:on}));let _=await a.getAccountInfo(d,"confirmed");if(!_)throw new Error(`Token mint ${c} not found`);let R=_.owner.toBase58()===N.TOKEN_2022_PROGRAM_ID.toBase58()?N.TOKEN_2022_PROGRAM_ID:N.TOKEN_PROGRAM_ID,h=await(0,N.getMint)(a,d,void 0,R);typeof l?.decimals=="number"&&h.decimals!==l.decimals&&this.log(`Decimals mismatch: requirements say ${l.decimals}, mint says ${h.decimals}`);let y=await(0,N.getAssociatedTokenAddress)(d,o,!1,R),x=await(0,N.getAssociatedTokenAddress)(d,E,!0,R);if(!await a.getAccountInfo(y,"confirmed"))throw new Error(`No token account found for ${c}. Please ensure you have USDC in your wallet.`);if(!await a.getAccountInfo(x,"confirmed"))throw new Error(`Seller token account not found. The seller (${i}) must have a USDC account.`);let j=BigInt(m);p.push((0,N.createTransferCheckedInstruction)(y,d,x,o,j,h.decimals,[],R));let{blockhash:W}=await a.getLatestBlockhash("confirmed"),re=new I.TransactionMessage({payerKey:f,recentBlockhash:W,instructions:p}).compileToV0Message(),L=new I.VersionedTransaction(re),g=await t.signTransaction(L);return this.log("Transaction signed successfully"),{serialized:Buffer.from(g.serialize()).toString("base64"),settlementProbe:{kind:"solana",sourceAta:y.toBase58(),destinationAta:x.toBase58(),asset:c,amount:m,blockhash:W}}}async confirmSettlement(e,t){if(e.kind!=="solana")throw new Error(`SolanaAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`);let r=new I.Connection(t,"confirmed"),s=new I.PublicKey(e.destinationAta),a=await r.getSignaturesForAddress(s,{limit:25});if(a.length===0)return{settled:!1};let o=BigInt(e.amount);for(let i of a){if(i.err)continue;let c=await r.getTransaction(i.signature,{commitment:"confirmed",maxSupportedTransactionVersion:0});if(!c?.meta)continue;let l=c.transaction.message.getAccountKeys().keySegments().flat(),m=c.meta.preTokenBalances??[],f=c.meta.postTokenBalances??[];for(let d of f){if(d.mint!==e.asset)continue;let E=l[d.accountIndex];if(!E||!E.equals(s))continue;let p=m.find(h=>h.accountIndex===d.accountIndex),_=BigInt(p?.uiTokenAmount.amount??"0");if(BigInt(d.uiTokenAmount.amount??"0")-_===o)return{settled:!0,txSignature:i.signature}}}return{settled:!1}}};function ne(n){return new at(n)}var cn={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"}]},kt=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function fe(n){if(!n||typeof n!="object")return!1;let e=n;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var ot=class{name="EVM";networks=[Ve,pe,tt,qe,De,Me,$e,Le,Ke,We];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]:D[e]?D[e]:e==="base"?D[pe]:e==="bsc"?D[Ve]:e==="ethereum"?D[qe]:e==="arbitrum"?D[De]:e==="polygon"?D[Me]:e==="optimism"?D[$e]:e==="avalanche"?D[Le]:e==="skale-base"?D[Ke]:e==="skale-base-sepolia"?D[We]:D[pe]}getAddress(e){return fe(e)?e.address:null}isConnected(e){return fe(e)?!!e.address:!1}getChainId(e){if(je[e])return je[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(!fe(t)||!t.address)return 0;let s=r||this.getDefaultRpcUrl(e.network);try{let a=this.encodeBalanceOf(t.address),o=await fetch(s,{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(!o.ok)throw new Error(`RPC request failed: ${o.status}`);let i=await o.json();if(i.error)throw new Error(`RPC error: ${JSON.stringify(i.error)}`);if(!i.result||i.result==="0x")return 0;let c=BigInt(i.result),l=e.extra?.decimals??6;return Number(c)/Math.pow(10,l)}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",s=e.from.slice(2).toLowerCase().padStart(64,"0"),a=e.nonce.slice(2).toLowerCase().padStart(64,"0"),o=r+s+a,i=await this.ethCall(t,e.asset,o);return{settled:BigInt(i)!==0n}}if(e.kind==="permit2"){let r="0x4fe02b44",s=BigInt(e.nonce),a=s>>8n,o=s&0xffn,i=e.from.slice(2).toLowerCase().padStart(64,"0"),c=a.toString(16).padStart(64,"0"),l=r+i+c,m=await this.ethCall(t,te,l);return{settled:(BigInt(m)>>o&1n)===1n}}throw new Error(`EvmAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`)}async ethCall(e,t,r){let s=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(!s.ok)throw new Error(`RPC request failed: ${s.status}`);let a=await s.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(!fe(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:s,asset:a,extra:o}=e,i=e.amount??e.maxAmountRequired;if(!i)throw new Error("Missing amount in payment requirements");this.log("Building EVM transaction:",{from:t.address,to:s,amount:i,asset:a,network:e.network});let c=this.getChainId(e.network),l={name:o?.name??"USD Coin",version:o?.version??"2",chainId:BigInt(c),verifyingContract:a},m={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 d="0x"+[...f].map(y=>y.toString(16).padStart(2,"0")).join(""),E=Math.floor(Date.now()/1e3),p={from:t.address,to:s,value:i,validAfter:String(E-600),validBefore:String(E+(e.maxTimeoutSeconds||60)),nonce:d},_={from:t.address,to:s,value:BigInt(i),validAfter:BigInt(E-600),validBefore:BigInt(E+(e.maxTimeoutSeconds||60)),nonce:d};if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let R=await t.signTypedData({domain:l,types:m,primaryType:"TransferWithAuthorization",message:_});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:p,signature:R}),signature:R,settlementProbe:{kind:"eip3009",from:t.address,nonce:d,asset:a,chainId:c}}}async buildApprovalTransaction(e,t,r){let{payTo:s,asset:a,extra:o}=e,i=e.amount??e.maxAmountRequired;if(!i)throw new Error("Missing amount in payment requirements");let c=o?.facilitatorContract;if(!c)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:s,amount:i,asset:a,network:e.network,facilitatorContract:c});let l=r||this.getDefaultRpcUrl(e.network),m=o?.fee??"0",f=BigInt(i)+BigInt(m),d=await this.readAllowance(l,a,t.address,c);if(d<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 L=this.calculateApprovalAmount(i,m,o?.approvalStrategy);this.log(`Approving ${L} for ${c} (current allowance: ${d})`);let g=await t.sendTransaction({to:a,data:this.encodeApprove(c,L),value:0n});this.log(`Approval tx sent: ${g}`),await this.waitForReceipt(l,g),this.log("Approval confirmed")}else this.log("Sufficient allowance, skipping approval");let E=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(E);let p=[...E].reduce((L,g)=>L*256n+BigInt(g),0n).toString(),_=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(_);let R="0x"+[..._].map(L=>L.toString(16).padStart(2,"0")).join(""),y=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),x=o?.eip712Domain,U=x?{name:x.name,version:x.version,chainId:BigInt(x.chainId),verifyingContract:x.verifyingContract}:{name:"DexterBSCFacilitator",version:"1",chainId:BigInt(this.getChainId(e.network)),verifyingContract:c},M=o?.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"}]},j={from:t.address,to:s,token:a,amount:BigInt(i),fee:BigInt(m),nonce:BigInt(p),deadline:BigInt(y),paymentId:R},W=await t.signTypedData({domain:U,types:M,primaryType:"Payment",message:j});this.log("EIP-712 Payment signature obtained");let re={from:t.address,to:s,token:a,amount:i,fee:m,nonce:p,deadline:y,paymentId:R,signature:W};return{serialized:JSON.stringify(re),signature:W}}async buildPermit2Transaction(e,t,r){let{payTo:s,asset:a}=e,o=e.amount??e.maxAmountRequired;if(!o)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:s,amount:o,asset:a,network:e.network});let i=r||this.getDefaultRpcUrl(e.network),c=await this.readAllowance(i,a,t.address,te),l;if(c<BigInt(o)){let U=this.encodeApprove(te,kt);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${c})`);let M=this.getChainId(e.network),j=await this.readGasPrice(i),W=await this.readNonce(i,t.address),re=await t.signTransaction({to:a,data:U,chainId:M,gas:50000n,gasPrice:j,nonce:W});l={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:a,spender:te,amount:kt.toString(),signedTransaction:re,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${c})`);let M=await t.sendTransaction({to:a,data:U,value:0n});this.log(`Permit2 approval tx sent: ${M}`),await this.waitForReceipt(i,M),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 m=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(m);let f=[...m].reduce((U,M)=>U*256n+BigInt(M),0n),d=Math.floor(Date.now()/1e3),E=d-600,p=d+(e.maxTimeoutSeconds||300),_=this.getChainId(e.network),R={name:"Permit2",chainId:BigInt(_),verifyingContract:te},h={permitted:{token:a,amount:BigInt(o)},spender:Fe,nonce:f,deadline:BigInt(p),witness:{to:s,validAfter:BigInt(E)}},y=await t.signTypedData({domain:R,types:cn,primaryType:"PermitWitnessTransferFrom",message:h});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let x={signature:y,permit2Authorization:{from:t.address,permitted:{token:a,amount:o},spender:Fe,nonce:f.toString(),deadline:String(p),witness:{to:s,validAfter:String(E)}}};return{serialized:JSON.stringify(x),signature:y,extensions:l,settlementProbe:{kind:"permit2",from:t.address,nonce:f.toString(),chainId:_}}}async readAllowance(e,t,r,s){let a="0xdd62ed3e",o=r.slice(2).toLowerCase().padStart(64,"0"),i=s.slice(2).toLowerCase().padStart(64,"0"),c=a+o+i;try{let m=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:c},"latest"]})})).json();return m.error||!m.result||m.result==="0x"?0n:BigInt(m.result)}catch{return 0n}}encodeApprove(e,t){let r="0x095ea7b3",s=e.slice(2).toLowerCase().padStart(64,"0"),a=t.toString(16).padStart(64,"0");return r+s+a}async waitForReceipt(e,t,r=3e4){let s=Date.now();for(;Date.now()-s<r;){try{let o=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(o.result){if(o.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 s=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 s.result?parseInt(s.result,16):0}catch{return 0}}calculateApprovalAmount(e,t,r){let s=BigInt(e)+BigInt(t);if(!r||r.mode==="exact")return s;let a=BigInt(r.defaultMultiple??10),o=s*a;if(r.maxCapUsd){let i=this.inferDecimals(e),c=BigInt(Math.floor(r.maxCapUsd*Math.pow(10,i)));if(o>c)return c}if(r.exactAboveUsd){let i=this.inferDecimals(e),c=BigInt(Math.floor(r.exactAboveUsd*Math.pow(10,i)));if(BigInt(e)>c)return s}return o}inferDecimals(e){return e.length>12?18:6}};function Ce(n){return new ot(n)}function gt(n){if(n===He||n===_t)return!0;let e=n.toLowerCase();for(let t of Object.values(rt))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(st))if(t.toLowerCase()===e)return!0;return!1}function ln(n){return{[Oe]:"Solana",[Ze]:"Solana Devnet",[et]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[ue]:"Base",[be]:"Base Sepolia",[_e]:"Ethereum",[we]:"Arbitrum",[Te]:"Polygon",[xe]:"Optimism",[Ee]:"Avalanche",[Re]:"BSC",[Pe]:"SKALE Base",[ve]:"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 It(n,e){let t=ln(n);return t===n?e:t}async function un(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((o,i)=>r.set(i,o));let s={method:e?.method??t.method,headers:r,signal:e?.signal??t.signal,redirect:e?.redirect??t.redirect,credentials:e?.credentials??t.credentials},a=(s.method??"GET").toUpperCase();return e&&"body"in e?s.body=e.body:a!=="GET"&&a!=="HEAD"&&t.body&&(s.body=await t.arrayBuffer()),[t.url,s]}var pn=new WeakMap;function Nt(n){let{adapters:e=[ne({verbose:n.verbose}),Ce({verbose:n.verbose})],wallets:t,wallet:r,preferredNetwork:s,rpcUrls:a={},maxAmountAtomic:o,fetch:i=globalThis.fetch,verbose:c=!1,accessPass:l,onPaymentRequired:m,onPaymentDispatched:f,maxRetries:d=0,retryDelayMs:E=500}=n,p=c?console.log.bind(console,"[x402]"):()=>{};async function _(g,b){let w;for(let S=0;S<=d;S++)try{let T=await i(g,b);if(T.status>=502&&T.status<=504&&S<d){p(`Retry ${S+1}/${d}: server returned ${T.status}`),await new Promise(P=>setTimeout(P,E*Math.pow(2,S)));continue}return T}catch(T){w=T,S<d&&(p(`Retry ${S+1}/${d}: ${T instanceof Error?T.message:"network error"}`),await new Promise(P=>setTimeout(P,E*Math.pow(2,S))))}throw w}let R=new Map;function h(g){try{let b=new URL(g).host,w=R.get(b);if(w&&w.expiresAt>Date.now()/1e3+10)return w.jwt;w&&R.delete(b)}catch{}return null}function y(g,b){try{let w=new URL(g).host,S=b.split(".");if(S.length===3){let T=JSON.parse(atob(S[1].replace(/-/g,"+").replace(/_/g,"/"))),P=Math.floor(Date.now()/1e3),v=P+86400,V=Math.min(typeof T.exp=="number"?T.exp:P,v);R.set(w,{jwt:b,expiresAt:V}),p("Access pass cached for",w,"| expires:",new Date(V*1e3).toISOString())}}catch{p("Failed to cache access pass")}}let x=t||{};r&&!x.solana&&de(r)&&(x.solana=r),r&&!x.evm&&fe(r)&&(x.evm=r);function U(g){let b=[];for(let w of g){let S=w.scheme??"exact";if(S!=="exact"&&S!=="exact-approval")continue;let T=e.find(v=>v.canHandle(w.network));if(!T)continue;let P;T.name==="Solana"?P=x.solana:T.name==="EVM"&&(P=x.evm),P&&T.isConnected(P)&&b.push({accept:w,adapter:T,wallet:P})}if(b.length===0)return null;if(s){let w=b.find(S=>S.accept.network===s);if(w)return w}return b[0]}function M(g,b){return It(g,b)}function j(g,b){return a[g]||b.getDefaultRpcUrl(g)}async function W(g,b,w,S,T){let P="";if(l?.preferTier&&S.tiers){let u=S.tiers.find(A=>A.id===l.preferTier);if(u){if(l.maxSpend&&parseFloat(u.price)>parseFloat(l.maxSpend))throw new k("access_pass_exceeds_max_spend",`Access pass tier "${u.id}" costs $${u.price}, exceeds max spend $${l.maxSpend}`);P=`tier=${u.id}`}}else if(l?.preferDuration&&S.ratePerHour)P=`duration=${l.preferDuration}`;else if(S.tiers&&S.tiers.length>0){let u=S.tiers[0];if(l?.maxSpend&&parseFloat(u.price)>parseFloat(l.maxSpend))throw new k("access_pass_exceeds_max_spend",`Cheapest access pass costs $${u.price}, exceeds max spend $${l?.maxSpend}`);P=`tier=${u.id}`}let v=P?T.includes("?")?`${T}&${P}`:`${T}?${P}`:T;p("Purchasing access pass:",P||"default tier");let V=w.headers.get("PAYMENT-REQUIRED");if(!V)return null;let $;try{$=JSON.parse(atob(V))}catch{return null}let O=U($.accepts);if(!O)return null;let{accept:C,adapter:q,wallet:ye}=O;if(q.name==="Solana"&&!C.extra?.feePayer)return null;let J=C.extra?.decimals??(gt(C.asset)?6:void 0);if(typeof J!="number")return null;let ke=C.amount??C.maxAmountRequired;if(!ke)return null;let X=j(C.network,q);try{let u=await q.getBalance(C,ye,X),A=Number(ke)/Math.pow(10,J);if(u<A){let ut=M(C.network,q.name);throw new k("insufficient_balance",`Insufficient balance for access pass on ${ut}. Have $${u.toFixed(4)}, need $${A.toFixed(4)}`)}}catch(u){if(u instanceof k)throw u}let Y=await q.buildTransaction(C,ye,X),he;q.name==="EVM"?he=JSON.parse(Y.serialized):he={transaction:Y.serialized};let se=typeof g=="string"?g:g instanceof URL?g.href:g.url,Se=$.resource;if(typeof $.resource=="string")try{let u=new URL($.resource,se);["http:","https:"].includes(u.protocol)&&(Se=u.toString())}catch{}else if($.resource&&typeof $.resource=="object"&&"url"in $.resource){let u=$.resource;try{let A=new URL(u.url,se);["http:","https:"].includes(A.protocol)&&(Se={...u,url:A.toString()})}catch{}}let Xe={x402Version:C.x402Version??2,resource:Se,accepted:C,payload:he};Y.extensions&&(Xe.extensions=Y.extensions);let z=btoa(JSON.stringify(Xe)),ae=await i(v,{...b,method:"POST",headers:{...b?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":z}});if(!ae.ok)return p("Pass purchase failed:",ae.status),null;let K=ae.headers.get("ACCESS-PASS");return K&&(y(T,K),p("Access pass purchased and cached")),ae}async function re(g,b){let w=g;if(p("Making request:",w),l){let u=h(w);if(u){p("Using cached access pass");let A=await i(g,{...b,headers:{...b?.headers||{},Authorization:`Bearer ${u}`}});if(A.status!==401&&A.status!==402)return A;p("Cached pass rejected (status",A.status,"), purchasing new pass");try{R.delete(new URL(w).host)}catch{}}}let S=await _(g,b);if(S.status!==402)return S;p("Received 402 Payment Required");let T=S.headers.get("X-ACCESS-PASS-TIERS");if(l&&T){p("Server offers access passes, purchasing...");try{let u=JSON.parse(atob(T)),A=await W(g,b,S,u,w);if(A)return A}catch(u){p("Access pass purchase failed, falling back to per-request payment:",u)}}let P=S.headers.get("PAYMENT-REQUIRED");if(!P)throw new k("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let v;try{let u=atob(P);v=JSON.parse(u)}catch{throw new k("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}p("Payment requirements:",v);let V=S.headers.get("X-Quote-Hash");V&&p("Quote hash received:",V);let $=U(v.accepts);if(!$){let u=v.accepts.map(A=>A.network).join(", ");throw new k("no_matching_payment_option",`No connected wallet for any available network: ${u}`)}let{accept:O,adapter:C,wallet:q}=$;if(p(`Using ${C.name} for ${O.network}`),C.name==="Solana"&&!O.extra?.feePayer)throw new k("missing_fee_payer","Solana payment option missing feePayer in extra");let ye=O.extra?.decimals??(gt(O.asset)?6:void 0);if(typeof ye!="number")throw new k("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let J=O.amount??O.maxAmountRequired;if(!J)throw new k("missing_amount","Payment option missing amount");if(o&&BigInt(J)>BigInt(o))throw new k("amount_exceeds_max",`Payment amount ${J} exceeds maximum ${o}`);let ke=j(O.network,C);p("Checking balance...");try{let u=await C.getBalance(O,q,ke),A=Number(J)/Math.pow(10,ye);if(u<A){let ut=M(O.network,C.name);throw new k("insufficient_balance",`Insufficient balance on ${ut}. Have $${u.toFixed(4)}, need $${A.toFixed(4)}`)}p(`Balance OK: $${u.toFixed(4)} >= $${A.toFixed(4)}`)}catch(u){if(u instanceof k)throw u;p("Balance check failed (RPC error), proceeding with transaction attempt")}if(m&&!await m(O))throw new k("payment_rejected","Payment rejected by onPaymentRequired callback");p("Building transaction...");let X=await C.buildTransaction(O,q,ke);p("Transaction signed");let Y;C.name==="EVM"?Y=JSON.parse(X.serialized):Y={transaction:X.serialized};let he=g,se=v.resource;if(typeof v.resource=="string")try{let u=new URL(v.resource,he).toString();u!==v.resource&&p("Resolved relative resource URL:",v.resource,"\u2192",u),se=u}catch{se=v.resource}else if(v.resource&&typeof v.resource=="object"&&"url"in v.resource){let u=v.resource;try{let A=new URL(u.url,he).toString();A!==u.url&&(p("Resolved relative resource URL:",u.url,"\u2192",A),se={...u,url:A})}catch{}}let Se={x402Version:O.x402Version??2,resource:se,accepted:O,payload:Y};X.extensions&&(Se.extensions=X.extensions);let Xe=btoa(JSON.stringify(Se));if(f)try{f(O,X.settlementProbe)}catch{}p("Retrying request with payment...");let z=await _(g,{...b,headers:{...b?.headers||{},"PAYMENT-SIGNATURE":Xe,...V?{"X-Quote-Hash":V}:{}}});if(p("Retry response status:",z.status),z.status===402){let u="unknown";try{let A=await z.clone().json();u=String(A.error||A.message||JSON.stringify(A)),p("Rejection reason:",u)}catch{}throw new k("payment_rejected",`Payment was rejected by the server: ${u}`)}let ae=z.headers.get("PAYMENT-RESPONSE"),K;if(ae)try{K=JSON.parse(atob(ae))}catch{}return K??={},K.amountAtomic=J,K.assetDecimals=ye,pn.set(z,K),K.extensions&&p("Settlement extensions:",Object.keys(K.extensions).join(", ")),z}async function L(g,b){let[w,S]=await un(g,b);return re(w,S)}return{fetch:L}}function H(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 Je(n){let e="";try{e=(await n.clone().text()).slice(0,600)}catch{}let t=e.toLowerCase(),r=t.includes("settle")||t.includes("facilitator"),s=e;try{let a=JSON.parse(e),o=[a.error,a.detail,a.message].filter(i=>typeof i=="string"&&i.length>0);o.length>0&&(s=o.join(" \u2014 "))}catch{}return s||(s=`HTTP ${n.status}`),{reason:r?"settlement_failed":"merchant_rejected",detail:`merchant HTTP ${n.status}: ${s}`}}var it="Payment authorization was sent, but the merchant did not respond within the timeout. ",ct=" Do not retry without checking \u2014 inspect the funding wallet for a transfer to the merchant before attempting payment again.";async function lt(n,e,t){if(!n)return{confirmed:!1,detail:it+"This payment scheme has no on-chain confirmation check, so the SDK cannot verify whether it settled."+ct};try{if(n.kind==="solana"){let o=ne(),i=t??o.getDefaultRpcUrl(e.caip2);if(!o.confirmSettlement)return Ut();let c=await o.confirmSettlement(n,i);return c.settled?{confirmed:!0,txSignature:c.txSignature}:Ot()}let r=Ce(),s=r.getDefaultRpcUrl(e.caip2);if(!r.confirmSettlement)return Ut();let a=await r.confirmSettlement(n,s);return a.settled?{confirmed:!0,txSignature:a.txSignature}:Ot()}catch(r){return{confirmed:!1,detail:it+`On-chain confirmation could not be completed (${H(r)}).`+ct}}}function Ot(){return{confirmed:!1,detail:it+"On-chain confirmation found no matching settlement yet \u2014 the payment may still be pending, or may not have settled."+ct}}function Ut(){return{confirmed:!1,detail:it+"The chain adapter does not support on-chain confirmation."+ct}}var mn=new Set(["exact","exact-approval"]);async function dn(n,e,t,r){let s;try{s=await r.signNextVoucher(t.amount)}catch{return null}let a=new Headers(e.headers??void 0);a.set("X-Tab-Voucher",Ie(s));let o={method:e.method??"GET",headers:a};e.signal&&(o.signal=e.signal),typeof e.body=="string"&&(o.body=e.body);let i;try{i=await fetch(n,o)}catch(c){return{ok:!1,reason:"error",detail:c?.message??String(c)}}return i.status===402?(r.rollbackVoucher?.call(r,s),null):i.ok?{ok:!0,paid:!0,response:i,amountPaid:t.amount,network:t.network}:{ok:!1,...await Je(i)}}var Bt={version:2,async parseChallenge(n){return Qe(n)},async pay(n,e,t,r,s){if(s.tab){let h=t.options.find(y=>y.scheme==="tab"&&y.network.family==="svm"&&y.payTo===s.tab.counterparty);if(h){let y=await dn(n,e,h,s.tab);if(y)return y}}let a=t.options.filter(h=>mn.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 o=a.find(h=>h.network.family==="evm"?!!r.evm:h.network.family==="svm"?!!r.solana:!1);if(!o)return{ok:!1,reason:"unsupported_network"};let i=s.timeoutMs??15e3,c=s.responseTimeoutMs??12e4,l=new AbortController,m=setTimeout(()=>l.abort(),i),f=!1,d,E=(h,y)=>{f=!0,d=y,clearTimeout(m),m=setTimeout(()=>l.abort(),c)},p=Nt({wallets:r,preferredNetwork:o.network.caip2,maxAmountAtomic:s.maxAmountAtomic,fetch:globalThis.fetch,onPaymentDispatched:E}),_=e.signal?AbortSignal.any([e.signal,l.signal]):l.signal,R={method:e.method??"GET",headers:e.headers,signal:_};typeof e.body=="string"&&(R.body=e.body);try{let h=await p.fetch(n,R);if(clearTimeout(m),!h.ok)return{ok:!1,...await Je(h)};let y,x=h.headers.get("PAYMENT-RESPONSE");if(x)try{let U=dt(x);U&&typeof U.transaction=="string"&&(y=U.transaction)}catch{}return{ok:!0,paid:!0,response:h,amountPaid:o.amount,network:o.network,txSignature:y}}catch(h){clearTimeout(m);let y=h;if(y?.name==="AbortError"){if(!f)return{ok:!1,reason:"timeout"};let x=await lt(d,o.network,s.solanaRpcUrl);return x.confirmed?{ok:!0,paid:!0,response:void 0,amountPaid:o.amount,network:o.network,txSignature:x.txSignature}:{ok:!1,reason:"payment_unconfirmed",detail:x.detail}}return{ok:!1,reason:"error",detail:y?.message??String(h)}}}};var Dt=require("viem");var fn={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 gn(){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 yn(n,e,t){if(typeof n.signTypedData!="function")throw new Error("EVM wallet does not support signTypedData");let r=Math.floor(Date.now()/1e3),s=String(r-600),a=String(r+(e.maxTimeoutSeconds??60)),o={from:n.address,to:e.payTo,value:e.amount,validAfter:s,validBefore:a,nonce:await gn()},i=je[e.network.caip2];if(i===void 0)throw new Error(`unknown chain id for network ${e.network.caip2}`);let c=e.extra,l=await n.signTypedData({domain:{name:c.name,version:c.version,chainId:i,verifyingContract:(0,Dt.getAddress)(e.asset)},types:fn,primaryType:"TransferWithAuthorization",message:o});return{payment:{x402Version:1,scheme:e.scheme,network:t,payload:{signature:l,authorization:o}},settlementProbe:{kind:"eip3009",from:o.from,nonce:o.nonce,asset:e.asset,chainId:i}}}async function yt(n,e,t){try{let r;for(let s of n.options){let a=s.network.family==="evm"&&!!e.evm||s.network.family==="svm"&&!!e.solana;if(s.scheme!=="exact"){a&&(r=s.scheme);continue}if(s.network.family==="evm"&&e.evm){let o=await e.evm;return await hn(s,o,t)}if(s.network.family==="svm"&&e.solana){let o=await e.solana;return await Sn(s,o,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:H(r)}}}async function hn(n,e,t){if(t.maxAmountAtomic!==void 0&&BigInt(n.amount)>BigInt(t.maxAmountAtomic))return{ok:!1,reason:"budget_exceeded"};let r=n.extra??{},s=r.name,a=r.version;if(typeof s!="string"||s.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 o=n.network.bare,{payment:i,settlementProbe:c}=await yn(e,n,o);return{ok:!0,headerValue:Buffer.from(JSON.stringify(i),"utf8").toString("base64"),option:n,settlementProbe:c}}async function Sn(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 s=n.network.bare,a={x402Version:1,scheme:n.scheme,network:s,asset:n.asset,payTo:n.payTo,amount:n.amount,maxAmountRequired:n.amount,maxTimeoutSeconds:n.maxTimeoutSeconds??60,extra:r},i=await ne().buildTransaction(a,e,t.solanaRpcUrl),c={x402Version:1,scheme:n.scheme,network:s,payload:{transaction:i.serialized}};return{ok:!0,headerValue:Buffer.from(JSON.stringify(c),"utf8").toString("base64"),option:n,settlementProbe:i.settlementProbe}}function An(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,s=Ne(String(r.network??""));s&&e.push({scheme:String(r.scheme??"exact"),network:s,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 Mt={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,s){let a,o=new AbortController,i=!1,c,l;try{let m=s.timeoutMs??15e3;a=setTimeout(()=>o.abort(),m);let f=await yt(t,r,s);if(!f.ok)return{ok:!1,reason:f.reason,detail:f.detail};let d=f.headerValue,E=f.option;l=E,c=f.settlementProbe;let p=new Headers(e.headers??void 0);p.set("X-PAYMENT",d);let _=e.signal!=null?AbortSignal.any([e.signal,o.signal]):o.signal,R={method:e.method,headers:p,signal:_};typeof e.body=="string"&&(R.body=e.body),i=!0,clearTimeout(a);let h=s.responseTimeoutMs??12e4;a=setTimeout(()=>o.abort(),h);let y=await fetch(n,R);return y.ok?{ok:!0,paid:!0,response:y,amountPaid:E.amount,network:E.network,txSignature:bn(y)}:{ok:!1,...await Je(y)}}catch(m){if(m instanceof Error&&m.name==="AbortError"){if(!i)return{ok:!1,reason:"timeout"};let f=await lt(c,l.network,s.solanaRpcUrl);return f.confirmed?{ok:!0,paid:!0,response:void 0,amountPaid:l.amount,network:l.network,txSignature:f.txSignature}:{ok:!1,reason:"payment_unconfirmed",detail:f.detail}}return{ok:!1,reason:"error",detail:H(m)}}finally{a!==void 0&&clearTimeout(a)}}};function bn(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}}var Lt=G(require("tweetnacl"),1);var ht=require("@solana/web3.js"),$t=Symbol.for("x402:keypair");function St(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[$t];if(r&&r.secretKey&&r.publicKey)return{publicKey:r.publicKey,signMessage:async s=>Lt.sign.detached(s,r.secretKey)}}return null}var wn=[Bt,Mt];async function Tn(n){let e=St(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. ${H(t)}`),fetch}}async function At(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 s;try{s=await(await Tn(t))(n,{...e})}catch(a){return{ok:!1,reason:"error",detail:H(a)}}if(s.status!==402)return{ok:!0,paid:!1,response:s};for(let a of wn){let o=await a.parseChallenge(s.clone());if(o)return a.pay(n,e,o,t,r)}return{ok:!1,reason:"no_payment_options"}}async function Vt(n,e={},t){let r=await Ae(n,e);if(r.kind==="free")return{result:{ok:!0,paid:!1,response:r.response},tab:null};if(r.kind==="no_tab")return{result:{ok:!1,reason:"no_payment_options",detail:`no tab option offered (schemes: ${r.schemesOffered.join(", ")})`},tab:null};if(r.kind==="error")return{result:{ok:!1,reason:"error",detail:r.detail},tab:null};let{offer:s}=r,a=BigInt(Z(t.perUnitCap));if(BigInt(s.amountAtomic)>a)return{result:{ok:!1,reason:"budget_exceeded",detail:`seller quotes ${s.amountAtomic} atomic; perUnitCap allows ${a}`},tab:null};let o=t.tabs?.get(s.payTo);return(!o||!o.state.isOpen)&&(o=await Ge({vault:t.vault,network:"solana:mainnet",seller:s.payTo,perUnitCap:t.perUnitCap,totalCap:t.totalCap,sessionDuration:t.sessionDuration,facilitatorUrl:t.facilitatorUrl}),t.tabs?.set(s.payTo,o)),{result:await At(n,e,{},{tab:o}),tab:o}}var ge=require("@dexterai/vault/instructions"),bt=require("@dexterai/vault/precompile"),F=require("@dexterai/vault/constants");function xn(n){return{counterparty:n.payTo,perRequest:{atomic:n.amountAtomic,human:ce(n.amountAtomic)},asset:n.asset,network:{caip2:n.networkCaip2},scheme:"tab",settlement:{custody:"non-custodial",protection:"freeze",settleOn:"close"},credit:null,...n.resourceUrl!==void 0?{resourceUrl:n.resourceUrl}:{}}}async function Kt(n,e={},t={}){let r=t.cache?.get(n);if(r)return{kind:"terms",terms:r};let s=await Ae(n,e,t.fetchImpl??fetch);if(s.kind!=="offer")return s;if(s.offer.asset!==He)return{kind:"error",detail:`tab offer asset is not USDC ("${s.offer.asset}"); refusing to render a human price`};let a=xn(s.offer);return t.cache?.set(n,a),{kind:"terms",terms:a}}0&&(module.exports={DEFAULT_FACILITATOR_URL,DEXTER_VAULT_PROGRAM_ID,INSTRUCTIONS_SYSVAR_ID,SECP256R1_PROGRAM_ID,SessionScopeExceededError,TabClosedError,UnsupportedNetworkError,atomicToHuman,buildRegisterSessionKeyInstruction,buildRevokeSessionKeyInstruction,buildSecp256r1VerifyInstruction,buildVoucherMessage,humanToAtomic,openTab,payUrlWithTab,resolveTabOffer,resolveTabTerms,resumeTab,sessionRegisterMessage,sessionRevokeMessage,voucherPayloadMessage,voucherToHeader});
|
|
6
|
+
`):null}}var vt=require("@solana/web3.js");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"}],nn=new Map(Pt.map(n=>[n.caip2.toLowerCase(),n])),rn=new Map(Pt.map(n=>[n.bare.toLowerCase(),n]));function Ne(n){if(!n)return null;let e=n.toLowerCase(),t=nn.get(e)||rn.get(e);return t?{caip2:t.caip2,bare:t.bare,family:t.family}:null}function dt(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 sn(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,s=Ne(String(r.network??""));s&&e.push({scheme:String(r.scheme??"exact"),network:s,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 Qe(n){let e=n.headers.get("payment-required");if(!e)return null;let t;try{t=dt(e)}catch{return null}let r=Array.isArray(t.accepts)?t.accepts:[];return r.length===0?null:{x402Version:2,options:sn(r),resourceUrl:t.resource&&typeof t.resource=="object"?String(t.resource.url??""):void 0}}async function Ae(n,e={},t=fetch){let r={method:e.method??"GET",headers:e.headers};typeof e.body=="string"&&(r.body=e.body);let s;try{s=await t(n,r)}catch(i){return{kind:"error",detail:`probe failed: ${i?.message??String(i)}`}}if(s.status!==402)return s.ok?{kind:"free",response:s}:{kind:"error",detail:`probe returned HTTP ${s.status}`};let a=await Qe(s);if(!a)return{kind:"error",detail:"the 402 carries no x402 v2 PAYMENT-REQUIRED challenge"};let o=a.options.find(i=>i.scheme==="tab"&&i.network.family==="svm");if(!o)return{kind:"no_tab",schemesOffered:a.options.map(i=>i.scheme)};try{new vt.PublicKey(o.payTo)}catch{return{kind:"error",detail:`tab option payTo is not a valid Solana pubkey: "${o.payTo}"`}}return{kind:"offer",offer:{payTo:o.payTo,amountAtomic:o.amount,asset:o.asset,networkCaip2:o.network.caip2,resourceUrl:a.resourceUrl}}}var Oe="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Ze="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",et="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",le=Oe,Ue=Ze,Be=et,ue="eip155:8453",be="eip155:84532",we="eip155:42161",Te="eip155:137",xe="eip155:10",Ee="eip155:43114",Re="eip155:56",Pe="eip155:1187947933",ve="eip155:324705682",_e="eip155:1",pe=ue,tt=be,De=we,Me=Te,$e=xe,Le=Ee,Ve=Re,Ke=Pe,We=ve,qe=_e,He="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",_t="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",kt="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",ft="0x55d398326f99059fF775485246999027B3197955",nt="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",rt={[Re]:nt,[ue]:kt,[be]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[we]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[Te]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[xe]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[Ee]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[Pe]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[ve]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[_e]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},st={[ft]:{symbol:"USDT",decimals:18},[nt]:{symbol:"USDC",decimals:18}};var te="0x000000000022D473030F116dDEE9F6B43aC78BA3",Fe="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",je={[Re]:56,[ue]:8453,[be]:84532,[we]:42161,[Te]:137,[xe]:10,[Ee]:43114,[Pe]:1187947933,[ve]:324705682,[_e]:1},me={[Oe]:"https://api.dexter.cash/api/solana/rpc",[Ze]:"https://api.devnet.solana.com",[et]:"https://api.testnet.solana.com"},D={[Re]:"https://api.dexter.cash/api/evm/bsc/rpc",[ue]:"https://api.dexter.cash/api/base/rpc",[be]:"https://sepolia.base.org",[we]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[Te]:"https://api.dexter.cash/api/evm/polygon/rpc",[xe]:"https://api.dexter.cash/api/evm/optimism/rpc",[Ee]:"https://api.dexter.cash/api/evm/avalanche/rpc",[Pe]:"https://skale-base.skalenodes.com/v1/base",[ve]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[_e]:"https://eth.llamarpc.com"};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)}};var I=require("@solana/web3.js"),N=require("@solana/spl-token");var an=12e3,on=1;function de(n){if(!n||typeof n!="object")return!1;let e=n;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var at=class{name="Solana";networks=[le,Ue,Be];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]:me[e]?me[e]:e==="solana"?me[le]:e==="solana-devnet"?me[Ue]:e==="solana-testnet"?me[Be]:me[le]}getAddress(e){return de(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return de(e)?e.publicKey!==null:!1}async getBalance(e,t,r){if(!de(t)||!t.publicKey)return 0;let s=r||this.getDefaultRpcUrl(e.network),a=new I.Connection(s,"confirmed"),o=new I.PublicKey(t.publicKey.toBase58()),i=new I.PublicKey(e.asset);try{let l=(await a.getAccountInfo(i,"confirmed"))?.owner.toBase58()===N.TOKEN_2022_PROGRAM_ID.toBase58()?N.TOKEN_2022_PROGRAM_ID:N.TOKEN_PROGRAM_ID,m=await(0,N.getAssociatedTokenAddress)(i,o,!1,l),f=await(0,N.getAccount)(a,m,void 0,l),d=e.extra?.decimals??6;return Number(f.amount)/Math.pow(10,d)}catch(c){if(c&&typeof c=="object"&&"name"in c&&(c.name==="TokenAccountNotFoundError"||c.name==="TokenInvalidAccountOwnerError"))return 0;throw c}}async buildTransaction(e,t,r){if(!de(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let s=r||this.getDefaultRpcUrl(e.network),a=new I.Connection(s,"confirmed"),o=new I.PublicKey(t.publicKey.toBase58()),{payTo:i,asset:c,extra:l}=e,m=e.amount??e.maxAmountRequired;if(!m)throw new Error("Missing amount in payment requirements");if(!l?.feePayer)throw new Error("Missing feePayer in payment requirements");let f=new I.PublicKey(l.feePayer),d=new I.PublicKey(c),E=new I.PublicKey(i);this.log("Building transaction:",{from:o.toBase58(),to:i,amount:m,asset:c,feePayer:l.feePayer});let p=[];p.push(I.ComputeBudgetProgram.setComputeUnitLimit({units:an})),p.push(I.ComputeBudgetProgram.setComputeUnitPrice({microLamports:on}));let _=await a.getAccountInfo(d,"confirmed");if(!_)throw new Error(`Token mint ${c} not found`);let R=_.owner.toBase58()===N.TOKEN_2022_PROGRAM_ID.toBase58()?N.TOKEN_2022_PROGRAM_ID:N.TOKEN_PROGRAM_ID,h=await(0,N.getMint)(a,d,void 0,R);typeof l?.decimals=="number"&&h.decimals!==l.decimals&&this.log(`Decimals mismatch: requirements say ${l.decimals}, mint says ${h.decimals}`);let y=await(0,N.getAssociatedTokenAddress)(d,o,!1,R),x=await(0,N.getAssociatedTokenAddress)(d,E,!0,R);if(!await a.getAccountInfo(y,"confirmed"))throw new Error(`No token account found for ${c}. Please ensure you have USDC in your wallet.`);if(!await a.getAccountInfo(x,"confirmed"))throw new Error(`Seller token account not found. The seller (${i}) must have a USDC account.`);let j=BigInt(m);p.push((0,N.createTransferCheckedInstruction)(y,d,x,o,j,h.decimals,[],R));let{blockhash:W}=await a.getLatestBlockhash("confirmed"),re=new I.TransactionMessage({payerKey:f,recentBlockhash:W,instructions:p}).compileToV0Message(),L=new I.VersionedTransaction(re),g=await t.signTransaction(L);return this.log("Transaction signed successfully"),{serialized:Buffer.from(g.serialize()).toString("base64"),settlementProbe:{kind:"solana",sourceAta:y.toBase58(),destinationAta:x.toBase58(),asset:c,amount:m,blockhash:W}}}async confirmSettlement(e,t){if(e.kind!=="solana")throw new Error(`SolanaAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`);let r=new I.Connection(t,"confirmed"),s=new I.PublicKey(e.destinationAta),a=await r.getSignaturesForAddress(s,{limit:25});if(a.length===0)return{settled:!1};let o=BigInt(e.amount);for(let i of a){if(i.err)continue;let c=await r.getTransaction(i.signature,{commitment:"confirmed",maxSupportedTransactionVersion:0});if(!c?.meta)continue;let l=c.transaction.message.getAccountKeys().keySegments().flat(),m=c.meta.preTokenBalances??[],f=c.meta.postTokenBalances??[];for(let d of f){if(d.mint!==e.asset)continue;let E=l[d.accountIndex];if(!E||!E.equals(s))continue;let p=m.find(h=>h.accountIndex===d.accountIndex),_=BigInt(p?.uiTokenAmount.amount??"0");if(BigInt(d.uiTokenAmount.amount??"0")-_===o)return{settled:!0,txSignature:i.signature}}}return{settled:!1}}};function ne(n){return new at(n)}var cn={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"}]},Ct=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function fe(n){if(!n||typeof n!="object")return!1;let e=n;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var ot=class{name="EVM";networks=[Ve,pe,tt,qe,De,Me,$e,Le,Ke,We];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]:D[e]?D[e]:e==="base"?D[pe]:e==="bsc"?D[Ve]:e==="ethereum"?D[qe]:e==="arbitrum"?D[De]:e==="polygon"?D[Me]:e==="optimism"?D[$e]:e==="avalanche"?D[Le]:e==="skale-base"?D[Ke]:e==="skale-base-sepolia"?D[We]:D[pe]}getAddress(e){return fe(e)?e.address:null}isConnected(e){return fe(e)?!!e.address:!1}getChainId(e){if(je[e])return je[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(!fe(t)||!t.address)return 0;let s=r||this.getDefaultRpcUrl(e.network);try{let a=this.encodeBalanceOf(t.address),o=await fetch(s,{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(!o.ok)throw new Error(`RPC request failed: ${o.status}`);let i=await o.json();if(i.error)throw new Error(`RPC error: ${JSON.stringify(i.error)}`);if(!i.result||i.result==="0x")return 0;let c=BigInt(i.result),l=e.extra?.decimals??6;return Number(c)/Math.pow(10,l)}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",s=e.from.slice(2).toLowerCase().padStart(64,"0"),a=e.nonce.slice(2).toLowerCase().padStart(64,"0"),o=r+s+a,i=await this.ethCall(t,e.asset,o);return{settled:BigInt(i)!==0n}}if(e.kind==="permit2"){let r="0x4fe02b44",s=BigInt(e.nonce),a=s>>8n,o=s&0xffn,i=e.from.slice(2).toLowerCase().padStart(64,"0"),c=a.toString(16).padStart(64,"0"),l=r+i+c,m=await this.ethCall(t,te,l);return{settled:(BigInt(m)>>o&1n)===1n}}throw new Error(`EvmAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`)}async ethCall(e,t,r){let s=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(!s.ok)throw new Error(`RPC request failed: ${s.status}`);let a=await s.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(!fe(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:s,asset:a,extra:o}=e,i=e.amount??e.maxAmountRequired;if(!i)throw new Error("Missing amount in payment requirements");this.log("Building EVM transaction:",{from:t.address,to:s,amount:i,asset:a,network:e.network});let c=this.getChainId(e.network),l={name:o?.name??"USD Coin",version:o?.version??"2",chainId:BigInt(c),verifyingContract:a},m={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 d="0x"+[...f].map(y=>y.toString(16).padStart(2,"0")).join(""),E=Math.floor(Date.now()/1e3),p={from:t.address,to:s,value:i,validAfter:String(E-600),validBefore:String(E+(e.maxTimeoutSeconds||60)),nonce:d},_={from:t.address,to:s,value:BigInt(i),validAfter:BigInt(E-600),validBefore:BigInt(E+(e.maxTimeoutSeconds||60)),nonce:d};if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let R=await t.signTypedData({domain:l,types:m,primaryType:"TransferWithAuthorization",message:_});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:p,signature:R}),signature:R,settlementProbe:{kind:"eip3009",from:t.address,nonce:d,asset:a,chainId:c}}}async buildApprovalTransaction(e,t,r){let{payTo:s,asset:a,extra:o}=e,i=e.amount??e.maxAmountRequired;if(!i)throw new Error("Missing amount in payment requirements");let c=o?.facilitatorContract;if(!c)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:s,amount:i,asset:a,network:e.network,facilitatorContract:c});let l=r||this.getDefaultRpcUrl(e.network),m=o?.fee??"0",f=BigInt(i)+BigInt(m),d=await this.readAllowance(l,a,t.address,c);if(d<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 L=this.calculateApprovalAmount(i,m,o?.approvalStrategy);this.log(`Approving ${L} for ${c} (current allowance: ${d})`);let g=await t.sendTransaction({to:a,data:this.encodeApprove(c,L),value:0n});this.log(`Approval tx sent: ${g}`),await this.waitForReceipt(l,g),this.log("Approval confirmed")}else this.log("Sufficient allowance, skipping approval");let E=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(E);let p=[...E].reduce((L,g)=>L*256n+BigInt(g),0n).toString(),_=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(_);let R="0x"+[..._].map(L=>L.toString(16).padStart(2,"0")).join(""),y=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),x=o?.eip712Domain,U=x?{name:x.name,version:x.version,chainId:BigInt(x.chainId),verifyingContract:x.verifyingContract}:{name:"DexterBSCFacilitator",version:"1",chainId:BigInt(this.getChainId(e.network)),verifyingContract:c},M=o?.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"}]},j={from:t.address,to:s,token:a,amount:BigInt(i),fee:BigInt(m),nonce:BigInt(p),deadline:BigInt(y),paymentId:R},W=await t.signTypedData({domain:U,types:M,primaryType:"Payment",message:j});this.log("EIP-712 Payment signature obtained");let re={from:t.address,to:s,token:a,amount:i,fee:m,nonce:p,deadline:y,paymentId:R,signature:W};return{serialized:JSON.stringify(re),signature:W}}async buildPermit2Transaction(e,t,r){let{payTo:s,asset:a}=e,o=e.amount??e.maxAmountRequired;if(!o)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:s,amount:o,asset:a,network:e.network});let i=r||this.getDefaultRpcUrl(e.network),c=await this.readAllowance(i,a,t.address,te),l;if(c<BigInt(o)){let U=this.encodeApprove(te,Ct);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${c})`);let M=this.getChainId(e.network),j=await this.readGasPrice(i),W=await this.readNonce(i,t.address),re=await t.signTransaction({to:a,data:U,chainId:M,gas:50000n,gasPrice:j,nonce:W});l={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:a,spender:te,amount:Ct.toString(),signedTransaction:re,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${c})`);let M=await t.sendTransaction({to:a,data:U,value:0n});this.log(`Permit2 approval tx sent: ${M}`),await this.waitForReceipt(i,M),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 m=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(m);let f=[...m].reduce((U,M)=>U*256n+BigInt(M),0n),d=Math.floor(Date.now()/1e3),E=d-600,p=d+(e.maxTimeoutSeconds||300),_=this.getChainId(e.network),R={name:"Permit2",chainId:BigInt(_),verifyingContract:te},h={permitted:{token:a,amount:BigInt(o)},spender:Fe,nonce:f,deadline:BigInt(p),witness:{to:s,validAfter:BigInt(E)}},y=await t.signTypedData({domain:R,types:cn,primaryType:"PermitWitnessTransferFrom",message:h});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let x={signature:y,permit2Authorization:{from:t.address,permitted:{token:a,amount:o},spender:Fe,nonce:f.toString(),deadline:String(p),witness:{to:s,validAfter:String(E)}}};return{serialized:JSON.stringify(x),signature:y,extensions:l,settlementProbe:{kind:"permit2",from:t.address,nonce:f.toString(),chainId:_}}}async readAllowance(e,t,r,s){let a="0xdd62ed3e",o=r.slice(2).toLowerCase().padStart(64,"0"),i=s.slice(2).toLowerCase().padStart(64,"0"),c=a+o+i;try{let m=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:c},"latest"]})})).json();return m.error||!m.result||m.result==="0x"?0n:BigInt(m.result)}catch{return 0n}}encodeApprove(e,t){let r="0x095ea7b3",s=e.slice(2).toLowerCase().padStart(64,"0"),a=t.toString(16).padStart(64,"0");return r+s+a}async waitForReceipt(e,t,r=3e4){let s=Date.now();for(;Date.now()-s<r;){try{let o=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(o.result){if(o.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 s=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 s.result?parseInt(s.result,16):0}catch{return 0}}calculateApprovalAmount(e,t,r){let s=BigInt(e)+BigInt(t);if(!r||r.mode==="exact")return s;let a=BigInt(r.defaultMultiple??10),o=s*a;if(r.maxCapUsd){let i=this.inferDecimals(e),c=BigInt(Math.floor(r.maxCapUsd*Math.pow(10,i)));if(o>c)return c}if(r.exactAboveUsd){let i=this.inferDecimals(e),c=BigInt(Math.floor(r.exactAboveUsd*Math.pow(10,i)));if(BigInt(e)>c)return s}return o}inferDecimals(e){return e.length>12?18:6}};function ke(n){return new ot(n)}function gt(n){if(n===He||n===_t)return!0;let e=n.toLowerCase();for(let t of Object.values(rt))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(st))if(t.toLowerCase()===e)return!0;return!1}function ln(n){return{[Oe]:"Solana",[Ze]:"Solana Devnet",[et]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[ue]:"Base",[be]:"Base Sepolia",[_e]:"Ethereum",[we]:"Arbitrum",[Te]:"Polygon",[xe]:"Optimism",[Ee]:"Avalanche",[Re]:"BSC",[Pe]:"SKALE Base",[ve]:"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 It(n,e){let t=ln(n);return t===n?e:t}async function un(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((o,i)=>r.set(i,o));let s={method:e?.method??t.method,headers:r,signal:e?.signal??t.signal,redirect:e?.redirect??t.redirect,credentials:e?.credentials??t.credentials},a=(s.method??"GET").toUpperCase();return e&&"body"in e?s.body=e.body:a!=="GET"&&a!=="HEAD"&&t.body&&(s.body=await t.arrayBuffer()),[t.url,s]}var pn=new WeakMap;function Nt(n){let{adapters:e=[ne({verbose:n.verbose}),ke({verbose:n.verbose})],wallets:t,wallet:r,preferredNetwork:s,rpcUrls:a={},maxAmountAtomic:o,fetch:i=globalThis.fetch,verbose:c=!1,accessPass:l,onPaymentRequired:m,onPaymentDispatched:f,maxRetries:d=0,retryDelayMs:E=500}=n,p=c?console.log.bind(console,"[x402]"):()=>{};async function _(g,b){let w;for(let S=0;S<=d;S++)try{let T=await i(g,b);if(T.status>=502&&T.status<=504&&S<d){p(`Retry ${S+1}/${d}: server returned ${T.status}`),await new Promise(P=>setTimeout(P,E*Math.pow(2,S)));continue}return T}catch(T){w=T,S<d&&(p(`Retry ${S+1}/${d}: ${T instanceof Error?T.message:"network error"}`),await new Promise(P=>setTimeout(P,E*Math.pow(2,S))))}throw w}let R=new Map;function h(g){try{let b=new URL(g).host,w=R.get(b);if(w&&w.expiresAt>Date.now()/1e3+10)return w.jwt;w&&R.delete(b)}catch{}return null}function y(g,b){try{let w=new URL(g).host,S=b.split(".");if(S.length===3){let T=JSON.parse(atob(S[1].replace(/-/g,"+").replace(/_/g,"/"))),P=Math.floor(Date.now()/1e3),v=P+86400,V=Math.min(typeof T.exp=="number"?T.exp:P,v);R.set(w,{jwt:b,expiresAt:V}),p("Access pass cached for",w,"| expires:",new Date(V*1e3).toISOString())}}catch{p("Failed to cache access pass")}}let x=t||{};r&&!x.solana&&de(r)&&(x.solana=r),r&&!x.evm&&fe(r)&&(x.evm=r);function U(g){let b=[];for(let w of g){let S=w.scheme??"exact";if(S!=="exact"&&S!=="exact-approval")continue;let T=e.find(v=>v.canHandle(w.network));if(!T)continue;let P;T.name==="Solana"?P=x.solana:T.name==="EVM"&&(P=x.evm),P&&T.isConnected(P)&&b.push({accept:w,adapter:T,wallet:P})}if(b.length===0)return null;if(s){let w=b.find(S=>S.accept.network===s);if(w)return w}return b[0]}function M(g,b){return It(g,b)}function j(g,b){return a[g]||b.getDefaultRpcUrl(g)}async function W(g,b,w,S,T){let P="";if(l?.preferTier&&S.tiers){let u=S.tiers.find(A=>A.id===l.preferTier);if(u){if(l.maxSpend&&parseFloat(u.price)>parseFloat(l.maxSpend))throw new C("access_pass_exceeds_max_spend",`Access pass tier "${u.id}" costs $${u.price}, exceeds max spend $${l.maxSpend}`);P=`tier=${u.id}`}}else if(l?.preferDuration&&S.ratePerHour)P=`duration=${l.preferDuration}`;else if(S.tiers&&S.tiers.length>0){let u=S.tiers[0];if(l?.maxSpend&&parseFloat(u.price)>parseFloat(l.maxSpend))throw new C("access_pass_exceeds_max_spend",`Cheapest access pass costs $${u.price}, exceeds max spend $${l?.maxSpend}`);P=`tier=${u.id}`}let v=P?T.includes("?")?`${T}&${P}`:`${T}?${P}`:T;p("Purchasing access pass:",P||"default tier");let V=w.headers.get("PAYMENT-REQUIRED");if(!V)return null;let $;try{$=JSON.parse(atob(V))}catch{return null}let O=U($.accepts);if(!O)return null;let{accept:k,adapter:q,wallet:ye}=O;if(q.name==="Solana"&&!k.extra?.feePayer)return null;let J=k.extra?.decimals??(gt(k.asset)?6:void 0);if(typeof J!="number")return null;let Ce=k.amount??k.maxAmountRequired;if(!Ce)return null;let X=j(k.network,q);try{let u=await q.getBalance(k,ye,X),A=Number(Ce)/Math.pow(10,J);if(u<A){let ut=M(k.network,q.name);throw new C("insufficient_balance",`Insufficient balance for access pass on ${ut}. Have $${u.toFixed(4)}, need $${A.toFixed(4)}`)}}catch(u){if(u instanceof C)throw u}let Y=await q.buildTransaction(k,ye,X),he;q.name==="EVM"?he=JSON.parse(Y.serialized):he={transaction:Y.serialized};let se=typeof g=="string"?g:g instanceof URL?g.href:g.url,Se=$.resource;if(typeof $.resource=="string")try{let u=new URL($.resource,se);["http:","https:"].includes(u.protocol)&&(Se=u.toString())}catch{}else if($.resource&&typeof $.resource=="object"&&"url"in $.resource){let u=$.resource;try{let A=new URL(u.url,se);["http:","https:"].includes(A.protocol)&&(Se={...u,url:A.toString()})}catch{}}let Xe={x402Version:k.x402Version??2,resource:Se,accepted:k,payload:he};Y.extensions&&(Xe.extensions=Y.extensions);let z=btoa(JSON.stringify(Xe)),ae=await i(v,{...b,method:"POST",headers:{...b?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":z}});if(!ae.ok)return p("Pass purchase failed:",ae.status),null;let K=ae.headers.get("ACCESS-PASS");return K&&(y(T,K),p("Access pass purchased and cached")),ae}async function re(g,b){let w=g;if(p("Making request:",w),l){let u=h(w);if(u){p("Using cached access pass");let A=await i(g,{...b,headers:{...b?.headers||{},Authorization:`Bearer ${u}`}});if(A.status!==401&&A.status!==402)return A;p("Cached pass rejected (status",A.status,"), purchasing new pass");try{R.delete(new URL(w).host)}catch{}}}let S=await _(g,b);if(S.status!==402)return S;p("Received 402 Payment Required");let T=S.headers.get("X-ACCESS-PASS-TIERS");if(l&&T){p("Server offers access passes, purchasing...");try{let u=JSON.parse(atob(T)),A=await W(g,b,S,u,w);if(A)return A}catch(u){p("Access pass purchase failed, falling back to per-request payment:",u)}}let P=S.headers.get("PAYMENT-REQUIRED");if(!P)throw new C("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let v;try{let u=atob(P);v=JSON.parse(u)}catch{throw new C("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}p("Payment requirements:",v);let V=S.headers.get("X-Quote-Hash");V&&p("Quote hash received:",V);let $=U(v.accepts);if(!$){let u=v.accepts.map(A=>A.network).join(", ");throw new C("no_matching_payment_option",`No connected wallet for any available network: ${u}`)}let{accept:O,adapter:k,wallet:q}=$;if(p(`Using ${k.name} for ${O.network}`),k.name==="Solana"&&!O.extra?.feePayer)throw new C("missing_fee_payer","Solana payment option missing feePayer in extra");let ye=O.extra?.decimals??(gt(O.asset)?6:void 0);if(typeof ye!="number")throw new C("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let J=O.amount??O.maxAmountRequired;if(!J)throw new C("missing_amount","Payment option missing amount");if(o&&BigInt(J)>BigInt(o))throw new C("amount_exceeds_max",`Payment amount ${J} exceeds maximum ${o}`);let Ce=j(O.network,k);p("Checking balance...");try{let u=await k.getBalance(O,q,Ce),A=Number(J)/Math.pow(10,ye);if(u<A){let ut=M(O.network,k.name);throw new C("insufficient_balance",`Insufficient balance on ${ut}. Have $${u.toFixed(4)}, need $${A.toFixed(4)}`)}p(`Balance OK: $${u.toFixed(4)} >= $${A.toFixed(4)}`)}catch(u){if(u instanceof C)throw u;p("Balance check failed (RPC error), proceeding with transaction attempt")}if(m&&!await m(O))throw new C("payment_rejected","Payment rejected by onPaymentRequired callback");p("Building transaction...");let X=await k.buildTransaction(O,q,Ce);p("Transaction signed");let Y;k.name==="EVM"?Y=JSON.parse(X.serialized):Y={transaction:X.serialized};let he=g,se=v.resource;if(typeof v.resource=="string")try{let u=new URL(v.resource,he).toString();u!==v.resource&&p("Resolved relative resource URL:",v.resource,"\u2192",u),se=u}catch{se=v.resource}else if(v.resource&&typeof v.resource=="object"&&"url"in v.resource){let u=v.resource;try{let A=new URL(u.url,he).toString();A!==u.url&&(p("Resolved relative resource URL:",u.url,"\u2192",A),se={...u,url:A})}catch{}}let Se={x402Version:O.x402Version??2,resource:se,accepted:O,payload:Y};X.extensions&&(Se.extensions=X.extensions);let Xe=btoa(JSON.stringify(Se));if(f)try{f(O,X.settlementProbe)}catch{}p("Retrying request with payment...");let z=await _(g,{...b,headers:{...b?.headers||{},"PAYMENT-SIGNATURE":Xe,...V?{"X-Quote-Hash":V}:{}}});if(p("Retry response status:",z.status),z.status===402){let u="unknown";try{let A=await z.clone().json();u=String(A.error||A.message||JSON.stringify(A)),p("Rejection reason:",u)}catch{}throw new C("payment_rejected",`Payment was rejected by the server: ${u}`)}let ae=z.headers.get("PAYMENT-RESPONSE"),K;if(ae)try{K=JSON.parse(atob(ae))}catch{}return K??={},K.amountAtomic=J,K.assetDecimals=ye,pn.set(z,K),K.extensions&&p("Settlement extensions:",Object.keys(K.extensions).join(", ")),z}async function L(g,b){let[w,S]=await un(g,b);return re(w,S)}return{fetch:L}}function H(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 Je(n){let e="";try{e=(await n.clone().text()).slice(0,600)}catch{}let t=e.toLowerCase(),r=t.includes("settle")||t.includes("facilitator"),s=e;try{let a=JSON.parse(e),o=[a.error,a.detail,a.message].filter(i=>typeof i=="string"&&i.length>0);o.length>0&&(s=o.join(" \u2014 "))}catch{}return s||(s=`HTTP ${n.status}`),{reason:r?"settlement_failed":"merchant_rejected",detail:`merchant HTTP ${n.status}: ${s}`}}var it="Payment authorization was sent, but the merchant did not respond within the timeout. ",ct=" Do not retry without checking \u2014 inspect the funding wallet for a transfer to the merchant before attempting payment again.";async function lt(n,e,t){if(!n)return{confirmed:!1,detail:it+"This payment scheme has no on-chain confirmation check, so the SDK cannot verify whether it settled."+ct};try{if(n.kind==="solana"){let o=ne(),i=t??o.getDefaultRpcUrl(e.caip2);if(!o.confirmSettlement)return Ut();let c=await o.confirmSettlement(n,i);return c.settled?{confirmed:!0,txSignature:c.txSignature}:Ot()}let r=ke(),s=r.getDefaultRpcUrl(e.caip2);if(!r.confirmSettlement)return Ut();let a=await r.confirmSettlement(n,s);return a.settled?{confirmed:!0,txSignature:a.txSignature}:Ot()}catch(r){return{confirmed:!1,detail:it+`On-chain confirmation could not be completed (${H(r)}).`+ct}}}function Ot(){return{confirmed:!1,detail:it+"On-chain confirmation found no matching settlement yet \u2014 the payment may still be pending, or may not have settled."+ct}}function Ut(){return{confirmed:!1,detail:it+"The chain adapter does not support on-chain confirmation."+ct}}var mn=new Set(["exact","exact-approval"]);async function dn(n,e,t,r){let s;try{s=await r.signNextVoucher(t.amount)}catch{return null}let a=new Headers(e.headers??void 0);a.set("X-Tab-Voucher",Ie(s));let o={method:e.method??"GET",headers:a};e.signal&&(o.signal=e.signal),typeof e.body=="string"&&(o.body=e.body);let i;try{i=await fetch(n,o)}catch(c){return{ok:!1,reason:"error",detail:c?.message??String(c)}}return i.status===402?(r.rollbackVoucher?.call(r,s),null):i.ok?{ok:!0,paid:!0,response:i,amountPaid:t.amount,network:t.network}:{ok:!1,...await Je(i)}}var Bt={version:2,async parseChallenge(n){return Qe(n)},async pay(n,e,t,r,s){if(s.tab){let h=t.options.find(y=>y.scheme==="tab"&&y.network.family==="svm"&&y.payTo===s.tab.counterparty);if(h){let y=await dn(n,e,h,s.tab);if(y)return y}}let a=t.options.filter(h=>mn.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 o=a.find(h=>h.network.family==="evm"?!!r.evm:h.network.family==="svm"?!!r.solana:!1);if(!o)return{ok:!1,reason:"unsupported_network"};let i=s.timeoutMs??15e3,c=s.responseTimeoutMs??12e4,l=new AbortController,m=setTimeout(()=>l.abort(),i),f=!1,d,E=(h,y)=>{f=!0,d=y,clearTimeout(m),m=setTimeout(()=>l.abort(),c)},p=Nt({wallets:r,preferredNetwork:o.network.caip2,maxAmountAtomic:s.maxAmountAtomic,fetch:globalThis.fetch,onPaymentDispatched:E}),_=e.signal?AbortSignal.any([e.signal,l.signal]):l.signal,R={method:e.method??"GET",headers:e.headers,signal:_};typeof e.body=="string"&&(R.body=e.body);try{let h=await p.fetch(n,R);if(clearTimeout(m),!h.ok)return{ok:!1,...await Je(h)};let y,x=h.headers.get("PAYMENT-RESPONSE");if(x)try{let U=dt(x);U&&typeof U.transaction=="string"&&(y=U.transaction)}catch{}return{ok:!0,paid:!0,response:h,amountPaid:o.amount,network:o.network,txSignature:y}}catch(h){clearTimeout(m);let y=h;if(y?.name==="AbortError"){if(!f)return{ok:!1,reason:"timeout"};let x=await lt(d,o.network,s.solanaRpcUrl);return x.confirmed?{ok:!0,paid:!0,response:void 0,amountPaid:o.amount,network:o.network,txSignature:x.txSignature}:{ok:!1,reason:"payment_unconfirmed",detail:x.detail}}return{ok:!1,reason:"error",detail:y?.message??String(h)}}}};var Dt=require("viem");var fn={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 gn(){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 yn(n,e,t){if(typeof n.signTypedData!="function")throw new Error("EVM wallet does not support signTypedData");let r=Math.floor(Date.now()/1e3),s=String(r-600),a=String(r+(e.maxTimeoutSeconds??60)),o={from:n.address,to:e.payTo,value:e.amount,validAfter:s,validBefore:a,nonce:await gn()},i=je[e.network.caip2];if(i===void 0)throw new Error(`unknown chain id for network ${e.network.caip2}`);let c=e.extra,l=await n.signTypedData({domain:{name:c.name,version:c.version,chainId:i,verifyingContract:(0,Dt.getAddress)(e.asset)},types:fn,primaryType:"TransferWithAuthorization",message:o});return{payment:{x402Version:1,scheme:e.scheme,network:t,payload:{signature:l,authorization:o}},settlementProbe:{kind:"eip3009",from:o.from,nonce:o.nonce,asset:e.asset,chainId:i}}}async function yt(n,e,t){try{let r;for(let s of n.options){let a=s.network.family==="evm"&&!!e.evm||s.network.family==="svm"&&!!e.solana;if(s.scheme!=="exact"){a&&(r=s.scheme);continue}if(s.network.family==="evm"&&e.evm){let o=await e.evm;return await hn(s,o,t)}if(s.network.family==="svm"&&e.solana){let o=await e.solana;return await Sn(s,o,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:H(r)}}}async function hn(n,e,t){if(t.maxAmountAtomic!==void 0&&BigInt(n.amount)>BigInt(t.maxAmountAtomic))return{ok:!1,reason:"budget_exceeded"};let r=n.extra??{},s=r.name,a=r.version;if(typeof s!="string"||s.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 o=n.network.bare,{payment:i,settlementProbe:c}=await yn(e,n,o);return{ok:!0,headerValue:Buffer.from(JSON.stringify(i),"utf8").toString("base64"),option:n,settlementProbe:c}}async function Sn(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 s=n.network.bare,a={x402Version:1,scheme:n.scheme,network:s,asset:n.asset,payTo:n.payTo,amount:n.amount,maxAmountRequired:n.amount,maxTimeoutSeconds:n.maxTimeoutSeconds??60,extra:r},i=await ne().buildTransaction(a,e,t.solanaRpcUrl),c={x402Version:1,scheme:n.scheme,network:s,payload:{transaction:i.serialized}};return{ok:!0,headerValue:Buffer.from(JSON.stringify(c),"utf8").toString("base64"),option:n,settlementProbe:i.settlementProbe}}function An(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,s=Ne(String(r.network??""));s&&e.push({scheme:String(r.scheme??"exact"),network:s,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 Mt={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,s){let a,o=new AbortController,i=!1,c,l;try{let m=s.timeoutMs??15e3;a=setTimeout(()=>o.abort(),m);let f=await yt(t,r,s);if(!f.ok)return{ok:!1,reason:f.reason,detail:f.detail};let d=f.headerValue,E=f.option;l=E,c=f.settlementProbe;let p=new Headers(e.headers??void 0);p.set("X-PAYMENT",d);let _=e.signal!=null?AbortSignal.any([e.signal,o.signal]):o.signal,R={method:e.method,headers:p,signal:_};typeof e.body=="string"&&(R.body=e.body),i=!0,clearTimeout(a);let h=s.responseTimeoutMs??12e4;a=setTimeout(()=>o.abort(),h);let y=await fetch(n,R);return y.ok?{ok:!0,paid:!0,response:y,amountPaid:E.amount,network:E.network,txSignature:bn(y)}:{ok:!1,...await Je(y)}}catch(m){if(m instanceof Error&&m.name==="AbortError"){if(!i)return{ok:!1,reason:"timeout"};let f=await lt(c,l.network,s.solanaRpcUrl);return f.confirmed?{ok:!0,paid:!0,response:void 0,amountPaid:l.amount,network:l.network,txSignature:f.txSignature}:{ok:!1,reason:"payment_unconfirmed",detail:f.detail}}return{ok:!1,reason:"error",detail:H(m)}}finally{a!==void 0&&clearTimeout(a)}}};function bn(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}}var Lt=G(require("tweetnacl"),1);var ht=require("@solana/web3.js"),$t=Symbol.for("x402:keypair");function St(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[$t];if(r&&r.secretKey&&r.publicKey)return{publicKey:r.publicKey,signMessage:async s=>Lt.sign.detached(s,r.secretKey)}}return null}var wn=[Bt,Mt];async function Tn(n){let e=St(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. ${H(t)}`),fetch}}async function At(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 s;try{s=await(await Tn(t))(n,{...e})}catch(a){return{ok:!1,reason:"error",detail:H(a)}}if(s.status!==402)return{ok:!0,paid:!1,response:s};for(let a of wn){let o=await a.parseChallenge(s.clone());if(o)return a.pay(n,e,o,t,r)}return{ok:!1,reason:"no_payment_options"}}async function Vt(n,e={},t){let r=await Ae(n,e);if(r.kind==="free")return{result:{ok:!0,paid:!1,response:r.response},tab:null};if(r.kind==="no_tab")return{result:{ok:!1,reason:"no_payment_options",detail:`no tab option offered (schemes: ${r.schemesOffered.join(", ")})`},tab:null};if(r.kind==="error")return{result:{ok:!1,reason:"error",detail:r.detail},tab:null};let{offer:s}=r,a=BigInt(Z(t.perUnitCap));if(BigInt(s.amountAtomic)>a)return{result:{ok:!1,reason:"budget_exceeded",detail:`seller quotes ${s.amountAtomic} atomic; perUnitCap allows ${a}`},tab:null};let o=t.tabs?.get(s.payTo);return(!o||!o.state.isOpen)&&(o=await Ge({vault:t.vault,network:"solana:mainnet",seller:s.payTo,perUnitCap:t.perUnitCap,totalCap:t.totalCap,sessionDuration:t.sessionDuration,facilitatorUrl:t.facilitatorUrl}),t.tabs?.set(s.payTo,o)),{result:await At(n,e,{},{tab:o}),tab:o}}var ge=require("@dexterai/vault/instructions"),bt=require("@dexterai/vault/precompile"),F=require("@dexterai/vault/constants");function xn(n){return{counterparty:n.payTo,perRequest:{atomic:n.amountAtomic,human:ce(n.amountAtomic)},asset:n.asset,network:{caip2:n.networkCaip2},scheme:"tab",settlement:{custody:"non-custodial",protection:"lock",settleOn:"close"},credit:null,...n.resourceUrl!==void 0?{resourceUrl:n.resourceUrl}:{}}}async function Kt(n,e={},t={}){let r=t.cache?.get(n);if(r)return{kind:"terms",terms:r};let s=await Ae(n,e,t.fetchImpl??fetch);if(s.kind!=="offer")return s;if(s.offer.asset!==He)return{kind:"error",detail:`tab offer asset is not USDC ("${s.offer.asset}"); refusing to render a human price`};let a=xn(s.offer);return t.cache?.set(n,a),{kind:"terms",terms:a}}0&&(module.exports={DEFAULT_FACILITATOR_URL,DEXTER_VAULT_PROGRAM_ID,INSTRUCTIONS_SYSVAR_ID,SECP256R1_PROGRAM_ID,SessionScopeExceededError,TabClosedError,UnsupportedNetworkError,atomicToHuman,buildRegisterSessionKeyInstruction,buildRevokeSessionKeyInstruction,buildSecp256r1VerifyInstruction,buildVoucherMessage,humanToAtomic,openTab,payUrlWithTab,resolveTabOffer,resolveTabTerms,resumeTab,sessionRegisterMessage,sessionRevokeMessage,voucherPayloadMessage,voucherToHeader});
|
package/dist/tab/index.d.cts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { O as OpenTabOptions, T as Tab, R as ResumeTabOptions, V as VaultAdapter } from '../types-
|
|
2
|
-
export { S as SessionScopeExceededError, b as TabCloseResult, c as TabClosedError, a as TabState, U as UnsupportedNetworkError } from '../types-
|
|
1
|
+
import { O as OpenTabOptions, T as Tab, R as ResumeTabOptions, V as VaultAdapter } from '../types-DuoL3s8n.cjs';
|
|
2
|
+
export { S as SessionScopeExceededError, b as TabCloseResult, c as TabClosedError, a as TabState, U as UnsupportedNetworkError } from '../types-DuoL3s8n.cjs';
|
|
3
3
|
import { HumanAmount, AtomicAmount, SignedVoucher } from '@dexterai/vault/types';
|
|
4
4
|
export { AtomicAmount, HumanAmount, SessionKey, SessionScope, SignedVoucher, TabNetworkId, VoucherPayload } from '@dexterai/vault/types';
|
|
5
|
-
import { a as PayResult } from '../types-
|
|
5
|
+
import { a as PayResult } from '../types-DMzS_Rh2.cjs';
|
|
6
6
|
export { SessionRegisterMessageArgs, SessionRevokeMessageArgs, VoucherPayloadBytes, buildVoucherMessage, sessionRegisterMessage, sessionRevokeMessage, voucherPayloadMessage } from '@dexterai/vault/messages';
|
|
7
7
|
export { BuildRegisterSessionKeyArgs, BuildRevokeSessionKeyArgs, buildRegisterSessionKeyInstruction, buildRevokeSessionKeyInstruction } from '@dexterai/vault/instructions';
|
|
8
8
|
export { buildSecp256r1VerifyInstruction } from '@dexterai/vault/precompile';
|
|
@@ -25,7 +25,7 @@ import '../types-xQu1U4xk.cjs';
|
|
|
25
25
|
*/
|
|
26
26
|
|
|
27
27
|
/** Live Dexter x402 facilitator API. NOT facilitator.dexter.cash —
|
|
28
|
-
* that's a marketing redirect.
|
|
28
|
+
* that's a marketing redirect. */
|
|
29
29
|
declare const DEFAULT_FACILITATOR_URL = "https://x402.dexter.cash";
|
|
30
30
|
/**
|
|
31
31
|
* Convert a human decimal string ("0.001") to atomic-unit string ("1000")
|
|
@@ -137,13 +137,15 @@ interface TabTerms {
|
|
|
137
137
|
scheme: 'tab';
|
|
138
138
|
/**
|
|
139
139
|
* How a Dexter tab settles — properties of scheme 'tab' as shipped, not
|
|
140
|
-
* seller-configurable:
|
|
141
|
-
*
|
|
140
|
+
* seller-configurable: protection is 'lock' (the standard since Step-4) —
|
|
141
|
+
* accrued charges crystallize on-chain into a reservation the buyer cannot
|
|
142
|
+
* withdraw out from under, sized to the accrued amount only (not a
|
|
143
|
+
* whole-wallet freeze). Funds stay in the buyer's vault until settle
|
|
142
144
|
* (non-custodial), and settlement happens at tab close.
|
|
143
145
|
*/
|
|
144
146
|
settlement: {
|
|
145
147
|
custody: 'non-custodial';
|
|
146
|
-
protection: '
|
|
148
|
+
protection: 'lock';
|
|
147
149
|
settleOn: 'close';
|
|
148
150
|
};
|
|
149
151
|
/** Credit terms (Product 2). Reserved; always null today. */
|
package/dist/tab/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { O as OpenTabOptions, T as Tab, R as ResumeTabOptions, V as VaultAdapter } from '../types-
|
|
2
|
-
export { S as SessionScopeExceededError, b as TabCloseResult, c as TabClosedError, a as TabState, U as UnsupportedNetworkError } from '../types-
|
|
1
|
+
import { O as OpenTabOptions, T as Tab, R as ResumeTabOptions, V as VaultAdapter } from '../types-DuoL3s8n.js';
|
|
2
|
+
export { S as SessionScopeExceededError, b as TabCloseResult, c as TabClosedError, a as TabState, U as UnsupportedNetworkError } from '../types-DuoL3s8n.js';
|
|
3
3
|
import { HumanAmount, AtomicAmount, SignedVoucher } from '@dexterai/vault/types';
|
|
4
4
|
export { AtomicAmount, HumanAmount, SessionKey, SessionScope, SignedVoucher, TabNetworkId, VoucherPayload } from '@dexterai/vault/types';
|
|
5
|
-
import { a as PayResult } from '../types-
|
|
5
|
+
import { a as PayResult } from '../types-BL9QW1gf.js';
|
|
6
6
|
export { SessionRegisterMessageArgs, SessionRevokeMessageArgs, VoucherPayloadBytes, buildVoucherMessage, sessionRegisterMessage, sessionRevokeMessage, voucherPayloadMessage } from '@dexterai/vault/messages';
|
|
7
7
|
export { BuildRegisterSessionKeyArgs, BuildRevokeSessionKeyArgs, buildRegisterSessionKeyInstruction, buildRevokeSessionKeyInstruction } from '@dexterai/vault/instructions';
|
|
8
8
|
export { buildSecp256r1VerifyInstruction } from '@dexterai/vault/precompile';
|
|
@@ -25,7 +25,7 @@ import '../types-xQu1U4xk.js';
|
|
|
25
25
|
*/
|
|
26
26
|
|
|
27
27
|
/** Live Dexter x402 facilitator API. NOT facilitator.dexter.cash —
|
|
28
|
-
* that's a marketing redirect.
|
|
28
|
+
* that's a marketing redirect. */
|
|
29
29
|
declare const DEFAULT_FACILITATOR_URL = "https://x402.dexter.cash";
|
|
30
30
|
/**
|
|
31
31
|
* Convert a human decimal string ("0.001") to atomic-unit string ("1000")
|
|
@@ -137,13 +137,15 @@ interface TabTerms {
|
|
|
137
137
|
scheme: 'tab';
|
|
138
138
|
/**
|
|
139
139
|
* How a Dexter tab settles — properties of scheme 'tab' as shipped, not
|
|
140
|
-
* seller-configurable:
|
|
141
|
-
*
|
|
140
|
+
* seller-configurable: protection is 'lock' (the standard since Step-4) —
|
|
141
|
+
* accrued charges crystallize on-chain into a reservation the buyer cannot
|
|
142
|
+
* withdraw out from under, sized to the accrued amount only (not a
|
|
143
|
+
* whole-wallet freeze). Funds stay in the buyer's vault until settle
|
|
142
144
|
* (non-custodial), and settlement happens at tab close.
|
|
143
145
|
*/
|
|
144
146
|
settlement: {
|
|
145
147
|
custody: 'non-custodial';
|
|
146
|
-
protection: '
|
|
148
|
+
protection: 'lock';
|
|
147
149
|
settleOn: 'close';
|
|
148
150
|
};
|
|
149
151
|
/** Credit terms (Product 2). Reserved; always null today. */
|