@dexterai/x402 3.15.0 → 3.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -1
- package/dist/client/index.cjs +1 -1
- package/dist/client/index.d.cts +3 -152
- package/dist/client/index.d.ts +3 -152
- package/dist/client/index.js +1 -1
- package/dist/tab/index.cjs +5 -5
- package/dist/tab/index.d.cts +78 -3
- package/dist/tab/index.d.ts +78 -3
- package/dist/tab/index.js +5 -5
- package/dist/tab/seller/index.cjs +4 -4
- package/dist/tab/seller/index.d.cts +30 -1
- package/dist/tab/seller/index.d.ts +30 -1
- package/dist/tab/seller/index.js +4 -4
- package/dist/types-B1wGPP7B.d.cts +154 -0
- package/dist/types-ZjcxOAbW.d.ts +154 -0
- package/package.json +1 -1
package/dist/tab/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Kt=Object.create;var Je=Object.defineProperty;var Wt=Object.getOwnPropertyDescriptor;var qt=Object.getOwnPropertyNames;var Ht=Object.getPrototypeOf,Ft=Object.prototype.hasOwnProperty;var jt=(n,e)=>{for(var t in e)Je(n,t,{get:e[t],enumerable:!0})},wt=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of qt(e))!Ft.call(n,a)&&a!==t&&Je(n,a,{get:()=>e[a],enumerable:!(r=Wt(e,a))||r.enumerable});return n};var G=(n,e,t)=>(t=n!=null?Kt(Ht(n)):{},wt(e||!n||!n.__esModule?Je(t,"default",{value:n,enumerable:!0}):t,n)),Jt=n=>wt(Je({},"__esModule",{value:!0}),n);var Tn={};jt(Tn,{DEFAULT_FACILITATOR_URL:()=>Xe,DEXTER_VAULT_PROGRAM_ID:()=>F.DEXTER_VAULT_PROGRAM_ID,INSTRUCTIONS_SYSVAR_ID:()=>F.INSTRUCTIONS_SYSVAR_ID,SECP256R1_PROGRAM_ID:()=>F.SECP256R1_PROGRAM_ID,SessionScopeExceededError:()=>ie,TabClosedError:()=>Q,UnsupportedNetworkError:()=>oe,atomicToHuman:()=>Ce,buildRegisterSessionKeyInstruction:()=>fe.buildRegisterSessionKeyInstruction,buildRevokeSessionKeyInstruction:()=>fe.buildRevokeSessionKeyInstruction,buildSecp256r1VerifyInstruction:()=>bt.buildSecp256r1VerifyInstruction,buildVoucherMessage:()=>B.buildVoucherMessage,humanToAtomic:()=>Z,openTab:()=>Ye,payUrlWithTab:()=>Vt,resolveTabOffer:()=>Ge,resumeTab:()=>Pt,sessionRegisterMessage:()=>B.sessionRegisterMessage,sessionRevokeMessage:()=>B.sessionRevokeMessage,voucherPayloadMessage:()=>B.voucherPayloadMessage,voucherToHeader:()=>ke});module.exports=Jt(Tn);var oe=class extends Error{constructor(t){super(`Network ${t} is not yet supported by @dexterai/x402/tab`);this.network=t;this.name="UnsupportedNetworkError"}},ie=class extends Error{constructor(t,r){super(`Session scope exceeded: ${t}${r?` (${r})`:""}`);this.reason=t;this.name="SessionScopeExceededError"}},Q=class extends Error{constructor(t){super(`Tab ${t} is already closed`);this.channelId=t;this.name="TabClosedError"}};var pt=require("@solana/web3.js"),ee=require("@noble/hashes/utils");var Xt=G(require("tweetnacl"),1);var B=require("@dexterai/vault/messages");var Tt=require("@noble/hashes/sha256");function xt(n){let e=new Uint8Array(8);new DataView(e.buffer).setBigUint64(0,n.nonce,!0);let t=new TextEncoder().encode(n.sellerUrl),r=Tt.sha256.create();return r.update(n.vaultPda.toBytes()),r.update(t),r.update(e),r.digest()}var Yt=3600,Xe="https://x402.dexter.cash",Et=6;function Z(n,e=Et){if(!/^\d+(\.\d+)?$/.test(n))throw new Error(`amount must be a non-negative decimal string, got "${n}"`);let[t,r=""]=n.split(".");if(r.length>e)throw new Error(`amount "${n}" has more than ${e} decimals`);let a=r.padEnd(e,"0"),s=`${t}${a}`.replace(/^0+(?=\d)/,"");return s===""?"0":s}function Ce(n,e=Et){if(!/^\d+$/.test(n))throw new Error(`atomic must be a non-negative integer string, got "${n}"`);let t=n.padStart(e+1,"0"),r=t.slice(0,-e).replace(/^0+(?=\d)/,"")||"0",a=t.slice(-e).replace(/0+$/,"");return a?`${r}.${a}`:r}var ut=class{channelId;network;counterparty;internals;cumulativeAtomic=0n;sequenceNumber=0;closed=!1;lastSignedVoucher=null;previousSignedVoucher=null;constructor(e){this.internals=e,this.channelId=e.channelIdHex,this.network=e.network,this.counterparty=e.counterparty}get state(){let e=this.internals.totalCapAtomic-this.cumulativeAtomic,t=Math.floor(Date.now()/1e3);return{isOpen:!this.closed,spent:Ce(this.cumulativeAtomic.toString()),remaining:Ce(e.toString()),expiresInSec:Math.max(0,this.internals.expiresAtUnix-t)}}async signNextVoucher(e){if(this.closed)throw new Q(this.channelId);let t=BigInt(e);if(t<=0n)throw new Error(`voucher increment must be > 0, got ${e}`);if(t>this.internals.perUnitCapAtomic)throw new ie("cap_exceeded",`single voucher increment ${t} exceeds perUnitCap ${this.internals.perUnitCapAtomic}`);let r=this.cumulativeAtomic+t;if(r>this.internals.totalCapAtomic)throw new ie("cap_exceeded",`cumulative ${r} would exceed totalCap ${this.internals.totalCapAtomic}`);let a=this.sequenceNumber+1,s={channelId:this.channelId,cumulativeAmount:r.toString(),sequenceNumber:a},o=await this.internals.vault.signWithSession(this.internals.session,s);return this.previousSignedVoucher=this.lastSignedVoucher,this.lastSignedVoucher=o,this.sequenceNumber=a,this.cumulativeAtomic=r,o}rollbackVoucher(e){let t=this.lastSignedVoucher;if(!t||t.payload.sequenceNumber!==e.payload.sequenceNumber||t.payload.cumulativeAmount!==e.payload.cumulativeAmount)return!1;let r=this.previousSignedVoucher;if(r)this.sequenceNumber=r.payload.sequenceNumber,this.cumulativeAtomic=BigInt(r.payload.cumulativeAmount),this.lastSignedVoucher=r;else if(t.payload.sequenceNumber===1)this.sequenceNumber=0,this.cumulativeAtomic=0n,this.lastSignedVoucher=null;else return!1;return this.previousSignedVoucher=null,!0}async stream(e,t){if(this.closed)throw new Q(this.channelId);let r=await this.signNextVoucher(this.internals.perUnitCapAtomic.toString()),a=new Headers(t?.headers);a.set("X-Tab-Voucher",ke(r)),a.set("Accept","text/event-stream");let s=await fetch(e,{...t,headers:a});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`tab.stream HTTP ${s.status}: ${o.slice(0,500)}`)}if(!s.body)throw new Error("tab.stream response has no body");return Zt(s.body)}async close(){if(this.closed)throw new Q(this.channelId);let e={settleTx:""};return this.lastSignedVoucher&&this.cumulativeAtomic>0n&&(e=await zt(this.internals.facilitatorUrl,this.lastSignedVoucher,this.internals.network)),await this.internals.vault.signCloseTab(this.internals.session,this.channelId,this.cumulativeAtomic.toString()),this.closed=!0,this.internals.session.privateKey.fill(0),{settledAmount:Ce(this.cumulativeAtomic.toString()),...e}}};function ke(n){return Buffer.from(JSON.stringify({payload:n.payload,sessionPublicKey:(0,ee.bytesToHex)(n.sessionPublicKey),sessionRegistration:(0,ee.bytesToHex)(n.sessionRegistration),sessionSignature:(0,ee.bytesToHex)(n.sessionSignature)}),"utf8").toString("base64")}async function zt(n,e,t){let r=`${n.replace(/\/$/,"")}/tab/settle`,a={channelId:e.payload.channelId,cumulativeAmount:e.payload.cumulativeAmount,sequenceNumber:e.payload.sequenceNumber,sessionPublicKey:(0,ee.bytesToHex)(e.sessionPublicKey),sessionSignature:(0,ee.bytesToHex)(e.sessionSignature),sessionRegistration:(0,ee.bytesToHex)(e.sessionRegistration),network:t},s=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(a)}),o=await s.text();if(!s.ok)throw new Error(`tab settle ${s.status}: ${o.slice(0,500)}`);let i;try{i=JSON.parse(o)}catch{throw new Error(`tab settle returned non-JSON: ${o.slice(0,200)}`)}if(!i.settleTx)throw new Error(`tab settle returned no settleTx: ${o.slice(0,200)}`);let c={settleTx:i.settleTx};return typeof i.grossAmount=="string"&&(c.grossAmount=i.grossAmount),typeof i.feeAmount=="string"&&(c.feeAmount=i.feeAmount),typeof i.netAmount=="string"&&(c.netAmount=i.netAmount),c}async function Gt(n,e,t,r,a){let s=`${n.replace(/\/$/,"")}/tab/open`,o=await fetch(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({buyer_swig_address:e,seller:a,max_amount_atomic:t.toString(),network:r})}),i=await o.json().catch(()=>({}));if(!o.ok||!i.success||!i.armed)throw new Error(`tab_open_unprotected: ${i.error??`http_${o.status}`}`);return{armed:!0,signature:i.signature??""}}async function Ye(n){if(n.network!==n.vault.network)throw new oe(`options.network (${n.network}) doesn't match vault.network (${n.vault.network})`);if(n.network!=="solana:mainnet")throw new oe(n.network);let e=BigInt(Math.floor(Math.random()*4294967295)),t=new pt.PublicKey(n.vault.vaultPda),r=xt({vaultPda:t,sellerUrl:n.seller,nonce:BigInt(e)}),a=(0,ee.bytesToHex)(r),s=BigInt(Z(n.perUnitCap)),o=BigInt(Z(n.totalCap));if(s<=0n)throw new Error("perUnitCap must be > 0");if(o<s)throw new Error("totalCap must be >= perUnitCap");if(n.revolvingCapacity!==void 0&&BigInt(Z(n.revolvingCapacity))<=0n)throw new Error("revolvingCapacity must be > 0");let i=n.sessionDuration??Yt,c=Math.floor(Date.now()/1e3)+i,l=Qt(n.seller),m={channelId:a,maxAmountAtomic:o.toString(),revolvingCapacityAtomic:n.revolvingCapacity?Z(n.revolvingCapacity):o.toString(),expiresAtUnix:c,allowedCounterparty:l},f=await n.vault.authorizeSession(m);return await Gt(n.facilitatorUrl??Xe,n.vault.swigAddress,o,n.network,l),new ut({vault:n.vault,network:n.network,seller:n.seller,counterparty:l,session:f,channelIdHex:a,channelIdBytes:r,perUnitCapAtomic:s,totalCapAtomic:o,expiresAtUnix:c,facilitatorUrl:n.facilitatorUrl??Xe})}async function Pt(n){throw new Error("resumeTab is Phase 3 work. Session keys are memory-only by design; recovery requires reading active_session on chain and re-authorizing. Tracked in dexter-vault roadmap.")}function Qt(n){if(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(n))try{return new pt.PublicKey(n),n}catch{}throw new Error(`seller must be a base58 Solana pubkey for Phase 2 (got "${n}"). URL-based counterparty resolution lands in Phase 3 (seller middleware).`)}async function*Zt(n){let e=n.getReader(),t=new TextDecoder,r="";try{for(;;){let{done:a,value:s}=await e.read();if(a)break;r+=t.decode(s,{stream:!0});let o;for(;(o=r.indexOf(`
|
|
2
2
|
|
|
3
|
-
`))!==-1;){let
|
|
4
|
-
`);yield new TextEncoder().encode(
|
|
5
|
-
`))r.startsWith("event:")?
|
|
6
|
-
`):null}}var h=require("@dexterai/vault/instructions"),T=require("@dexterai/vault/precompile"),l=require("@dexterai/vault/constants");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,resumeTab,sessionRegisterMessage,sessionRevokeMessage,voucherPayloadMessage,voucherToHeader});
|
|
3
|
+
`))!==-1;){let i=r.slice(0,o);r=r.slice(o+2);let c=en(i);if(c.eventName==="end")return;if(c.data!==null){let l=c.data.replace(/\\n/g,`
|
|
4
|
+
`);yield new TextEncoder().encode(l)}}}}finally{e.releaseLock()}}function en(n){let e=null,t=[];for(let r of n.split(`
|
|
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 Rt=[{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"}],tn=new Map(Rt.map(n=>[n.caip2.toLowerCase(),n])),nn=new Map(Rt.map(n=>[n.bare.toLowerCase(),n]));function Ie(n){if(!n)return null;let e=n.toLowerCase(),t=tn.get(e)||nn.get(e);return t?{caip2:t.caip2,bare:t.bare,family:t.family}:null}function mt(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 rn(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,a=Ie(String(r.network??""));a&&e.push({scheme:String(r.scheme??"exact"),network:a,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 ze(n){let e=n.headers.get("payment-required");if(!e)return null;let t;try{t=mt(e)}catch{return null}let r=Array.isArray(t.accepts)?t.accepts:[];return r.length===0?null:{x402Version:2,options:rn(r),resourceUrl:t.resource&&typeof t.resource=="object"?String(t.resource.url??""):void 0}}async function Ge(n,e={},t=fetch){let r={method:e.method??"GET",headers:e.headers};typeof e.body=="string"&&(r.body=e.body);let a;try{a=await t(n,r)}catch(i){return{kind:"error",detail:`probe failed: ${i?.message??String(i)}`}}if(a.status!==402)return a.ok?{kind:"free",response:a}:{kind:"error",detail:`probe returned HTTP ${a.status}`};let s=await ze(a);if(!s)return{kind:"error",detail:"the 402 carries no x402 v2 PAYMENT-REQUIRED challenge"};let o=s.options.find(i=>i.scheme==="tab"&&i.network.family==="svm");if(!o)return{kind:"no_tab",schemesOffered:s.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:s.resourceUrl}}}var Ne="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Qe="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Ze="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",ce=Ne,Oe=Qe,Ue=Ze,le="eip155:8453",Se="eip155:84532",Ae="eip155:42161",be="eip155:137",we="eip155:10",Te="eip155:43114",xe="eip155:56",Ee="eip155:1187947933",Pe="eip155:324705682",Re="eip155:1",ue=le,et=Se,Be=Ae,De=be,Me=we,$e=Te,Le=xe,Ve=Ee,Ke=Pe,We=Re,dt="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",_t="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",Ct="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",ft="0x55d398326f99059fF775485246999027B3197955",tt="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",nt={[xe]:tt,[le]:Ct,[Se]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[Ae]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[be]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[we]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[Te]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[Ee]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[Pe]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[Re]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},rt={[ft]:{symbol:"USDT",decimals:18},[tt]:{symbol:"USDC",decimals:18}};var te="0x000000000022D473030F116dDEE9F6B43aC78BA3",qe="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",He={[xe]:56,[le]:8453,[Se]:84532,[Ae]:42161,[be]:137,[we]:10,[Te]:43114,[Ee]:1187947933,[Pe]:324705682,[Re]:1},pe={[Ne]:"https://api.dexter.cash/api/solana/rpc",[Qe]:"https://api.devnet.solana.com",[Ze]:"https://api.testnet.solana.com"},D={[xe]:"https://api.dexter.cash/api/evm/bsc/rpc",[le]:"https://api.dexter.cash/api/base/rpc",[Se]:"https://sepolia.base.org",[Ae]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[be]:"https://api.dexter.cash/api/evm/polygon/rpc",[we]:"https://api.dexter.cash/api/evm/optimism/rpc",[Te]:"https://api.dexter.cash/api/evm/avalanche/rpc",[Ee]:"https://skale-base.skalenodes.com/v1/base",[Pe]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[Re]:"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,sn=1;function me(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=[ce,Oe,Ue];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]:pe[e]?pe[e]:e==="solana"?pe[ce]:e==="solana-devnet"?pe[Oe]:e==="solana-testnet"?pe[Ue]:pe[ce]}getAddress(e){return me(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return me(e)?e.publicKey!==null:!1}async getBalance(e,t,r){if(!me(t)||!t.publicKey)return 0;let a=r||this.getDefaultRpcUrl(e.network),s=new I.Connection(a,"confirmed"),o=new I.PublicKey(t.publicKey.toBase58()),i=new I.PublicKey(e.asset);try{let l=(await s.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)(s,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(!me(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let a=r||this.getDefaultRpcUrl(e.network),s=new I.Connection(a,"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:sn}));let _=await s.getAccountInfo(d,"confirmed");if(!_)throw new Error(`Token mint ${c} not found`);let P=_.owner.toBase58()===N.TOKEN_2022_PROGRAM_ID.toBase58()?N.TOKEN_2022_PROGRAM_ID:N.TOKEN_PROGRAM_ID,h=await(0,N.getMint)(s,d,void 0,P);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,P),x=await(0,N.getAssociatedTokenAddress)(d,E,!0,P);if(!await s.getAccountInfo(y,"confirmed"))throw new Error(`No token account found for ${c}. Please ensure you have USDC in your wallet.`);if(!await s.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,[],P));let{blockhash:W}=await s.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"),a=new I.PublicKey(e.destinationAta),s=await r.getSignaturesForAddress(a,{limit:25});if(s.length===0)return{settled:!1};let o=BigInt(e.amount);for(let i of s){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(a))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 on={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 de(n){if(!n||typeof n!="object")return!1;let e=n;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var st=class{name="EVM";networks=[Le,ue,et,We,Be,De,Me,$e,Ve,Ke];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[ue]:e==="bsc"?D[Le]:e==="ethereum"?D[We]:e==="arbitrum"?D[Be]:e==="polygon"?D[De]:e==="optimism"?D[Me]:e==="avalanche"?D[$e]:e==="skale-base"?D[Ve]:e==="skale-base-sepolia"?D[Ke]:D[ue]}getAddress(e){return de(e)?e.address:null}isConnected(e){return de(e)?!!e.address:!1}getChainId(e){if(He[e])return He[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(!de(t)||!t.address)return 0;let a=r||this.getDefaultRpcUrl(e.network);try{let s=this.encodeBalanceOf(t.address),o=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:e.asset,data:s},"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(s){throw s}}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",a=e.from.slice(2).toLowerCase().padStart(64,"0"),s=e.nonce.slice(2).toLowerCase().padStart(64,"0"),o=r+a+s,i=await this.ethCall(t,e.asset,o);return{settled:BigInt(i)!==0n}}if(e.kind==="permit2"){let r="0x4fe02b44",a=BigInt(e.nonce),s=a>>8n,o=a&0xffn,i=e.from.slice(2).toLowerCase().padStart(64,"0"),c=s.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 a=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(!a.ok)throw new Error(`RPC request failed: ${a.status}`);let s=await a.json();if(s.error)throw new Error(`RPC error: ${JSON.stringify(s.error)}`);if(!s.result||s.result==="0x")throw new Error("RPC returned an empty result");return s.result}async buildTransaction(e,t,r){if(!de(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:a,asset:s,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:a,amount:i,asset:s,network:e.network});let c=this.getChainId(e.network),l={name:o?.name??"USD Coin",version:o?.version??"2",chainId:BigInt(c),verifyingContract:s},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:a,value:i,validAfter:String(E-600),validBefore:String(E+(e.maxTimeoutSeconds||60)),nonce:d},_={from:t.address,to:a,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 P=await t.signTypedData({domain:l,types:m,primaryType:"TransferWithAuthorization",message:_});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:p,signature:P}),signature:P,settlementProbe:{kind:"eip3009",from:t.address,nonce:d,asset:s,chainId:c}}}async buildApprovalTransaction(e,t,r){let{payTo:a,asset:s,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:a,amount:i,asset:s,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,s,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:s,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 P="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:a,token:s,amount:BigInt(i),fee:BigInt(m),nonce:BigInt(p),deadline:BigInt(y),paymentId:P},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:a,token:s,amount:i,fee:m,nonce:p,deadline:y,paymentId:P,signature:W};return{serialized:JSON.stringify(re),signature:W}}async buildPermit2Transaction(e,t,r){let{payTo:a,asset:s}=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:a,amount:o,asset:s,network:e.network});let i=r||this.getDefaultRpcUrl(e.network),c=await this.readAllowance(i,s,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:s,data:U,chainId:M,gas:50000n,gasPrice:j,nonce:W});l={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:s,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:s,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),P={name:"Permit2",chainId:BigInt(_),verifyingContract:te},h={permitted:{token:s,amount:BigInt(o)},spender:qe,nonce:f,deadline:BigInt(p),witness:{to:a,validAfter:BigInt(E)}},y=await t.signTypedData({domain:P,types:on,primaryType:"PermitWitnessTransferFrom",message:h});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let x={signature:y,permit2Authorization:{from:t.address,permitted:{token:s,amount:o},spender:qe,nonce:f.toString(),deadline:String(p),witness:{to:a,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,a){let s="0xdd62ed3e",o=r.slice(2).toLowerCase().padStart(64,"0"),i=a.slice(2).toLowerCase().padStart(64,"0"),c=s+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",a=e.slice(2).toLowerCase().padStart(64,"0"),s=t.toString(16).padStart(64,"0");return r+a+s}async waitForReceipt(e,t,r=3e4){let a=Date.now();for(;Date.now()-a<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(s){if(s instanceof Error&&s.message.includes("reverted"))throw s}await new Promise(s=>setTimeout(s,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 a=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 a.result?parseInt(a.result,16):0}catch{return 0}}calculateApprovalAmount(e,t,r){let a=BigInt(e)+BigInt(t);if(!r||r.mode==="exact")return a;let s=BigInt(r.defaultMultiple??10),o=a*s;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 a}return o}inferDecimals(e){return e.length>12?18:6}};function ve(n){return new st(n)}function gt(n){if(n===dt||n===_t)return!0;let e=n.toLowerCase();for(let t of Object.values(nt))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(rt))if(t.toLowerCase()===e)return!0;return!1}function cn(n){return{[Ne]:"Solana",[Qe]:"Solana Devnet",[Ze]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[le]:"Base",[Se]:"Base Sepolia",[Re]:"Ethereum",[Ae]:"Arbitrum",[be]:"Polygon",[we]:"Optimism",[Te]:"Avalanche",[xe]:"BSC",[Ee]:"SKALE Base",[Pe]:"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=cn(n);return t===n?e:t}async function ln(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 a={method:e?.method??t.method,headers:r,signal:e?.signal??t.signal,redirect:e?.redirect??t.redirect,credentials:e?.credentials??t.credentials},s=(a.method??"GET").toUpperCase();return e&&"body"in e?a.body=e.body:s!=="GET"&&s!=="HEAD"&&t.body&&(a.body=await t.arrayBuffer()),[t.url,a]}var un=new WeakMap;function Nt(n){let{adapters:e=[ne({verbose:n.verbose}),ve({verbose:n.verbose})],wallets:t,wallet:r,preferredNetwork:a,rpcUrls:s={},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(R=>setTimeout(R,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(R=>setTimeout(R,E*Math.pow(2,S))))}throw w}let P=new Map;function h(g){try{let b=new URL(g).host,w=P.get(b);if(w&&w.expiresAt>Date.now()/1e3+10)return w.jwt;w&&P.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,"/"))),R=Math.floor(Date.now()/1e3),v=R+86400,V=Math.min(typeof T.exp=="number"?T.exp:R,v);P.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&&me(r)&&(x.solana=r),r&&!x.evm&&de(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 R;T.name==="Solana"?R=x.solana:T.name==="EVM"&&(R=x.evm),R&&T.isConnected(R)&&b.push({accept:w,adapter:T,wallet:R})}if(b.length===0)return null;if(a){let w=b.find(S=>S.accept.network===a);if(w)return w}return b[0]}function M(g,b){return It(g,b)}function j(g,b){return s[g]||b.getDefaultRpcUrl(g)}async function W(g,b,w,S,T){let R="";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}`);R=`tier=${u.id}`}}else if(l?.preferDuration&&S.ratePerHour)R=`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}`);R=`tier=${u.id}`}let v=R?T.includes("?")?`${T}&${R}`:`${T}?${R}`:T;p("Purchasing access pass:",R||"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:ge}=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 _e=C.amount??C.maxAmountRequired;if(!_e)return null;let X=j(C.network,q);try{let u=await q.getBalance(C,ge,X),A=Number(_e)/Math.pow(10,J);if(u<A){let lt=M(C.network,q.name);throw new k("insufficient_balance",`Insufficient balance for access pass on ${lt}. Have $${u.toFixed(4)}, need $${A.toFixed(4)}`)}}catch(u){if(u instanceof k)throw u}let Y=await q.buildTransaction(C,ge,X),ye;q.name==="EVM"?ye=JSON.parse(Y.serialized):ye={transaction:Y.serialized};let ae=typeof g=="string"?g:g instanceof URL?g.href:g.url,he=$.resource;if(typeof $.resource=="string")try{let u=new URL($.resource,ae);["http:","https:"].includes(u.protocol)&&(he=u.toString())}catch{}else if($.resource&&typeof $.resource=="object"&&"url"in $.resource){let u=$.resource;try{let A=new URL(u.url,ae);["http:","https:"].includes(A.protocol)&&(he={...u,url:A.toString()})}catch{}}let je={x402Version:C.x402Version??2,resource:he,accepted:C,payload:ye};Y.extensions&&(je.extensions=Y.extensions);let z=btoa(JSON.stringify(je)),se=await i(v,{...b,method:"POST",headers:{...b?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":z}});if(!se.ok)return p("Pass purchase failed:",se.status),null;let K=se.headers.get("ACCESS-PASS");return K&&(y(T,K),p("Access pass purchased and cached")),se}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{P.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 R=S.headers.get("PAYMENT-REQUIRED");if(!R)throw new k("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let v;try{let u=atob(R);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 ge=O.extra?.decimals??(gt(O.asset)?6:void 0);if(typeof ge!="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 _e=j(O.network,C);p("Checking balance...");try{let u=await C.getBalance(O,q,_e),A=Number(J)/Math.pow(10,ge);if(u<A){let lt=M(O.network,C.name);throw new k("insufficient_balance",`Insufficient balance on ${lt}. 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,_e);p("Transaction signed");let Y;C.name==="EVM"?Y=JSON.parse(X.serialized):Y={transaction:X.serialized};let ye=g,ae=v.resource;if(typeof v.resource=="string")try{let u=new URL(v.resource,ye).toString();u!==v.resource&&p("Resolved relative resource URL:",v.resource,"\u2192",u),ae=u}catch{ae=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,ye).toString();A!==u.url&&(p("Resolved relative resource URL:",u.url,"\u2192",A),ae={...u,url:A})}catch{}}let he={x402Version:O.x402Version??2,resource:ae,accepted:O,payload:Y};X.extensions&&(he.extensions=X.extensions);let je=btoa(JSON.stringify(he));if(f)try{f(O,X.settlementProbe)}catch{}p("Retrying request with payment...");let z=await _(g,{...b,headers:{...b?.headers||{},"PAYMENT-SIGNATURE":je,...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 se=z.headers.get("PAYMENT-RESPONSE"),K;if(se)try{K=JSON.parse(atob(se))}catch{}return K??={},K.amountAtomic=J,K.assetDecimals=ge,un.set(z,K),K.extensions&&p("Settlement extensions:",Object.keys(K.extensions).join(", ")),z}async function L(g,b){let[w,S]=await ln(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 Fe(n){let e="";try{e=(await n.clone().text()).slice(0,600)}catch{}let t=e.toLowerCase(),r=t.includes("settle")||t.includes("facilitator"),a=e;try{let s=JSON.parse(e),o=[s.error,s.detail,s.message].filter(i=>typeof i=="string"&&i.length>0);o.length>0&&(a=o.join(" \u2014 "))}catch{}return a||(a=`HTTP ${n.status}`),{reason:r?"settlement_failed":"merchant_rejected",detail:`merchant HTTP ${n.status}: ${a}`}}var ot="Payment authorization was sent, but the merchant did not respond within the timeout. ",it=" Do not retry without checking \u2014 inspect the funding wallet for a transfer to the merchant before attempting payment again.";async function ct(n,e,t){if(!n)return{confirmed:!1,detail:ot+"This payment scheme has no on-chain confirmation check, so the SDK cannot verify whether it settled."+it};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=ve(),a=r.getDefaultRpcUrl(e.caip2);if(!r.confirmSettlement)return Ut();let s=await r.confirmSettlement(n,a);return s.settled?{confirmed:!0,txSignature:s.txSignature}:Ot()}catch(r){return{confirmed:!1,detail:ot+`On-chain confirmation could not be completed (${H(r)}).`+it}}}function Ot(){return{confirmed:!1,detail:ot+"On-chain confirmation found no matching settlement yet \u2014 the payment may still be pending, or may not have settled."+it}}function Ut(){return{confirmed:!1,detail:ot+"The chain adapter does not support on-chain confirmation."+it}}var pn=new Set(["exact","exact-approval"]);async function mn(n,e,t,r){let a;try{a=await r.signNextVoucher(t.amount)}catch{return null}let s=new Headers(e.headers??void 0);s.set("X-Tab-Voucher",ke(a));let o={method:e.method??"GET",headers:s};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,a),null):i.ok?{ok:!0,paid:!0,response:i,amountPaid:t.amount,network:t.network}:{ok:!1,...await Fe(i)}}var Bt={version:2,async parseChallenge(n){return ze(n)},async pay(n,e,t,r,a){if(a.tab){let h=t.options.find(y=>y.scheme==="tab"&&y.network.family==="svm"&&y.payTo===a.tab.counterparty);if(h){let y=await mn(n,e,h,a.tab);if(y)return y}}let s=t.options.filter(h=>pn.has(h.scheme));if(s.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=s.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=a.timeoutMs??15e3,c=a.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:a.maxAmountAtomic,fetch:globalThis.fetch,onPaymentDispatched:E}),_=e.signal?AbortSignal.any([e.signal,l.signal]):l.signal,P={method:e.method??"GET",headers:e.headers,signal:_};typeof e.body=="string"&&(P.body=e.body);try{let h=await p.fetch(n,P);if(clearTimeout(m),!h.ok)return{ok:!1,...await Fe(h)};let y,x=h.headers.get("PAYMENT-RESPONSE");if(x)try{let U=mt(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 ct(d,o.network,a.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 dn={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 fn(){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 gn(n,e,t){if(typeof n.signTypedData!="function")throw new Error("EVM wallet does not support signTypedData");let r=Math.floor(Date.now()/1e3),a=String(r-600),s=String(r+(e.maxTimeoutSeconds??60)),o={from:n.address,to:e.payTo,value:e.amount,validAfter:a,validBefore:s,nonce:await fn()},i=He[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:dn,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 a of n.options){let s=a.network.family==="evm"&&!!e.evm||a.network.family==="svm"&&!!e.solana;if(a.scheme!=="exact"){s&&(r=a.scheme);continue}if(a.network.family==="evm"&&e.evm){let o=await e.evm;return await yn(a,o,t)}if(a.network.family==="svm"&&e.solana){let o=await e.solana;return await hn(a,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 yn(n,e,t){if(t.maxAmountAtomic!==void 0&&BigInt(n.amount)>BigInt(t.maxAmountAtomic))return{ok:!1,reason:"budget_exceeded"};let r=n.extra??{},a=r.name,s=r.version;if(typeof a!="string"||a.length===0||typeof s!="string"||s.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 gn(e,n,o);return{ok:!0,headerValue:Buffer.from(JSON.stringify(i),"utf8").toString("base64"),option:n,settlementProbe:c}}async function hn(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 a=n.network.bare,s={x402Version:1,scheme:n.scheme,network:a,asset:n.asset,payTo:n.payTo,amount:n.amount,maxAmountRequired:n.amount,maxTimeoutSeconds:n.maxTimeoutSeconds??60,extra:r},i=await ne().buildTransaction(s,e,t.solanaRpcUrl),c={x402Version:1,scheme:n.scheme,network:a,payload:{transaction:i.serialized}};return{ok:!0,headerValue:Buffer.from(JSON.stringify(c),"utf8").toString("base64"),option:n,settlementProbe:i.settlementProbe}}function Sn(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,a=Ie(String(r.network??""));a&&e.push({scheme:String(r.scheme??"exact"),network:a,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=Sn(t);return r.length===0?null:{x402Version:1,options:r}},async pay(n,e,t,r,a){let s,o=new AbortController,i=!1,c,l;try{let m=a.timeoutMs??15e3;s=setTimeout(()=>o.abort(),m);let f=await yt(t,r,a);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,P={method:e.method,headers:p,signal:_};typeof e.body=="string"&&(P.body=e.body),i=!0,clearTimeout(s);let h=a.responseTimeoutMs??12e4;s=setTimeout(()=>o.abort(),h);let y=await fetch(n,P);return y.ok?{ok:!0,paid:!0,response:y,amountPaid:E.amount,network:E.network,txSignature:An(y)}:{ok:!1,...await Fe(y)}}catch(m){if(m instanceof Error&&m.name==="AbortError"){if(!i)return{ok:!1,reason:"timeout"};let f=await ct(c,l.network,a.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{s!==void 0&&clearTimeout(s)}}};function An(n){let e=n.headers.get("x-payment-response")??n.headers.get("X-PAYMENT-RESPONSE");if(e)try{let t=JSON.parse(Buffer.from(e,"base64").toString("utf8")),r=t.transaction??t.txHash??t.transactionHash;return typeof r=="string"?r:void 0}catch{return}}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 a=>Lt.sign.detached(a,r.secretKey)}}return null}var bn=[Bt,Mt];async function wn(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 a;try{a=await(await wn(t))(n,{...e})}catch(s){return{ok:!1,reason:"error",detail:H(s)}}if(a.status!==402)return{ok:!0,paid:!1,response:a};for(let s of bn){let o=await s.parseChallenge(a.clone());if(o)return s.pay(n,e,o,t,r)}return{ok:!1,reason:"no_payment_options"}}async function Vt(n,e={},t){let r=await Ge(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:a}=r,s=BigInt(Z(t.perUnitCap));if(BigInt(a.amountAtomic)>s)return{result:{ok:!1,reason:"budget_exceeded",detail:`seller quotes ${a.amountAtomic} atomic; perUnitCap allows ${s}`},tab:null};let o=t.tabs?.get(a.payTo);return(!o||!o.state.isOpen)&&(o=await Ye({vault:t.vault,network:"solana:mainnet",seller:a.payTo,perUnitCap:t.perUnitCap,totalCap:t.totalCap,sessionDuration:t.sessionDuration,facilitatorUrl:t.facilitatorUrl}),t.tabs?.set(a.payTo,o)),{result:await At(n,e,{},{tab:o}),tab:o}}var fe=require("@dexterai/vault/instructions"),bt=require("@dexterai/vault/precompile"),F=require("@dexterai/vault/constants");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,resumeTab,sessionRegisterMessage,sessionRevokeMessage,voucherPayloadMessage,voucherToHeader});
|
package/dist/tab/index.d.cts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import { O as OpenTabOptions, T as Tab, R as ResumeTabOptions } from '../types-DEnVPFxF.cjs';
|
|
2
|
-
export { S as SessionScopeExceededError, b as TabCloseResult, c as TabClosedError, a as TabState, U as UnsupportedNetworkError
|
|
1
|
+
import { O as OpenTabOptions, T as Tab, R as ResumeTabOptions, V as VaultAdapter } from '../types-DEnVPFxF.cjs';
|
|
2
|
+
export { S as SessionScopeExceededError, b as TabCloseResult, c as TabClosedError, a as TabState, U as UnsupportedNetworkError } from '../types-DEnVPFxF.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-B1wGPP7B.cjs';
|
|
5
6
|
export { SessionRegisterMessageArgs, SessionRevokeMessageArgs, VoucherPayloadBytes, buildVoucherMessage, sessionRegisterMessage, sessionRevokeMessage, voucherPayloadMessage } from '@dexterai/vault/messages';
|
|
6
7
|
export { BuildRegisterSessionKeyArgs, BuildRevokeSessionKeyArgs, buildRegisterSessionKeyInstruction, buildRevokeSessionKeyInstruction } from '@dexterai/vault/instructions';
|
|
7
8
|
export { buildSecp256r1VerifyInstruction } from '@dexterai/vault/precompile';
|
|
8
9
|
export { DEXTER_VAULT_PROGRAM_ID, INSTRUCTIONS_SYSVAR_ID, SECP256R1_PROGRAM_ID } from '@dexterai/vault/constants';
|
|
10
|
+
import '../types-xQu1U4xk.cjs';
|
|
9
11
|
|
|
10
12
|
/**
|
|
11
13
|
* The `Tab` runtime — the live object returned by `openTab()`.
|
|
@@ -42,4 +44,77 @@ declare function voucherToHeader(signed: SignedVoucher): string;
|
|
|
42
44
|
declare function openTab(options: OpenTabOptions): Promise<Tab>;
|
|
43
45
|
declare function resumeTab(_options: ResumeTabOptions): Promise<Tab>;
|
|
44
46
|
|
|
45
|
-
|
|
47
|
+
interface TabOffer {
|
|
48
|
+
/** Seller counterparty (base58) read from the challenge's payTo. */
|
|
49
|
+
payTo: string;
|
|
50
|
+
/** Atomic per-request amount the seller quoted (maxAmountRequired). */
|
|
51
|
+
amountAtomic: string;
|
|
52
|
+
asset: string;
|
|
53
|
+
/** CAIP-2 network from the challenge (x402 v2 form). */
|
|
54
|
+
networkCaip2: string;
|
|
55
|
+
resourceUrl?: string;
|
|
56
|
+
}
|
|
57
|
+
type TabOfferResult = {
|
|
58
|
+
kind: 'offer';
|
|
59
|
+
offer: TabOffer;
|
|
60
|
+
}
|
|
61
|
+
/** The resource answered without demanding payment. `response` is the
|
|
62
|
+
* LIVE probe response — the caller owns consuming (or cancelling) its
|
|
63
|
+
* body, same contract as payAndFetch's unpaid branch. */
|
|
64
|
+
| {
|
|
65
|
+
kind: 'free';
|
|
66
|
+
response: Response;
|
|
67
|
+
} | {
|
|
68
|
+
kind: 'no_tab';
|
|
69
|
+
schemesOffered: string[];
|
|
70
|
+
} | {
|
|
71
|
+
kind: 'error';
|
|
72
|
+
detail: string;
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* Probe a URL and resolve its tab payment offer. Sends the caller's
|
|
76
|
+
* method/headers (and a string body, mirroring payAndFetch's probe rules)
|
|
77
|
+
* WITHOUT any payment attached; a paying caller follows up via
|
|
78
|
+
* payUrlWithTab. Never throws for an expected failure.
|
|
79
|
+
*/
|
|
80
|
+
declare function resolveTabOffer(url: string, init?: RequestInit, fetchImpl?: typeof fetch): Promise<TabOfferResult>;
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Step-3a buyer orchestration: pay a URL through a tab with ZERO seller
|
|
84
|
+
* knowledge. Resolution + lifecycle only — composes resolveTabOffer,
|
|
85
|
+
* openTab, and payAndFetch; no new on-chain or settlement code.
|
|
86
|
+
*
|
|
87
|
+
* The caller owns close(): tabs amortize settle cost across requests, so
|
|
88
|
+
* this function never closes the tab it returns — including when payment
|
|
89
|
+
* FAILS after the tab opened (tab is non-null there; close it to settle
|
|
90
|
+
* whatever streamed and free the freeze).
|
|
91
|
+
*
|
|
92
|
+
* Request count: two unpaid GETs precede the paid one — resolveTabOffer
|
|
93
|
+
* probes to discover the offer, then payAndFetch probes again as part of
|
|
94
|
+
* protocol dispatch. Three requests total per call; sellers see the extra
|
|
95
|
+
* probes as ordinary 402s.
|
|
96
|
+
*/
|
|
97
|
+
|
|
98
|
+
interface PayUrlWithTabOptions {
|
|
99
|
+
vault: VaultAdapter;
|
|
100
|
+
/** Max single-voucher spend (human units) — quotes above this are refused. */
|
|
101
|
+
perUnitCap: HumanAmount;
|
|
102
|
+
/** Max cumulative tab spend (human units). */
|
|
103
|
+
totalCap: HumanAmount;
|
|
104
|
+
sessionDuration?: number;
|
|
105
|
+
facilitatorUrl?: string;
|
|
106
|
+
/**
|
|
107
|
+
* Open-tab registry keyed by counterparty base58. Pass the SAME Map across
|
|
108
|
+
* calls to reuse one open tab per seller instead of re-registering
|
|
109
|
+
* (one tab per (vault, counterparty)). Newly opened tabs are added to it.
|
|
110
|
+
*/
|
|
111
|
+
tabs?: Map<string, Tab>;
|
|
112
|
+
}
|
|
113
|
+
interface PayUrlWithTabResult {
|
|
114
|
+
result: PayResult;
|
|
115
|
+
/** The tab used — caller owns close(). Null when nothing was paid. */
|
|
116
|
+
tab: Tab | null;
|
|
117
|
+
}
|
|
118
|
+
declare function payUrlWithTab(url: string, init: RequestInit | undefined, opts: PayUrlWithTabOptions): Promise<PayUrlWithTabResult>;
|
|
119
|
+
|
|
120
|
+
export { DEFAULT_FACILITATOR_URL, OpenTabOptions, type PayUrlWithTabOptions, type PayUrlWithTabResult, ResumeTabOptions, Tab, type TabOffer, type TabOfferResult, VaultAdapter, atomicToHuman, humanToAtomic, openTab, payUrlWithTab, resolveTabOffer, resumeTab, voucherToHeader };
|
package/dist/tab/index.d.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import { O as OpenTabOptions, T as Tab, R as ResumeTabOptions } from '../types-DEnVPFxF.js';
|
|
2
|
-
export { S as SessionScopeExceededError, b as TabCloseResult, c as TabClosedError, a as TabState, U as UnsupportedNetworkError
|
|
1
|
+
import { O as OpenTabOptions, T as Tab, R as ResumeTabOptions, V as VaultAdapter } from '../types-DEnVPFxF.js';
|
|
2
|
+
export { S as SessionScopeExceededError, b as TabCloseResult, c as TabClosedError, a as TabState, U as UnsupportedNetworkError } from '../types-DEnVPFxF.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-ZjcxOAbW.js';
|
|
5
6
|
export { SessionRegisterMessageArgs, SessionRevokeMessageArgs, VoucherPayloadBytes, buildVoucherMessage, sessionRegisterMessage, sessionRevokeMessage, voucherPayloadMessage } from '@dexterai/vault/messages';
|
|
6
7
|
export { BuildRegisterSessionKeyArgs, BuildRevokeSessionKeyArgs, buildRegisterSessionKeyInstruction, buildRevokeSessionKeyInstruction } from '@dexterai/vault/instructions';
|
|
7
8
|
export { buildSecp256r1VerifyInstruction } from '@dexterai/vault/precompile';
|
|
8
9
|
export { DEXTER_VAULT_PROGRAM_ID, INSTRUCTIONS_SYSVAR_ID, SECP256R1_PROGRAM_ID } from '@dexterai/vault/constants';
|
|
10
|
+
import '../types-xQu1U4xk.js';
|
|
9
11
|
|
|
10
12
|
/**
|
|
11
13
|
* The `Tab` runtime — the live object returned by `openTab()`.
|
|
@@ -42,4 +44,77 @@ declare function voucherToHeader(signed: SignedVoucher): string;
|
|
|
42
44
|
declare function openTab(options: OpenTabOptions): Promise<Tab>;
|
|
43
45
|
declare function resumeTab(_options: ResumeTabOptions): Promise<Tab>;
|
|
44
46
|
|
|
45
|
-
|
|
47
|
+
interface TabOffer {
|
|
48
|
+
/** Seller counterparty (base58) read from the challenge's payTo. */
|
|
49
|
+
payTo: string;
|
|
50
|
+
/** Atomic per-request amount the seller quoted (maxAmountRequired). */
|
|
51
|
+
amountAtomic: string;
|
|
52
|
+
asset: string;
|
|
53
|
+
/** CAIP-2 network from the challenge (x402 v2 form). */
|
|
54
|
+
networkCaip2: string;
|
|
55
|
+
resourceUrl?: string;
|
|
56
|
+
}
|
|
57
|
+
type TabOfferResult = {
|
|
58
|
+
kind: 'offer';
|
|
59
|
+
offer: TabOffer;
|
|
60
|
+
}
|
|
61
|
+
/** The resource answered without demanding payment. `response` is the
|
|
62
|
+
* LIVE probe response — the caller owns consuming (or cancelling) its
|
|
63
|
+
* body, same contract as payAndFetch's unpaid branch. */
|
|
64
|
+
| {
|
|
65
|
+
kind: 'free';
|
|
66
|
+
response: Response;
|
|
67
|
+
} | {
|
|
68
|
+
kind: 'no_tab';
|
|
69
|
+
schemesOffered: string[];
|
|
70
|
+
} | {
|
|
71
|
+
kind: 'error';
|
|
72
|
+
detail: string;
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* Probe a URL and resolve its tab payment offer. Sends the caller's
|
|
76
|
+
* method/headers (and a string body, mirroring payAndFetch's probe rules)
|
|
77
|
+
* WITHOUT any payment attached; a paying caller follows up via
|
|
78
|
+
* payUrlWithTab. Never throws for an expected failure.
|
|
79
|
+
*/
|
|
80
|
+
declare function resolveTabOffer(url: string, init?: RequestInit, fetchImpl?: typeof fetch): Promise<TabOfferResult>;
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Step-3a buyer orchestration: pay a URL through a tab with ZERO seller
|
|
84
|
+
* knowledge. Resolution + lifecycle only — composes resolveTabOffer,
|
|
85
|
+
* openTab, and payAndFetch; no new on-chain or settlement code.
|
|
86
|
+
*
|
|
87
|
+
* The caller owns close(): tabs amortize settle cost across requests, so
|
|
88
|
+
* this function never closes the tab it returns — including when payment
|
|
89
|
+
* FAILS after the tab opened (tab is non-null there; close it to settle
|
|
90
|
+
* whatever streamed and free the freeze).
|
|
91
|
+
*
|
|
92
|
+
* Request count: two unpaid GETs precede the paid one — resolveTabOffer
|
|
93
|
+
* probes to discover the offer, then payAndFetch probes again as part of
|
|
94
|
+
* protocol dispatch. Three requests total per call; sellers see the extra
|
|
95
|
+
* probes as ordinary 402s.
|
|
96
|
+
*/
|
|
97
|
+
|
|
98
|
+
interface PayUrlWithTabOptions {
|
|
99
|
+
vault: VaultAdapter;
|
|
100
|
+
/** Max single-voucher spend (human units) — quotes above this are refused. */
|
|
101
|
+
perUnitCap: HumanAmount;
|
|
102
|
+
/** Max cumulative tab spend (human units). */
|
|
103
|
+
totalCap: HumanAmount;
|
|
104
|
+
sessionDuration?: number;
|
|
105
|
+
facilitatorUrl?: string;
|
|
106
|
+
/**
|
|
107
|
+
* Open-tab registry keyed by counterparty base58. Pass the SAME Map across
|
|
108
|
+
* calls to reuse one open tab per seller instead of re-registering
|
|
109
|
+
* (one tab per (vault, counterparty)). Newly opened tabs are added to it.
|
|
110
|
+
*/
|
|
111
|
+
tabs?: Map<string, Tab>;
|
|
112
|
+
}
|
|
113
|
+
interface PayUrlWithTabResult {
|
|
114
|
+
result: PayResult;
|
|
115
|
+
/** The tab used — caller owns close(). Null when nothing was paid. */
|
|
116
|
+
tab: Tab | null;
|
|
117
|
+
}
|
|
118
|
+
declare function payUrlWithTab(url: string, init: RequestInit | undefined, opts: PayUrlWithTabOptions): Promise<PayUrlWithTabResult>;
|
|
119
|
+
|
|
120
|
+
export { DEFAULT_FACILITATOR_URL, OpenTabOptions, type PayUrlWithTabOptions, type PayUrlWithTabResult, ResumeTabOptions, Tab, type TabOffer, type TabOfferResult, VaultAdapter, atomicToHuman, humanToAtomic, openTab, payUrlWithTab, resolveTabOffer, resumeTab, voucherToHeader };
|
package/dist/tab/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var
|
|
1
|
+
var pe=class extends Error{constructor(t){super(`Network ${t} is not yet supported by @dexterai/x402/tab`);this.network=t;this.name="UnsupportedNetworkError"}},me=class extends Error{constructor(t,r){super(`Session scope exceeded: ${t}${r?` (${r})`:""}`);this.reason=t;this.name="SessionScopeExceededError"}},Q=class extends Error{constructor(t){super(`Tab ${t} is already closed`);this.channelId=t;this.name="TabClosedError"}};import{PublicKey as ht}from"@solana/web3.js";import{bytesToHex as ee}from"@noble/hashes/utils";import Cn from"tweetnacl";import{sessionRegisterMessage as Ot,sessionRevokeMessage as Ut,voucherPayloadMessage as gt,buildVoucherMessage as Bt}from"@dexterai/vault/messages";import{sha256 as Dt}from"@noble/hashes/sha256";function yt(n){let e=new Uint8Array(8);new DataView(e.buffer).setBigUint64(0,n.nonce,!0);let t=new TextEncoder().encode(n.sellerUrl),r=Dt.create();return r.update(n.vaultPda.toBytes()),r.update(t),r.update(e),r.digest()}var Mt=3600,nt="https://x402.dexter.cash",St=6;function Z(n,e=St){if(!/^\d+(\.\d+)?$/.test(n))throw new Error(`amount must be a non-negative decimal string, got "${n}"`);let[t,r=""]=n.split(".");if(r.length>e)throw new Error(`amount "${n}" has more than ${e} decimals`);let a=r.padEnd(e,"0"),s=`${t}${a}`.replace(/^0+(?=\d)/,"");return s===""?"0":s}function Ve(n,e=St){if(!/^\d+$/.test(n))throw new Error(`atomic must be a non-negative integer string, got "${n}"`);let t=n.padStart(e+1,"0"),r=t.slice(0,-e).replace(/^0+(?=\d)/,"")||"0",a=t.slice(-e).replace(/0+$/,"");return a?`${r}.${a}`:r}var rt=class{channelId;network;counterparty;internals;cumulativeAtomic=0n;sequenceNumber=0;closed=!1;lastSignedVoucher=null;previousSignedVoucher=null;constructor(e){this.internals=e,this.channelId=e.channelIdHex,this.network=e.network,this.counterparty=e.counterparty}get state(){let e=this.internals.totalCapAtomic-this.cumulativeAtomic,t=Math.floor(Date.now()/1e3);return{isOpen:!this.closed,spent:Ve(this.cumulativeAtomic.toString()),remaining:Ve(e.toString()),expiresInSec:Math.max(0,this.internals.expiresAtUnix-t)}}async signNextVoucher(e){if(this.closed)throw new Q(this.channelId);let t=BigInt(e);if(t<=0n)throw new Error(`voucher increment must be > 0, got ${e}`);if(t>this.internals.perUnitCapAtomic)throw new me("cap_exceeded",`single voucher increment ${t} exceeds perUnitCap ${this.internals.perUnitCapAtomic}`);let r=this.cumulativeAtomic+t;if(r>this.internals.totalCapAtomic)throw new me("cap_exceeded",`cumulative ${r} would exceed totalCap ${this.internals.totalCapAtomic}`);let a=this.sequenceNumber+1,s={channelId:this.channelId,cumulativeAmount:r.toString(),sequenceNumber:a},o=await this.internals.vault.signWithSession(this.internals.session,s);return this.previousSignedVoucher=this.lastSignedVoucher,this.lastSignedVoucher=o,this.sequenceNumber=a,this.cumulativeAtomic=r,o}rollbackVoucher(e){let t=this.lastSignedVoucher;if(!t||t.payload.sequenceNumber!==e.payload.sequenceNumber||t.payload.cumulativeAmount!==e.payload.cumulativeAmount)return!1;let r=this.previousSignedVoucher;if(r)this.sequenceNumber=r.payload.sequenceNumber,this.cumulativeAtomic=BigInt(r.payload.cumulativeAmount),this.lastSignedVoucher=r;else if(t.payload.sequenceNumber===1)this.sequenceNumber=0,this.cumulativeAtomic=0n,this.lastSignedVoucher=null;else return!1;return this.previousSignedVoucher=null,!0}async stream(e,t){if(this.closed)throw new Q(this.channelId);let r=await this.signNextVoucher(this.internals.perUnitCapAtomic.toString()),a=new Headers(t?.headers);a.set("X-Tab-Voucher",Ke(r)),a.set("Accept","text/event-stream");let s=await fetch(e,{...t,headers:a});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`tab.stream HTTP ${s.status}: ${o.slice(0,500)}`)}if(!s.body)throw new Error("tab.stream response has no body");return Wt(s.body)}async close(){if(this.closed)throw new Q(this.channelId);let e={settleTx:""};return this.lastSignedVoucher&&this.cumulativeAtomic>0n&&(e=await $t(this.internals.facilitatorUrl,this.lastSignedVoucher,this.internals.network)),await this.internals.vault.signCloseTab(this.internals.session,this.channelId,this.cumulativeAtomic.toString()),this.closed=!0,this.internals.session.privateKey.fill(0),{settledAmount:Ve(this.cumulativeAtomic.toString()),...e}}};function Ke(n){return Buffer.from(JSON.stringify({payload:n.payload,sessionPublicKey:ee(n.sessionPublicKey),sessionRegistration:ee(n.sessionRegistration),sessionSignature:ee(n.sessionSignature)}),"utf8").toString("base64")}async function $t(n,e,t){let r=`${n.replace(/\/$/,"")}/tab/settle`,a={channelId:e.payload.channelId,cumulativeAmount:e.payload.cumulativeAmount,sequenceNumber:e.payload.sequenceNumber,sessionPublicKey:ee(e.sessionPublicKey),sessionSignature:ee(e.sessionSignature),sessionRegistration:ee(e.sessionRegistration),network:t},s=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(a)}),o=await s.text();if(!s.ok)throw new Error(`tab settle ${s.status}: ${o.slice(0,500)}`);let i;try{i=JSON.parse(o)}catch{throw new Error(`tab settle returned non-JSON: ${o.slice(0,200)}`)}if(!i.settleTx)throw new Error(`tab settle returned no settleTx: ${o.slice(0,200)}`);let c={settleTx:i.settleTx};return typeof i.grossAmount=="string"&&(c.grossAmount=i.grossAmount),typeof i.feeAmount=="string"&&(c.feeAmount=i.feeAmount),typeof i.netAmount=="string"&&(c.netAmount=i.netAmount),c}async function Lt(n,e,t,r,a){let s=`${n.replace(/\/$/,"")}/tab/open`,o=await fetch(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({buyer_swig_address:e,seller:a,max_amount_atomic:t.toString(),network:r})}),i=await o.json().catch(()=>({}));if(!o.ok||!i.success||!i.armed)throw new Error(`tab_open_unprotected: ${i.error??`http_${o.status}`}`);return{armed:!0,signature:i.signature??""}}async function at(n){if(n.network!==n.vault.network)throw new pe(`options.network (${n.network}) doesn't match vault.network (${n.vault.network})`);if(n.network!=="solana:mainnet")throw new pe(n.network);let e=BigInt(Math.floor(Math.random()*4294967295)),t=new ht(n.vault.vaultPda),r=yt({vaultPda:t,sellerUrl:n.seller,nonce:BigInt(e)}),a=ee(r),s=BigInt(Z(n.perUnitCap)),o=BigInt(Z(n.totalCap));if(s<=0n)throw new Error("perUnitCap must be > 0");if(o<s)throw new Error("totalCap must be >= perUnitCap");if(n.revolvingCapacity!==void 0&&BigInt(Z(n.revolvingCapacity))<=0n)throw new Error("revolvingCapacity must be > 0");let i=n.sessionDuration??Mt,c=Math.floor(Date.now()/1e3)+i,l=Kt(n.seller),m={channelId:a,maxAmountAtomic:o.toString(),revolvingCapacityAtomic:n.revolvingCapacity?Z(n.revolvingCapacity):o.toString(),expiresAtUnix:c,allowedCounterparty:l},f=await n.vault.authorizeSession(m);return await Lt(n.facilitatorUrl??nt,n.vault.swigAddress,o,n.network,l),new rt({vault:n.vault,network:n.network,seller:n.seller,counterparty:l,session:f,channelIdHex:a,channelIdBytes:r,perUnitCapAtomic:s,totalCapAtomic:o,expiresAtUnix:c,facilitatorUrl:n.facilitatorUrl??nt})}async function Vt(n){throw new Error("resumeTab is Phase 3 work. Session keys are memory-only by design; recovery requires reading active_session on chain and re-authorizing. Tracked in dexter-vault roadmap.")}function Kt(n){if(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(n))try{return new ht(n),n}catch{}throw new Error(`seller must be a base58 Solana pubkey for Phase 2 (got "${n}"). URL-based counterparty resolution lands in Phase 3 (seller middleware).`)}async function*Wt(n){let e=n.getReader(),t=new TextDecoder,r="";try{for(;;){let{done:a,value:s}=await e.read();if(a)break;r+=t.decode(s,{stream:!0});let o;for(;(o=r.indexOf(`
|
|
2
2
|
|
|
3
|
-
`))!==-1;){let
|
|
4
|
-
`);yield new TextEncoder().encode(
|
|
5
|
-
`))
|
|
6
|
-
`):null}}import{buildRegisterSessionKeyInstruction as O,buildRevokeSessionKeyInstruction as H,deriveSwigWalletAddress as se}from"@dexterai/vault/instructions";import{buildSecp256r1VerifyInstruction as M}from"@dexterai/vault/precompile";import{DEXTER_VAULT_PROGRAM_ID as B,SECP256R1_PROGRAM_ID as D,INSTRUCTIONS_SYSVAR_ID as q}from"@dexterai/vault/constants";export{y as DEFAULT_FACILITATOR_URL,B as DEXTER_VAULT_PROGRAM_ID,q as INSTRUCTIONS_SYSVAR_ID,D as SECP256R1_PROGRAM_ID,d as SessionScopeExceededError,c as TabClosedError,m as UnsupportedNetworkError,h as atomicToHuman,O as buildRegisterSessionKeyInstruction,H as buildRevokeSessionKeyInstruction,M as buildSecp256r1VerifyInstruction,k as buildVoucherMessage,g as humanToAtomic,E as openTab,K as resumeTab,I as sessionRegisterMessage,R as sessionRevokeMessage,b as voucherPayloadMessage,v as voucherToHeader};
|
|
3
|
+
`))!==-1;){let i=r.slice(0,o);r=r.slice(o+2);let c=qt(i);if(c.eventName==="end")return;if(c.data!==null){let l=c.data.replace(/\\n/g,`
|
|
4
|
+
`);yield new TextEncoder().encode(l)}}}}finally{e.releaseLock()}}function qt(n){let e=null,t=[];for(let r of n.split(`
|
|
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}}import{PublicKey as Jt}from"@solana/web3.js";var At=[{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"}],Ht=new Map(At.map(n=>[n.caip2.toLowerCase(),n])),Ft=new Map(At.map(n=>[n.bare.toLowerCase(),n]));function Ee(n){if(!n)return null;let e=n.toLowerCase(),t=Ht.get(e)||Ft.get(e);return t?{caip2:t.caip2,bare:t.bare,family:t.family}:null}function st(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-(e.length%4||4))%4);return JSON.parse(Buffer.from(t,"base64").toString("utf8"))}function jt(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,a=Ee(String(r.network??""));a&&e.push({scheme:String(r.scheme??"exact"),network:a,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 We(n){let e=n.headers.get("payment-required");if(!e)return null;let t;try{t=st(e)}catch{return null}let r=Array.isArray(t.accepts)?t.accepts:[];return r.length===0?null:{x402Version:2,options:jt(r),resourceUrl:t.resource&&typeof t.resource=="object"?String(t.resource.url??""):void 0}}async function ot(n,e={},t=fetch){let r={method:e.method??"GET",headers:e.headers};typeof e.body=="string"&&(r.body=e.body);let a;try{a=await t(n,r)}catch(i){return{kind:"error",detail:`probe failed: ${i?.message??String(i)}`}}if(a.status!==402)return a.ok?{kind:"free",response:a}:{kind:"error",detail:`probe returned HTTP ${a.status}`};let s=await We(a);if(!s)return{kind:"error",detail:"the 402 carries no x402 v2 PAYMENT-REQUIRED challenge"};let o=s.options.find(i=>i.scheme==="tab"&&i.network.family==="svm");if(!o)return{kind:"no_tab",schemesOffered:s.options.map(i=>i.scheme)};try{new Jt(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:s.resourceUrl}}}var Pe="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",qe="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",He="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",te=Pe,Re=qe,ve=He,ne="eip155:8453",de="eip155:84532",fe="eip155:42161",ge="eip155:137",ye="eip155:10",he="eip155:43114",Se="eip155:56",Ae="eip155:1187947933",be="eip155:324705682",we="eip155:1",re=ne,Fe=de,_e=fe,Ce=ge,ke=ye,Ie=he,Ne=Se,Oe=Ae,Ue=be,Be=we,it="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",bt="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",wt="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",ct="0x55d398326f99059fF775485246999027B3197955",je="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",Je={[Se]:je,[ne]:wt,[de]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[fe]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[ge]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[ye]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[he]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[Ae]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[be]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[we]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},Xe={[ct]:{symbol:"USDT",decimals:18},[je]:{symbol:"USDC",decimals:18}};var J="0x000000000022D473030F116dDEE9F6B43aC78BA3",De="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",Me={[Se]:56,[ne]:8453,[de]:84532,[fe]:42161,[ge]:137,[ye]:10,[he]:43114,[Ae]:1187947933,[be]:324705682,[we]:1},ae={[Pe]:"https://api.dexter.cash/api/solana/rpc",[qe]:"https://api.devnet.solana.com",[He]:"https://api.testnet.solana.com"},O={[Se]:"https://api.dexter.cash/api/evm/bsc/rpc",[ne]:"https://api.dexter.cash/api/base/rpc",[de]:"https://sepolia.base.org",[fe]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[ge]:"https://api.dexter.cash/api/evm/polygon/rpc",[ye]:"https://api.dexter.cash/api/evm/optimism/rpc",[he]:"https://api.dexter.cash/api/evm/avalanche/rpc",[Ae]:"https://skale-base.skalenodes.com/v1/base",[be]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[we]:"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)}};import{PublicKey as se,Connection as lt,TransactionMessage as Xt,VersionedTransaction as Yt,ComputeBudgetProgram as Tt}from"@solana/web3.js";import{getAssociatedTokenAddress as ut,getAccount as zt,createTransferCheckedInstruction as Gt,getMint as Qt,TOKEN_PROGRAM_ID as xt,TOKEN_2022_PROGRAM_ID as Ye}from"@solana/spl-token";var Zt=12e3,en=1;function oe(n){if(!n||typeof n!="object")return!1;let e=n;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var ze=class{name="Solana";networks=[te,Re,ve];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]:ae[e]?ae[e]:e==="solana"?ae[te]:e==="solana-devnet"?ae[Re]:e==="solana-testnet"?ae[ve]:ae[te]}getAddress(e){return oe(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return oe(e)?e.publicKey!==null:!1}async getBalance(e,t,r){if(!oe(t)||!t.publicKey)return 0;let a=r||this.getDefaultRpcUrl(e.network),s=new lt(a,"confirmed"),o=new se(t.publicKey.toBase58()),i=new se(e.asset);try{let l=(await s.getAccountInfo(i,"confirmed"))?.owner.toBase58()===Ye.toBase58()?Ye:xt,m=await ut(i,o,!1,l),f=await zt(s,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(!oe(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let a=r||this.getDefaultRpcUrl(e.network),s=new lt(a,"confirmed"),o=new se(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 se(l.feePayer),d=new se(c),E=new se(i);this.log("Building transaction:",{from:o.toBase58(),to:i,amount:m,asset:c,feePayer:l.feePayer});let p=[];p.push(Tt.setComputeUnitLimit({units:Zt})),p.push(Tt.setComputeUnitPrice({microLamports:en}));let _=await s.getAccountInfo(d,"confirmed");if(!_)throw new Error(`Token mint ${c} not found`);let P=_.owner.toBase58()===Ye.toBase58()?Ye:xt,h=await Qt(s,d,void 0,P);typeof l?.decimals=="number"&&h.decimals!==l.decimals&&this.log(`Decimals mismatch: requirements say ${l.decimals}, mint says ${h.decimals}`);let y=await ut(d,o,!1,P),x=await ut(d,E,!0,P);if(!await s.getAccountInfo(y,"confirmed"))throw new Error(`No token account found for ${c}. Please ensure you have USDC in your wallet.`);if(!await s.getAccountInfo(x,"confirmed"))throw new Error(`Seller token account not found. The seller (${i}) must have a USDC account.`);let W=BigInt(m);p.push(Gt(y,d,x,o,W,h.decimals,[],P));let{blockhash:L}=await s.getLatestBlockhash("confirmed"),Y=new Xt({payerKey:f,recentBlockhash:L,instructions:p}).compileToV0Message(),D=new Yt(Y),g=await t.signTransaction(D);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:L}}}async confirmSettlement(e,t){if(e.kind!=="solana")throw new Error(`SolanaAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`);let r=new lt(t,"confirmed"),a=new se(e.destinationAta),s=await r.getSignaturesForAddress(a,{limit:25});if(s.length===0)return{settled:!1};let o=BigInt(e.amount);for(let i of s){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(a))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 X(n){return new ze(n)}var tn={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"}]},Et=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function ie(n){if(!n||typeof n!="object")return!1;let e=n;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var Ge=class{name="EVM";networks=[Ne,re,Fe,Be,_e,Ce,ke,Ie,Oe,Ue];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]:O[e]?O[e]:e==="base"?O[re]:e==="bsc"?O[Ne]:e==="ethereum"?O[Be]:e==="arbitrum"?O[_e]:e==="polygon"?O[Ce]:e==="optimism"?O[ke]:e==="avalanche"?O[Ie]:e==="skale-base"?O[Oe]:e==="skale-base-sepolia"?O[Ue]:O[re]}getAddress(e){return ie(e)?e.address:null}isConnected(e){return ie(e)?!!e.address:!1}getChainId(e){if(Me[e])return Me[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(!ie(t)||!t.address)return 0;let a=r||this.getDefaultRpcUrl(e.network);try{let s=this.encodeBalanceOf(t.address),o=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:e.asset,data:s},"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(s){throw s}}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",a=e.from.slice(2).toLowerCase().padStart(64,"0"),s=e.nonce.slice(2).toLowerCase().padStart(64,"0"),o=r+a+s,i=await this.ethCall(t,e.asset,o);return{settled:BigInt(i)!==0n}}if(e.kind==="permit2"){let r="0x4fe02b44",a=BigInt(e.nonce),s=a>>8n,o=a&0xffn,i=e.from.slice(2).toLowerCase().padStart(64,"0"),c=s.toString(16).padStart(64,"0"),l=r+i+c,m=await this.ethCall(t,J,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 a=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(!a.ok)throw new Error(`RPC request failed: ${a.status}`);let s=await a.json();if(s.error)throw new Error(`RPC error: ${JSON.stringify(s.error)}`);if(!s.result||s.result==="0x")throw new Error("RPC returned an empty result");return s.result}async buildTransaction(e,t,r){if(!ie(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:a,asset:s,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:a,amount:i,asset:s,network:e.network});let c=this.getChainId(e.network),l={name:o?.name??"USD Coin",version:o?.version??"2",chainId:BigInt(c),verifyingContract:s},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:a,value:i,validAfter:String(E-600),validBefore:String(E+(e.maxTimeoutSeconds||60)),nonce:d},_={from:t.address,to:a,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 P=await t.signTypedData({domain:l,types:m,primaryType:"TransferWithAuthorization",message:_});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:p,signature:P}),signature:P,settlementProbe:{kind:"eip3009",from:t.address,nonce:d,asset:s,chainId:c}}}async buildApprovalTransaction(e,t,r){let{payTo:a,asset:s,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:a,amount:i,asset:s,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,s,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 D=this.calculateApprovalAmount(i,m,o?.approvalStrategy);this.log(`Approving ${D} for ${c} (current allowance: ${d})`);let g=await t.sendTransaction({to:s,data:this.encodeApprove(c,D),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((D,g)=>D*256n+BigInt(g),0n).toString(),_=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(_);let P="0x"+[..._].map(D=>D.toString(16).padStart(2,"0")).join(""),y=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),x=o?.eip712Domain,N=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},U=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"}]},W={from:t.address,to:a,token:s,amount:BigInt(i),fee:BigInt(m),nonce:BigInt(p),deadline:BigInt(y),paymentId:P},L=await t.signTypedData({domain:N,types:U,primaryType:"Payment",message:W});this.log("EIP-712 Payment signature obtained");let Y={from:t.address,to:a,token:s,amount:i,fee:m,nonce:p,deadline:y,paymentId:P,signature:L};return{serialized:JSON.stringify(Y),signature:L}}async buildPermit2Transaction(e,t,r){let{payTo:a,asset:s}=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:a,amount:o,asset:s,network:e.network});let i=r||this.getDefaultRpcUrl(e.network),c=await this.readAllowance(i,s,t.address,J),l;if(c<BigInt(o)){let N=this.encodeApprove(J,Et);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${c})`);let U=this.getChainId(e.network),W=await this.readGasPrice(i),L=await this.readNonce(i,t.address),Y=await t.signTransaction({to:s,data:N,chainId:U,gas:50000n,gasPrice:W,nonce:L});l={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:s,spender:J,amount:Et.toString(),signedTransaction:Y,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${c})`);let U=await t.sendTransaction({to:s,data:N,value:0n});this.log(`Permit2 approval tx sent: ${U}`),await this.waitForReceipt(i,U),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((N,U)=>N*256n+BigInt(U),0n),d=Math.floor(Date.now()/1e3),E=d-600,p=d+(e.maxTimeoutSeconds||300),_=this.getChainId(e.network),P={name:"Permit2",chainId:BigInt(_),verifyingContract:J},h={permitted:{token:s,amount:BigInt(o)},spender:De,nonce:f,deadline:BigInt(p),witness:{to:a,validAfter:BigInt(E)}},y=await t.signTypedData({domain:P,types:tn,primaryType:"PermitWitnessTransferFrom",message:h});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let x={signature:y,permit2Authorization:{from:t.address,permitted:{token:s,amount:o},spender:De,nonce:f.toString(),deadline:String(p),witness:{to:a,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,a){let s="0xdd62ed3e",o=r.slice(2).toLowerCase().padStart(64,"0"),i=a.slice(2).toLowerCase().padStart(64,"0"),c=s+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",a=e.slice(2).toLowerCase().padStart(64,"0"),s=t.toString(16).padStart(64,"0");return r+a+s}async waitForReceipt(e,t,r=3e4){let a=Date.now();for(;Date.now()-a<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(s){if(s instanceof Error&&s.message.includes("reverted"))throw s}await new Promise(s=>setTimeout(s,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 a=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 a.result?parseInt(a.result,16):0}catch{return 0}}calculateApprovalAmount(e,t,r){let a=BigInt(e)+BigInt(t);if(!r||r.mode==="exact")return a;let s=BigInt(r.defaultMultiple??10),o=a*s;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 a}return o}inferDecimals(e){return e.length>12?18:6}};function Te(n){return new Ge(n)}function pt(n){if(n===it||n===bt)return!0;let e=n.toLowerCase();for(let t of Object.values(Je))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(Xe))if(t.toLowerCase()===e)return!0;return!1}function nn(n){return{[Pe]:"Solana",[qe]:"Solana Devnet",[He]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[ne]:"Base",[de]:"Base Sepolia",[we]:"Ethereum",[fe]:"Arbitrum",[ge]:"Polygon",[ye]:"Optimism",[he]:"Avalanche",[Se]:"BSC",[Ae]:"SKALE Base",[be]:"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 Pt(n,e){let t=nn(n);return t===n?e:t}async function rn(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 a={method:e?.method??t.method,headers:r,signal:e?.signal??t.signal,redirect:e?.redirect??t.redirect,credentials:e?.credentials??t.credentials},s=(a.method??"GET").toUpperCase();return e&&"body"in e?a.body=e.body:s!=="GET"&&s!=="HEAD"&&t.body&&(a.body=await t.arrayBuffer()),[t.url,a]}var an=new WeakMap;function Rt(n){let{adapters:e=[X({verbose:n.verbose}),Te({verbose:n.verbose})],wallets:t,wallet:r,preferredNetwork:a,rpcUrls:s={},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(R=>setTimeout(R,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(R=>setTimeout(R,E*Math.pow(2,S))))}throw w}let P=new Map;function h(g){try{let b=new URL(g).host,w=P.get(b);if(w&&w.expiresAt>Date.now()/1e3+10)return w.jwt;w&&P.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,"/"))),R=Math.floor(Date.now()/1e3),v=R+86400,M=Math.min(typeof T.exp=="number"?T.exp:R,v);P.set(w,{jwt:b,expiresAt:M}),p("Access pass cached for",w,"| expires:",new Date(M*1e3).toISOString())}}catch{p("Failed to cache access pass")}}let x=t||{};r&&!x.solana&&oe(r)&&(x.solana=r),r&&!x.evm&&ie(r)&&(x.evm=r);function N(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 R;T.name==="Solana"?R=x.solana:T.name==="EVM"&&(R=x.evm),R&&T.isConnected(R)&&b.push({accept:w,adapter:T,wallet:R})}if(b.length===0)return null;if(a){let w=b.find(S=>S.accept.network===a);if(w)return w}return b[0]}function U(g,b){return Pt(g,b)}function W(g,b){return s[g]||b.getDefaultRpcUrl(g)}async function L(g,b,w,S,T){let R="";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}`);R=`tier=${u.id}`}}else if(l?.preferDuration&&S.ratePerHour)R=`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}`);R=`tier=${u.id}`}let v=R?T.includes("?")?`${T}&${R}`:`${T}?${R}`:T;p("Purchasing access pass:",R||"default tier");let M=w.headers.get("PAYMENT-REQUIRED");if(!M)return null;let B;try{B=JSON.parse(atob(M))}catch{return null}let I=N(B.accepts);if(!I)return null;let{accept:C,adapter:V,wallet:ce}=I;if(V.name==="Solana"&&!C.extra?.feePayer)return null;let q=C.extra?.decimals??(pt(C.asset)?6:void 0);if(typeof q!="number")return null;let xe=C.amount??C.maxAmountRequired;if(!xe)return null;let H=W(C.network,V);try{let u=await V.getBalance(C,ce,H),A=Number(xe)/Math.pow(10,q);if(u<A){let tt=U(C.network,V.name);throw new k("insufficient_balance",`Insufficient balance for access pass on ${tt}. Have $${u.toFixed(4)}, need $${A.toFixed(4)}`)}}catch(u){if(u instanceof k)throw u}let F=await V.buildTransaction(C,ce,H),le;V.name==="EVM"?le=JSON.parse(F.serialized):le={transaction:F.serialized};let z=typeof g=="string"?g:g instanceof URL?g.href:g.url,ue=B.resource;if(typeof B.resource=="string")try{let u=new URL(B.resource,z);["http:","https:"].includes(u.protocol)&&(ue=u.toString())}catch{}else if(B.resource&&typeof B.resource=="object"&&"url"in B.resource){let u=B.resource;try{let A=new URL(u.url,z);["http:","https:"].includes(A.protocol)&&(ue={...u,url:A.toString()})}catch{}}let Le={x402Version:C.x402Version??2,resource:ue,accepted:C,payload:le};F.extensions&&(Le.extensions=F.extensions);let j=btoa(JSON.stringify(Le)),G=await i(v,{...b,method:"POST",headers:{...b?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":j}});if(!G.ok)return p("Pass purchase failed:",G.status),null;let $=G.headers.get("ACCESS-PASS");return $&&(y(T,$),p("Access pass purchased and cached")),G}async function Y(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{P.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 L(g,b,S,u,w);if(A)return A}catch(u){p("Access pass purchase failed, falling back to per-request payment:",u)}}let R=S.headers.get("PAYMENT-REQUIRED");if(!R)throw new k("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let v;try{let u=atob(R);v=JSON.parse(u)}catch{throw new k("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}p("Payment requirements:",v);let M=S.headers.get("X-Quote-Hash");M&&p("Quote hash received:",M);let B=N(v.accepts);if(!B){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:I,adapter:C,wallet:V}=B;if(p(`Using ${C.name} for ${I.network}`),C.name==="Solana"&&!I.extra?.feePayer)throw new k("missing_fee_payer","Solana payment option missing feePayer in extra");let ce=I.extra?.decimals??(pt(I.asset)?6:void 0);if(typeof ce!="number")throw new k("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let q=I.amount??I.maxAmountRequired;if(!q)throw new k("missing_amount","Payment option missing amount");if(o&&BigInt(q)>BigInt(o))throw new k("amount_exceeds_max",`Payment amount ${q} exceeds maximum ${o}`);let xe=W(I.network,C);p("Checking balance...");try{let u=await C.getBalance(I,V,xe),A=Number(q)/Math.pow(10,ce);if(u<A){let tt=U(I.network,C.name);throw new k("insufficient_balance",`Insufficient balance on ${tt}. 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(I))throw new k("payment_rejected","Payment rejected by onPaymentRequired callback");p("Building transaction...");let H=await C.buildTransaction(I,V,xe);p("Transaction signed");let F;C.name==="EVM"?F=JSON.parse(H.serialized):F={transaction:H.serialized};let le=g,z=v.resource;if(typeof v.resource=="string")try{let u=new URL(v.resource,le).toString();u!==v.resource&&p("Resolved relative resource URL:",v.resource,"\u2192",u),z=u}catch{z=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,le).toString();A!==u.url&&(p("Resolved relative resource URL:",u.url,"\u2192",A),z={...u,url:A})}catch{}}let ue={x402Version:I.x402Version??2,resource:z,accepted:I,payload:F};H.extensions&&(ue.extensions=H.extensions);let Le=btoa(JSON.stringify(ue));if(f)try{f(I,H.settlementProbe)}catch{}p("Retrying request with payment...");let j=await _(g,{...b,headers:{...b?.headers||{},"PAYMENT-SIGNATURE":Le,...M?{"X-Quote-Hash":M}:{}}});if(p("Retry response status:",j.status),j.status===402){let u="unknown";try{let A=await j.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 G=j.headers.get("PAYMENT-RESPONSE"),$;if(G)try{$=JSON.parse(atob(G))}catch{}return $??={},$.amountAtomic=q,$.assetDecimals=ce,an.set(j,$),$.extensions&&p("Settlement extensions:",Object.keys($.extensions).join(", ")),j}async function D(g,b){let[w,S]=await rn(g,b);return Y(w,S)}return{fetch:D}}function K(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 $e(n){let e="";try{e=(await n.clone().text()).slice(0,600)}catch{}let t=e.toLowerCase(),r=t.includes("settle")||t.includes("facilitator"),a=e;try{let s=JSON.parse(e),o=[s.error,s.detail,s.message].filter(i=>typeof i=="string"&&i.length>0);o.length>0&&(a=o.join(" \u2014 "))}catch{}return a||(a=`HTTP ${n.status}`),{reason:r?"settlement_failed":"merchant_rejected",detail:`merchant HTTP ${n.status}: ${a}`}}var Qe="Payment authorization was sent, but the merchant did not respond within the timeout. ",Ze=" Do not retry without checking \u2014 inspect the funding wallet for a transfer to the merchant before attempting payment again.";async function et(n,e,t){if(!n)return{confirmed:!1,detail:Qe+"This payment scheme has no on-chain confirmation check, so the SDK cannot verify whether it settled."+Ze};try{if(n.kind==="solana"){let o=X(),i=t??o.getDefaultRpcUrl(e.caip2);if(!o.confirmSettlement)return _t();let c=await o.confirmSettlement(n,i);return c.settled?{confirmed:!0,txSignature:c.txSignature}:vt()}let r=Te(),a=r.getDefaultRpcUrl(e.caip2);if(!r.confirmSettlement)return _t();let s=await r.confirmSettlement(n,a);return s.settled?{confirmed:!0,txSignature:s.txSignature}:vt()}catch(r){return{confirmed:!1,detail:Qe+`On-chain confirmation could not be completed (${K(r)}).`+Ze}}}function vt(){return{confirmed:!1,detail:Qe+"On-chain confirmation found no matching settlement yet \u2014 the payment may still be pending, or may not have settled."+Ze}}function _t(){return{confirmed:!1,detail:Qe+"The chain adapter does not support on-chain confirmation."+Ze}}var sn=new Set(["exact","exact-approval"]);async function on(n,e,t,r){let a;try{a=await r.signNextVoucher(t.amount)}catch{return null}let s=new Headers(e.headers??void 0);s.set("X-Tab-Voucher",Ke(a));let o={method:e.method??"GET",headers:s};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,a),null):i.ok?{ok:!0,paid:!0,response:i,amountPaid:t.amount,network:t.network}:{ok:!1,...await $e(i)}}var Ct={version:2,async parseChallenge(n){return We(n)},async pay(n,e,t,r,a){if(a.tab){let h=t.options.find(y=>y.scheme==="tab"&&y.network.family==="svm"&&y.payTo===a.tab.counterparty);if(h){let y=await on(n,e,h,a.tab);if(y)return y}}let s=t.options.filter(h=>sn.has(h.scheme));if(s.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=s.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=a.timeoutMs??15e3,c=a.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=Rt({wallets:r,preferredNetwork:o.network.caip2,maxAmountAtomic:a.maxAmountAtomic,fetch:globalThis.fetch,onPaymentDispatched:E}),_=e.signal?AbortSignal.any([e.signal,l.signal]):l.signal,P={method:e.method??"GET",headers:e.headers,signal:_};typeof e.body=="string"&&(P.body=e.body);try{let h=await p.fetch(n,P);if(clearTimeout(m),!h.ok)return{ok:!1,...await $e(h)};let y,x=h.headers.get("PAYMENT-RESPONSE");if(x)try{let N=st(x);N&&typeof N.transaction=="string"&&(y=N.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 et(d,o.network,a.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)}}}};import{getAddress as cn}from"viem";var ln={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 un(){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 pn(n,e,t){if(typeof n.signTypedData!="function")throw new Error("EVM wallet does not support signTypedData");let r=Math.floor(Date.now()/1e3),a=String(r-600),s=String(r+(e.maxTimeoutSeconds??60)),o={from:n.address,to:e.payTo,value:e.amount,validAfter:a,validBefore:s,nonce:await un()},i=Me[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:cn(e.asset)},types:ln,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 mt(n,e,t){try{let r;for(let a of n.options){let s=a.network.family==="evm"&&!!e.evm||a.network.family==="svm"&&!!e.solana;if(a.scheme!=="exact"){s&&(r=a.scheme);continue}if(a.network.family==="evm"&&e.evm){let o=await e.evm;return await mn(a,o,t)}if(a.network.family==="svm"&&e.solana){let o=await e.solana;return await dn(a,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:K(r)}}}async function mn(n,e,t){if(t.maxAmountAtomic!==void 0&&BigInt(n.amount)>BigInt(t.maxAmountAtomic))return{ok:!1,reason:"budget_exceeded"};let r=n.extra??{},a=r.name,s=r.version;if(typeof a!="string"||a.length===0||typeof s!="string"||s.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 pn(e,n,o);return{ok:!0,headerValue:Buffer.from(JSON.stringify(i),"utf8").toString("base64"),option:n,settlementProbe:c}}async function dn(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 a=n.network.bare,s={x402Version:1,scheme:n.scheme,network:a,asset:n.asset,payTo:n.payTo,amount:n.amount,maxAmountRequired:n.amount,maxTimeoutSeconds:n.maxTimeoutSeconds??60,extra:r},i=await X().buildTransaction(s,e,t.solanaRpcUrl),c={x402Version:1,scheme:n.scheme,network:a,payload:{transaction:i.serialized}};return{ok:!0,headerValue:Buffer.from(JSON.stringify(c),"utf8").toString("base64"),option:n,settlementProbe:i.settlementProbe}}function fn(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,a=Ee(String(r.network??""));a&&e.push({scheme:String(r.scheme??"exact"),network:a,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 kt={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=fn(t);return r.length===0?null:{x402Version:1,options:r}},async pay(n,e,t,r,a){let s,o=new AbortController,i=!1,c,l;try{let m=a.timeoutMs??15e3;s=setTimeout(()=>o.abort(),m);let f=await mt(t,r,a);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,P={method:e.method,headers:p,signal:_};typeof e.body=="string"&&(P.body=e.body),i=!0,clearTimeout(s);let h=a.responseTimeoutMs??12e4;s=setTimeout(()=>o.abort(),h);let y=await fetch(n,P);return y.ok?{ok:!0,paid:!0,response:y,amountPaid:E.amount,network:E.network,txSignature:gn(y)}:{ok:!1,...await $e(y)}}catch(m){if(m instanceof Error&&m.name==="AbortError"){if(!i)return{ok:!1,reason:"timeout"};let f=await et(c,l.network,a.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:K(m)}}finally{s!==void 0&&clearTimeout(s)}}};function gn(n){let e=n.headers.get("x-payment-response")??n.headers.get("X-PAYMENT-RESPONSE");if(e)try{let t=JSON.parse(Buffer.from(e,"base64").toString("utf8")),r=t.transaction??t.txHash??t.transactionHash;return typeof r=="string"?r:void 0}catch{return}}import*as Nt from"tweetnacl";import{Keypair as Dr,VersionedTransaction as Mr,Transaction as $r}from"@solana/web3.js";var It=Symbol.for("x402:keypair");function dt(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[It];if(r&&r.secretKey&&r.publicKey)return{publicKey:r.publicKey,signMessage:async a=>Nt.sign.detached(a,r.secretKey)}}return null}var yn=[Ct,kt];async function hn(n){let e=dt(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. ${K(t)}`),fetch}}async function ft(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 a;try{a=await(await hn(t))(n,{...e})}catch(s){return{ok:!1,reason:"error",detail:K(s)}}if(a.status!==402)return{ok:!0,paid:!1,response:a};for(let s of yn){let o=await s.parseChallenge(a.clone());if(o)return s.pay(n,e,o,t,r)}return{ok:!1,reason:"no_payment_options"}}async function Sn(n,e={},t){let r=await ot(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:a}=r,s=BigInt(Z(t.perUnitCap));if(BigInt(a.amountAtomic)>s)return{result:{ok:!1,reason:"budget_exceeded",detail:`seller quotes ${a.amountAtomic} atomic; perUnitCap allows ${s}`},tab:null};let o=t.tabs?.get(a.payTo);return(!o||!o.state.isOpen)&&(o=await at({vault:t.vault,network:"solana:mainnet",seller:a.payTo,perUnitCap:t.perUnitCap,totalCap:t.totalCap,sessionDuration:t.sessionDuration,facilitatorUrl:t.facilitatorUrl}),t.tabs?.set(a.payTo,o)),{result:await ft(n,e,{},{tab:o}),tab:o}}import{buildRegisterSessionKeyInstruction as An,buildRevokeSessionKeyInstruction as bn,deriveSwigWalletAddress as sa}from"@dexterai/vault/instructions";import{buildSecp256r1VerifyInstruction as wn}from"@dexterai/vault/precompile";import{DEXTER_VAULT_PROGRAM_ID as Tn,SECP256R1_PROGRAM_ID as xn,INSTRUCTIONS_SYSVAR_ID as En}from"@dexterai/vault/constants";export{nt as DEFAULT_FACILITATOR_URL,Tn as DEXTER_VAULT_PROGRAM_ID,En as INSTRUCTIONS_SYSVAR_ID,xn as SECP256R1_PROGRAM_ID,me as SessionScopeExceededError,Q as TabClosedError,pe as UnsupportedNetworkError,Ve as atomicToHuman,An as buildRegisterSessionKeyInstruction,bn as buildRevokeSessionKeyInstruction,wn as buildSecp256r1VerifyInstruction,Bt as buildVoucherMessage,Z as humanToAtomic,at as openTab,Sn as payUrlWithTab,ot as resolveTabOffer,Vt as resumeTab,Ot as sessionRegisterMessage,Ut as sessionRevokeMessage,gt as voucherPayloadMessage,Ke as voucherToHeader};
|