@dexterai/x402 3.15.0 → 3.17.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 +77 -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 +137 -3
- package/dist/tab/index.d.ts +137 -3
- package/dist/tab/index.js +5 -5
- package/dist/tab/seller/index.cjs +4 -4
- package/dist/tab/seller/index.d.cts +65 -1
- package/dist/tab/seller/index.d.ts +65 -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 Wt=Object.create;var Ye=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var Ht=Object.getOwnPropertyNames;var Ft=Object.getPrototypeOf,jt=Object.prototype.hasOwnProperty;var Jt=(n,e)=>{for(var t in e)Ye(n,t,{get:e[t],enumerable:!0})},wt=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ht(e))!jt.call(n,s)&&s!==t&&Ye(n,s,{get:()=>e[s],enumerable:!(r=qt(e,s))||r.enumerable});return n};var G=(n,e,t)=>(t=n!=null?Wt(Ft(n)):{},wt(e||!n||!n.__esModule?Ye(t,"default",{value:n,enumerable:!0}):t,n)),Xt=n=>wt(Ye({},"__esModule",{value:!0}),n);var En={};Jt(En,{DEFAULT_FACILITATOR_URL:()=>ze,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:()=>ge.buildRegisterSessionKeyInstruction,buildRevokeSessionKeyInstruction:()=>ge.buildRevokeSessionKeyInstruction,buildSecp256r1VerifyInstruction:()=>bt.buildSecp256r1VerifyInstruction,buildVoucherMessage:()=>B.buildVoucherMessage,humanToAtomic:()=>Z,openTab:()=>Ge,payUrlWithTab:()=>Vt,resolveTabOffer:()=>Ae,resolveTabTerms:()=>Kt,resumeTab:()=>Rt,sessionRegisterMessage:()=>B.sessionRegisterMessage,sessionRevokeMessage:()=>B.sessionRevokeMessage,voucherPayloadMessage:()=>B.voucherPayloadMessage,voucherToHeader:()=>Ie});module.exports=Xt(En);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 mt=require("@solana/web3.js"),ee=require("@noble/hashes/utils");var Yt=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 zt=3600,ze="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 s=r.padEnd(e,"0"),a=`${t}${s}`.replace(/^0+(?=\d)/,"");return a===""?"0":a}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",s=t.slice(-e).replace(/0+$/,"");return s?`${r}.${s}`:r}var pt=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 s=this.sequenceNumber+1,a={channelId:this.channelId,cumulativeAmount:r.toString(),sequenceNumber:s},o=await this.internals.vault.signWithSession(this.internals.session,a);return this.previousSignedVoucher=this.lastSignedVoucher,this.lastSignedVoucher=o,this.sequenceNumber=s,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()),s=new Headers(t?.headers);s.set("X-Tab-Voucher",Ie(r)),s.set("Accept","text/event-stream");let a=await fetch(e,{...t,headers:s});if(!a.ok){let o=await a.text().catch(()=>"");throw new Error(`tab.stream HTTP ${a.status}: ${o.slice(0,500)}`)}if(!a.body)throw new Error("tab.stream response has no body");return en(a.body)}async close(){if(this.closed)throw new Q(this.channelId);let e={settleTx:""};return this.lastSignedVoucher&&this.cumulativeAtomic>0n&&(e=await Gt(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 Ie(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 Gt(n,e,t){let r=`${n.replace(/\/$/,"")}/tab/settle`,s={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},a=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)}),o=await a.text();if(!a.ok)throw new Error(`tab settle ${a.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 Qt(n,e,t,r,s){let a=`${n.replace(/\/$/,"")}/tab/open`,o=await fetch(a,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({buyer_swig_address:e,seller:s,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 Ge(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 mt.PublicKey(n.vault.vaultPda),r=xt({vaultPda:t,sellerUrl:n.seller,nonce:BigInt(e)}),s=(0,ee.bytesToHex)(r),a=BigInt(Z(n.perUnitCap)),o=BigInt(Z(n.totalCap));if(a<=0n)throw new Error("perUnitCap must be > 0");if(o<a)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??zt,c=Math.floor(Date.now()/1e3)+i,l=Zt(n.seller),m={channelId:s,maxAmountAtomic:o.toString(),revolvingCapacityAtomic:n.revolvingCapacity?Z(n.revolvingCapacity):o.toString(),expiresAtUnix:c,allowedCounterparty:l},f=await n.vault.authorizeSession(m);return await Qt(n.facilitatorUrl??ze,n.vault.swigAddress,o,n.network,l),new pt({vault:n.vault,network:n.network,seller:n.seller,counterparty:l,session:f,channelIdHex:s,channelIdBytes:r,perUnitCapAtomic:a,totalCapAtomic:o,expiresAtUnix:c,facilitatorUrl:n.facilitatorUrl??ze})}async function Rt(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 Zt(n){if(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(n))try{return new mt.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*en(n){let e=n.getReader(),t=new TextDecoder,r="";try{for(;;){let{done:s,value:a}=await e.read();if(s)break;r+=t.decode(a,{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=tn(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 tn(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 Pt=[{caip2:"eip155:8453",bare:"base",family:"evm"},{caip2:"eip155:1",bare:"ethereum",family:"evm"},{caip2:"eip155:137",bare:"polygon",family:"evm"},{caip2:"eip155:42161",bare:"arbitrum",family:"evm"},{caip2:"eip155:10",bare:"optimism",family:"evm"},{caip2:"eip155:43114",bare:"avalanche",family:"evm"},{caip2:"eip155:56",bare:"bsc",family:"evm"},{caip2:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",bare:"solana",family:"svm"}],nn=new Map(Pt.map(n=>[n.caip2.toLowerCase(),n])),rn=new Map(Pt.map(n=>[n.bare.toLowerCase(),n]));function Ne(n){if(!n)return null;let e=n.toLowerCase(),t=nn.get(e)||rn.get(e);return t?{caip2:t.caip2,bare:t.bare,family:t.family}:null}function dt(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-(e.length%4||4))%4);return JSON.parse(Buffer.from(t,"base64").toString("utf8"))}function sn(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,s=Ne(String(r.network??""));s&&e.push({scheme:String(r.scheme??"exact"),network:s,amount:String(r.amount??r.maxAmountRequired??"0"),asset:String(r.asset??""),payTo:String(r.payTo??""),maxTimeoutSeconds:typeof r.maxTimeoutSeconds=="number"?r.maxTimeoutSeconds:void 0,extra:r.extra&&typeof r.extra=="object"?r.extra:void 0})}return e}async function Qe(n){let e=n.headers.get("payment-required");if(!e)return null;let t;try{t=dt(e)}catch{return null}let r=Array.isArray(t.accepts)?t.accepts:[];return r.length===0?null:{x402Version:2,options:sn(r),resourceUrl:t.resource&&typeof t.resource=="object"?String(t.resource.url??""):void 0}}async function Ae(n,e={},t=fetch){let r={method:e.method??"GET",headers:e.headers};typeof e.body=="string"&&(r.body=e.body);let s;try{s=await t(n,r)}catch(i){return{kind:"error",detail:`probe failed: ${i?.message??String(i)}`}}if(s.status!==402)return s.ok?{kind:"free",response:s}:{kind:"error",detail:`probe returned HTTP ${s.status}`};let a=await Qe(s);if(!a)return{kind:"error",detail:"the 402 carries no x402 v2 PAYMENT-REQUIRED challenge"};let o=a.options.find(i=>i.scheme==="tab"&&i.network.family==="svm");if(!o)return{kind:"no_tab",schemesOffered:a.options.map(i=>i.scheme)};try{new vt.PublicKey(o.payTo)}catch{return{kind:"error",detail:`tab option payTo is not a valid Solana pubkey: "${o.payTo}"`}}return{kind:"offer",offer:{payTo:o.payTo,amountAtomic:o.amount,asset:o.asset,networkCaip2:o.network.caip2,resourceUrl:a.resourceUrl}}}var Oe="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Ze="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",et="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",le=Oe,Ue=Ze,Be=et,ue="eip155:8453",be="eip155:84532",we="eip155:42161",Te="eip155:137",xe="eip155:10",Ee="eip155:43114",Re="eip155:56",Pe="eip155:1187947933",ve="eip155:324705682",_e="eip155:1",pe=ue,tt=be,De=we,Me=Te,$e=xe,Le=Ee,Ve=Re,Ke=Pe,We=ve,qe=_e,He="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",_t="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",Ct="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",ft="0x55d398326f99059fF775485246999027B3197955",nt="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",rt={[Re]:nt,[ue]:Ct,[be]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[we]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[Te]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[xe]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[Ee]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[Pe]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[ve]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[_e]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},st={[ft]:{symbol:"USDT",decimals:18},[nt]:{symbol:"USDC",decimals:18}};var te="0x000000000022D473030F116dDEE9F6B43aC78BA3",Fe="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",je={[Re]:56,[ue]:8453,[be]:84532,[we]:42161,[Te]:137,[xe]:10,[Ee]:43114,[Pe]:1187947933,[ve]:324705682,[_e]:1},me={[Oe]:"https://api.dexter.cash/api/solana/rpc",[Ze]:"https://api.devnet.solana.com",[et]:"https://api.testnet.solana.com"},D={[Re]:"https://api.dexter.cash/api/evm/bsc/rpc",[ue]:"https://api.dexter.cash/api/base/rpc",[be]:"https://sepolia.base.org",[we]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[Te]:"https://api.dexter.cash/api/evm/polygon/rpc",[xe]:"https://api.dexter.cash/api/evm/optimism/rpc",[Ee]:"https://api.dexter.cash/api/evm/avalanche/rpc",[Pe]:"https://skale-base.skalenodes.com/v1/base",[ve]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[_e]:"https://eth.llamarpc.com"};var k=class n extends Error{code;details;constructor(e,t,r){super(t),this.name="X402Error",this.code=e,this.details=r,Object.setPrototypeOf(this,n.prototype)}};var I=require("@solana/web3.js"),N=require("@solana/spl-token");var an=12e3,on=1;function de(n){if(!n||typeof n!="object")return!1;let e=n;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var at=class{name="Solana";networks=[le,Ue,Be];config;log;constructor(e={}){this.config=e,this.log=e.verbose?console.log.bind(console,"[x402:solana]"):()=>{}}canHandle(e){return!!(this.networks.includes(e)||e==="solana"||e==="solana-devnet"||e==="solana-testnet"||e.startsWith("solana:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:me[e]?me[e]:e==="solana"?me[le]:e==="solana-devnet"?me[Ue]:e==="solana-testnet"?me[Be]:me[le]}getAddress(e){return de(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return de(e)?e.publicKey!==null:!1}async getBalance(e,t,r){if(!de(t)||!t.publicKey)return 0;let s=r||this.getDefaultRpcUrl(e.network),a=new I.Connection(s,"confirmed"),o=new I.PublicKey(t.publicKey.toBase58()),i=new I.PublicKey(e.asset);try{let l=(await a.getAccountInfo(i,"confirmed"))?.owner.toBase58()===N.TOKEN_2022_PROGRAM_ID.toBase58()?N.TOKEN_2022_PROGRAM_ID:N.TOKEN_PROGRAM_ID,m=await(0,N.getAssociatedTokenAddress)(i,o,!1,l),f=await(0,N.getAccount)(a,m,void 0,l),d=e.extra?.decimals??6;return Number(f.amount)/Math.pow(10,d)}catch(c){if(c&&typeof c=="object"&&"name"in c&&(c.name==="TokenAccountNotFoundError"||c.name==="TokenInvalidAccountOwnerError"))return 0;throw c}}async buildTransaction(e,t,r){if(!de(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let s=r||this.getDefaultRpcUrl(e.network),a=new I.Connection(s,"confirmed"),o=new I.PublicKey(t.publicKey.toBase58()),{payTo:i,asset:c,extra:l}=e,m=e.amount??e.maxAmountRequired;if(!m)throw new Error("Missing amount in payment requirements");if(!l?.feePayer)throw new Error("Missing feePayer in payment requirements");let f=new I.PublicKey(l.feePayer),d=new I.PublicKey(c),E=new I.PublicKey(i);this.log("Building transaction:",{from:o.toBase58(),to:i,amount:m,asset:c,feePayer:l.feePayer});let p=[];p.push(I.ComputeBudgetProgram.setComputeUnitLimit({units:an})),p.push(I.ComputeBudgetProgram.setComputeUnitPrice({microLamports:on}));let _=await a.getAccountInfo(d,"confirmed");if(!_)throw new Error(`Token mint ${c} not found`);let R=_.owner.toBase58()===N.TOKEN_2022_PROGRAM_ID.toBase58()?N.TOKEN_2022_PROGRAM_ID:N.TOKEN_PROGRAM_ID,h=await(0,N.getMint)(a,d,void 0,R);typeof l?.decimals=="number"&&h.decimals!==l.decimals&&this.log(`Decimals mismatch: requirements say ${l.decimals}, mint says ${h.decimals}`);let y=await(0,N.getAssociatedTokenAddress)(d,o,!1,R),x=await(0,N.getAssociatedTokenAddress)(d,E,!0,R);if(!await a.getAccountInfo(y,"confirmed"))throw new Error(`No token account found for ${c}. Please ensure you have USDC in your wallet.`);if(!await a.getAccountInfo(x,"confirmed"))throw new Error(`Seller token account not found. The seller (${i}) must have a USDC account.`);let j=BigInt(m);p.push((0,N.createTransferCheckedInstruction)(y,d,x,o,j,h.decimals,[],R));let{blockhash:W}=await a.getLatestBlockhash("confirmed"),re=new I.TransactionMessage({payerKey:f,recentBlockhash:W,instructions:p}).compileToV0Message(),L=new I.VersionedTransaction(re),g=await t.signTransaction(L);return this.log("Transaction signed successfully"),{serialized:Buffer.from(g.serialize()).toString("base64"),settlementProbe:{kind:"solana",sourceAta:y.toBase58(),destinationAta:x.toBase58(),asset:c,amount:m,blockhash:W}}}async confirmSettlement(e,t){if(e.kind!=="solana")throw new Error(`SolanaAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`);let r=new I.Connection(t,"confirmed"),s=new I.PublicKey(e.destinationAta),a=await r.getSignaturesForAddress(s,{limit:25});if(a.length===0)return{settled:!1};let o=BigInt(e.amount);for(let i of a){if(i.err)continue;let c=await r.getTransaction(i.signature,{commitment:"confirmed",maxSupportedTransactionVersion:0});if(!c?.meta)continue;let l=c.transaction.message.getAccountKeys().keySegments().flat(),m=c.meta.preTokenBalances??[],f=c.meta.postTokenBalances??[];for(let d of f){if(d.mint!==e.asset)continue;let E=l[d.accountIndex];if(!E||!E.equals(s))continue;let p=m.find(h=>h.accountIndex===d.accountIndex),_=BigInt(p?.uiTokenAmount.amount??"0");if(BigInt(d.uiTokenAmount.amount??"0")-_===o)return{settled:!0,txSignature:i.signature}}}return{settled:!1}}};function ne(n){return new at(n)}var cn={PermitWitnessTransferFrom:[{name:"permitted",type:"TokenPermissions"},{name:"spender",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"witness",type:"Witness"}],TokenPermissions:[{name:"token",type:"address"},{name:"amount",type:"uint256"}],Witness:[{name:"to",type:"address"},{name:"validAfter",type:"uint256"}]},kt=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function fe(n){if(!n||typeof n!="object")return!1;let e=n;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var ot=class{name="EVM";networks=[Ve,pe,tt,qe,De,Me,$e,Le,Ke,We];config;log;constructor(e={}){this.config=e,this.log=e.verbose?console.log.bind(console,"[x402:evm]"):()=>{}}canHandle(e){return!!(this.networks.includes(e)||e==="base"||e==="bsc"||e==="ethereum"||e==="arbitrum"||e==="polygon"||e==="optimism"||e==="avalanche"||e==="skale-base"||e==="skale-base-sepolia"||e.startsWith("eip155:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:D[e]?D[e]:e==="base"?D[pe]:e==="bsc"?D[Ve]:e==="ethereum"?D[qe]:e==="arbitrum"?D[De]:e==="polygon"?D[Me]:e==="optimism"?D[$e]:e==="avalanche"?D[Le]:e==="skale-base"?D[Ke]:e==="skale-base-sepolia"?D[We]:D[pe]}getAddress(e){return fe(e)?e.address:null}isConnected(e){return fe(e)?!!e.address:!1}getChainId(e){if(je[e])return je[e];if(e.startsWith("eip155:")){let t=e.split(":")[1];return parseInt(t,10)}return e==="base"?8453:e==="bsc"?56:e==="ethereum"?1:e==="arbitrum"?42161:8453}async getBalance(e,t,r){if(!fe(t)||!t.address)return 0;let s=r||this.getDefaultRpcUrl(e.network);try{let a=this.encodeBalanceOf(t.address),o=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:e.asset,data:a},"latest"]})});if(!o.ok)throw new Error(`RPC request failed: ${o.status}`);let i=await o.json();if(i.error)throw new Error(`RPC error: ${JSON.stringify(i.error)}`);if(!i.result||i.result==="0x")return 0;let c=BigInt(i.result),l=e.extra?.decimals??6;return Number(c)/Math.pow(10,l)}catch(a){throw a}}encodeBalanceOf(e){let t="0x70a08231",r=e.slice(2).toLowerCase().padStart(64,"0");return t+r}async confirmSettlement(e,t){if(e.kind==="eip3009"){let r="0xe94a0102",s=e.from.slice(2).toLowerCase().padStart(64,"0"),a=e.nonce.slice(2).toLowerCase().padStart(64,"0"),o=r+s+a,i=await this.ethCall(t,e.asset,o);return{settled:BigInt(i)!==0n}}if(e.kind==="permit2"){let r="0x4fe02b44",s=BigInt(e.nonce),a=s>>8n,o=s&0xffn,i=e.from.slice(2).toLowerCase().padStart(64,"0"),c=a.toString(16).padStart(64,"0"),l=r+i+c,m=await this.ethCall(t,te,l);return{settled:(BigInt(m)>>o&1n)===1n}}throw new Error(`EvmAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`)}async ethCall(e,t,r){let s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:r},"latest"]})});if(!s.ok)throw new Error(`RPC request failed: ${s.status}`);let a=await s.json();if(a.error)throw new Error(`RPC error: ${JSON.stringify(a.error)}`);if(!a.result||a.result==="0x")throw new Error("RPC returned an empty result");return a.result}async buildTransaction(e,t,r){if(!fe(t))throw new Error("Invalid EVM wallet");if(!t.address)throw new Error("Wallet not connected");if(e.scheme==="exact-approval")return this.buildApprovalTransaction(e,t,r);if(e.extra?.assetTransferMethod==="permit2")return this.buildPermit2Transaction(e,t,r);let{payTo:s,asset:a,extra:o}=e,i=e.amount??e.maxAmountRequired;if(!i)throw new Error("Missing amount in payment requirements");this.log("Building EVM transaction:",{from:t.address,to:s,amount:i,asset:a,network:e.network});let c=this.getChainId(e.network),l={name:o?.name??"USD Coin",version:o?.version??"2",chainId:BigInt(c),verifyingContract:a},m={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},f=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(f);let d="0x"+[...f].map(y=>y.toString(16).padStart(2,"0")).join(""),E=Math.floor(Date.now()/1e3),p={from:t.address,to:s,value:i,validAfter:String(E-600),validBefore:String(E+(e.maxTimeoutSeconds||60)),nonce:d},_={from:t.address,to:s,value:BigInt(i),validAfter:BigInt(E-600),validBefore:BigInt(E+(e.maxTimeoutSeconds||60)),nonce:d};if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let R=await t.signTypedData({domain:l,types:m,primaryType:"TransferWithAuthorization",message:_});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:p,signature:R}),signature:R,settlementProbe:{kind:"eip3009",from:t.address,nonce:d,asset:a,chainId:c}}}async buildApprovalTransaction(e,t,r){let{payTo:s,asset:a,extra:o}=e,i=e.amount??e.maxAmountRequired;if(!i)throw new Error("Missing amount in payment requirements");let c=o?.facilitatorContract;if(!c)throw new Error("exact-approval scheme requires extra.facilitatorContract from the facilitator. The /supported endpoint should provide this.");if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");this.log("Building approval-based transaction:",{from:t.address,to:s,amount:i,asset:a,network:e.network,facilitatorContract:c});let l=r||this.getDefaultRpcUrl(e.network),m=o?.fee??"0",f=BigInt(i)+BigInt(m),d=await this.readAllowance(l,a,t.address,c);if(d<f){if(!t.sendTransaction)throw new Error("BSC payments require a wallet that supports sendTransaction for the one-time token approval. Use createEvmKeypairWallet() or a browser wallet with transaction support.");let L=this.calculateApprovalAmount(i,m,o?.approvalStrategy);this.log(`Approving ${L} for ${c} (current allowance: ${d})`);let g=await t.sendTransaction({to:a,data:this.encodeApprove(c,L),value:0n});this.log(`Approval tx sent: ${g}`),await this.waitForReceipt(l,g),this.log("Approval confirmed")}else this.log("Sufficient allowance, skipping approval");let E=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(E);let p=[...E].reduce((L,g)=>L*256n+BigInt(g),0n).toString(),_=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(_);let R="0x"+[..._].map(L=>L.toString(16).padStart(2,"0")).join(""),y=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),x=o?.eip712Domain,U=x?{name:x.name,version:x.version,chainId:BigInt(x.chainId),verifyingContract:x.verifyingContract}:{name:"DexterBSCFacilitator",version:"1",chainId:BigInt(this.getChainId(e.network)),verifyingContract:c},M=o?.eip712Types??{Payment:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"token",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"paymentId",type:"bytes32"}]},j={from:t.address,to:s,token:a,amount:BigInt(i),fee:BigInt(m),nonce:BigInt(p),deadline:BigInt(y),paymentId:R},W=await t.signTypedData({domain:U,types:M,primaryType:"Payment",message:j});this.log("EIP-712 Payment signature obtained");let re={from:t.address,to:s,token:a,amount:i,fee:m,nonce:p,deadline:y,paymentId:R,signature:W};return{serialized:JSON.stringify(re),signature:W}}async buildPermit2Transaction(e,t,r){let{payTo:s,asset:a}=e,o=e.amount??e.maxAmountRequired;if(!o)throw new Error("Missing amount in payment requirements");if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");this.log("Building Permit2 transaction:",{from:t.address,to:s,amount:o,asset:a,network:e.network});let i=r||this.getDefaultRpcUrl(e.network),c=await this.readAllowance(i,a,t.address,te),l;if(c<BigInt(o)){let U=this.encodeApprove(te,kt);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${c})`);let M=this.getChainId(e.network),j=await this.readGasPrice(i),W=await this.readNonce(i,t.address),re=await t.signTransaction({to:a,data:U,chainId:M,gas:50000n,gasPrice:j,nonce:W});l={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:a,spender:te,amount:kt.toString(),signedTransaction:re,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${c})`);let M=await t.sendTransaction({to:a,data:U,value:0n});this.log(`Permit2 approval tx sent: ${M}`),await this.waitForReceipt(i,M),this.log("Permit2 approval confirmed")}else throw new Error("Permit2 payments require a wallet that supports signTransaction or sendTransaction for the one-time Permit2 approval. Use createEvmKeypairWallet() or a browser wallet with transaction support.")}else this.log("Sufficient Permit2 allowance, skipping approval");let m=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(m);let f=[...m].reduce((U,M)=>U*256n+BigInt(M),0n),d=Math.floor(Date.now()/1e3),E=d-600,p=d+(e.maxTimeoutSeconds||300),_=this.getChainId(e.network),R={name:"Permit2",chainId:BigInt(_),verifyingContract:te},h={permitted:{token:a,amount:BigInt(o)},spender:Fe,nonce:f,deadline:BigInt(p),witness:{to:s,validAfter:BigInt(E)}},y=await t.signTypedData({domain:R,types:cn,primaryType:"PermitWitnessTransferFrom",message:h});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let x={signature:y,permit2Authorization:{from:t.address,permitted:{token:a,amount:o},spender:Fe,nonce:f.toString(),deadline:String(p),witness:{to:s,validAfter:String(E)}}};return{serialized:JSON.stringify(x),signature:y,extensions:l,settlementProbe:{kind:"permit2",from:t.address,nonce:f.toString(),chainId:_}}}async readAllowance(e,t,r,s){let a="0xdd62ed3e",o=r.slice(2).toLowerCase().padStart(64,"0"),i=s.slice(2).toLowerCase().padStart(64,"0"),c=a+o+i;try{let m=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:c},"latest"]})})).json();return m.error||!m.result||m.result==="0x"?0n:BigInt(m.result)}catch{return 0n}}encodeApprove(e,t){let r="0x095ea7b3",s=e.slice(2).toLowerCase().padStart(64,"0"),a=t.toString(16).padStart(64,"0");return r+s+a}async waitForReceipt(e,t,r=3e4){let s=Date.now();for(;Date.now()-s<r;){try{let o=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionReceipt",params:[t]})})).json();if(o.result){if(o.result.status==="0x0")throw new Error(`Approval transaction reverted: ${t}`);return}}catch(a){if(a instanceof Error&&a.message.includes("reverted"))throw a}await new Promise(a=>setTimeout(a,2e3))}throw new Error(`Approval transaction receipt timeout after ${r}ms: ${t}`)}async readGasPrice(e){try{let r=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_gasPrice",params:[]})})).json();return r.result?BigInt(r.result):50000000n}catch{return 50000000n}}async readNonce(e,t){try{let s=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionCount",params:[t,"latest"]})})).json();return s.result?parseInt(s.result,16):0}catch{return 0}}calculateApprovalAmount(e,t,r){let s=BigInt(e)+BigInt(t);if(!r||r.mode==="exact")return s;let a=BigInt(r.defaultMultiple??10),o=s*a;if(r.maxCapUsd){let i=this.inferDecimals(e),c=BigInt(Math.floor(r.maxCapUsd*Math.pow(10,i)));if(o>c)return c}if(r.exactAboveUsd){let i=this.inferDecimals(e),c=BigInt(Math.floor(r.exactAboveUsd*Math.pow(10,i)));if(BigInt(e)>c)return s}return o}inferDecimals(e){return e.length>12?18:6}};function Ce(n){return new ot(n)}function gt(n){if(n===He||n===_t)return!0;let e=n.toLowerCase();for(let t of Object.values(rt))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(st))if(t.toLowerCase()===e)return!0;return!1}function ln(n){return{[Oe]:"Solana",[Ze]:"Solana Devnet",[et]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[ue]:"Base",[be]:"Base Sepolia",[_e]:"Ethereum",[we]:"Arbitrum",[Te]:"Polygon",[xe]:"Optimism",[Ee]:"Avalanche",[Re]:"BSC",[Pe]:"SKALE Base",[ve]:"SKALE Base Sepolia",base:"Base","base-sepolia":"Base Sepolia",ethereum:"Ethereum",arbitrum:"Arbitrum",polygon:"Polygon",optimism:"Optimism",avalanche:"Avalanche",bsc:"BSC","skale-base":"SKALE Base","skale-base-sepolia":"SKALE Base Sepolia"}[n]||n}function It(n,e){let t=ln(n);return t===n?e:t}async function un(n,e){if(typeof n=="string")return[n,e];if(n instanceof URL)return[n.href,e];let t=n,r=new Headers(t.headers);e?.headers&&new Headers(e.headers).forEach((o,i)=>r.set(i,o));let s={method:e?.method??t.method,headers:r,signal:e?.signal??t.signal,redirect:e?.redirect??t.redirect,credentials:e?.credentials??t.credentials},a=(s.method??"GET").toUpperCase();return e&&"body"in e?s.body=e.body:a!=="GET"&&a!=="HEAD"&&t.body&&(s.body=await t.arrayBuffer()),[t.url,s]}var pn=new WeakMap;function Nt(n){let{adapters:e=[ne({verbose:n.verbose}),Ce({verbose:n.verbose})],wallets:t,wallet:r,preferredNetwork:s,rpcUrls:a={},maxAmountAtomic:o,fetch:i=globalThis.fetch,verbose:c=!1,accessPass:l,onPaymentRequired:m,onPaymentDispatched:f,maxRetries:d=0,retryDelayMs:E=500}=n,p=c?console.log.bind(console,"[x402]"):()=>{};async function _(g,b){let w;for(let S=0;S<=d;S++)try{let T=await i(g,b);if(T.status>=502&&T.status<=504&&S<d){p(`Retry ${S+1}/${d}: server returned ${T.status}`),await new Promise(P=>setTimeout(P,E*Math.pow(2,S)));continue}return T}catch(T){w=T,S<d&&(p(`Retry ${S+1}/${d}: ${T instanceof Error?T.message:"network error"}`),await new Promise(P=>setTimeout(P,E*Math.pow(2,S))))}throw w}let R=new Map;function h(g){try{let b=new URL(g).host,w=R.get(b);if(w&&w.expiresAt>Date.now()/1e3+10)return w.jwt;w&&R.delete(b)}catch{}return null}function y(g,b){try{let w=new URL(g).host,S=b.split(".");if(S.length===3){let T=JSON.parse(atob(S[1].replace(/-/g,"+").replace(/_/g,"/"))),P=Math.floor(Date.now()/1e3),v=P+86400,V=Math.min(typeof T.exp=="number"?T.exp:P,v);R.set(w,{jwt:b,expiresAt:V}),p("Access pass cached for",w,"| expires:",new Date(V*1e3).toISOString())}}catch{p("Failed to cache access pass")}}let x=t||{};r&&!x.solana&&de(r)&&(x.solana=r),r&&!x.evm&&fe(r)&&(x.evm=r);function U(g){let b=[];for(let w of g){let S=w.scheme??"exact";if(S!=="exact"&&S!=="exact-approval")continue;let T=e.find(v=>v.canHandle(w.network));if(!T)continue;let P;T.name==="Solana"?P=x.solana:T.name==="EVM"&&(P=x.evm),P&&T.isConnected(P)&&b.push({accept:w,adapter:T,wallet:P})}if(b.length===0)return null;if(s){let w=b.find(S=>S.accept.network===s);if(w)return w}return b[0]}function M(g,b){return It(g,b)}function j(g,b){return a[g]||b.getDefaultRpcUrl(g)}async function W(g,b,w,S,T){let P="";if(l?.preferTier&&S.tiers){let u=S.tiers.find(A=>A.id===l.preferTier);if(u){if(l.maxSpend&&parseFloat(u.price)>parseFloat(l.maxSpend))throw new k("access_pass_exceeds_max_spend",`Access pass tier "${u.id}" costs $${u.price}, exceeds max spend $${l.maxSpend}`);P=`tier=${u.id}`}}else if(l?.preferDuration&&S.ratePerHour)P=`duration=${l.preferDuration}`;else if(S.tiers&&S.tiers.length>0){let u=S.tiers[0];if(l?.maxSpend&&parseFloat(u.price)>parseFloat(l.maxSpend))throw new k("access_pass_exceeds_max_spend",`Cheapest access pass costs $${u.price}, exceeds max spend $${l?.maxSpend}`);P=`tier=${u.id}`}let v=P?T.includes("?")?`${T}&${P}`:`${T}?${P}`:T;p("Purchasing access pass:",P||"default tier");let V=w.headers.get("PAYMENT-REQUIRED");if(!V)return null;let $;try{$=JSON.parse(atob(V))}catch{return null}let O=U($.accepts);if(!O)return null;let{accept:C,adapter:q,wallet:ye}=O;if(q.name==="Solana"&&!C.extra?.feePayer)return null;let J=C.extra?.decimals??(gt(C.asset)?6:void 0);if(typeof J!="number")return null;let ke=C.amount??C.maxAmountRequired;if(!ke)return null;let X=j(C.network,q);try{let u=await q.getBalance(C,ye,X),A=Number(ke)/Math.pow(10,J);if(u<A){let ut=M(C.network,q.name);throw new k("insufficient_balance",`Insufficient balance for access pass on ${ut}. Have $${u.toFixed(4)}, need $${A.toFixed(4)}`)}}catch(u){if(u instanceof k)throw u}let Y=await q.buildTransaction(C,ye,X),he;q.name==="EVM"?he=JSON.parse(Y.serialized):he={transaction:Y.serialized};let se=typeof g=="string"?g:g instanceof URL?g.href:g.url,Se=$.resource;if(typeof $.resource=="string")try{let u=new URL($.resource,se);["http:","https:"].includes(u.protocol)&&(Se=u.toString())}catch{}else if($.resource&&typeof $.resource=="object"&&"url"in $.resource){let u=$.resource;try{let A=new URL(u.url,se);["http:","https:"].includes(A.protocol)&&(Se={...u,url:A.toString()})}catch{}}let Xe={x402Version:C.x402Version??2,resource:Se,accepted:C,payload:he};Y.extensions&&(Xe.extensions=Y.extensions);let z=btoa(JSON.stringify(Xe)),ae=await i(v,{...b,method:"POST",headers:{...b?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":z}});if(!ae.ok)return p("Pass purchase failed:",ae.status),null;let K=ae.headers.get("ACCESS-PASS");return K&&(y(T,K),p("Access pass purchased and cached")),ae}async function re(g,b){let w=g;if(p("Making request:",w),l){let u=h(w);if(u){p("Using cached access pass");let A=await i(g,{...b,headers:{...b?.headers||{},Authorization:`Bearer ${u}`}});if(A.status!==401&&A.status!==402)return A;p("Cached pass rejected (status",A.status,"), purchasing new pass");try{R.delete(new URL(w).host)}catch{}}}let S=await _(g,b);if(S.status!==402)return S;p("Received 402 Payment Required");let T=S.headers.get("X-ACCESS-PASS-TIERS");if(l&&T){p("Server offers access passes, purchasing...");try{let u=JSON.parse(atob(T)),A=await W(g,b,S,u,w);if(A)return A}catch(u){p("Access pass purchase failed, falling back to per-request payment:",u)}}let P=S.headers.get("PAYMENT-REQUIRED");if(!P)throw new k("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let v;try{let u=atob(P);v=JSON.parse(u)}catch{throw new k("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}p("Payment requirements:",v);let V=S.headers.get("X-Quote-Hash");V&&p("Quote hash received:",V);let $=U(v.accepts);if(!$){let u=v.accepts.map(A=>A.network).join(", ");throw new k("no_matching_payment_option",`No connected wallet for any available network: ${u}`)}let{accept:O,adapter:C,wallet:q}=$;if(p(`Using ${C.name} for ${O.network}`),C.name==="Solana"&&!O.extra?.feePayer)throw new k("missing_fee_payer","Solana payment option missing feePayer in extra");let ye=O.extra?.decimals??(gt(O.asset)?6:void 0);if(typeof ye!="number")throw new k("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let J=O.amount??O.maxAmountRequired;if(!J)throw new k("missing_amount","Payment option missing amount");if(o&&BigInt(J)>BigInt(o))throw new k("amount_exceeds_max",`Payment amount ${J} exceeds maximum ${o}`);let ke=j(O.network,C);p("Checking balance...");try{let u=await C.getBalance(O,q,ke),A=Number(J)/Math.pow(10,ye);if(u<A){let ut=M(O.network,C.name);throw new k("insufficient_balance",`Insufficient balance on ${ut}. Have $${u.toFixed(4)}, need $${A.toFixed(4)}`)}p(`Balance OK: $${u.toFixed(4)} >= $${A.toFixed(4)}`)}catch(u){if(u instanceof k)throw u;p("Balance check failed (RPC error), proceeding with transaction attempt")}if(m&&!await m(O))throw new k("payment_rejected","Payment rejected by onPaymentRequired callback");p("Building transaction...");let X=await C.buildTransaction(O,q,ke);p("Transaction signed");let Y;C.name==="EVM"?Y=JSON.parse(X.serialized):Y={transaction:X.serialized};let he=g,se=v.resource;if(typeof v.resource=="string")try{let u=new URL(v.resource,he).toString();u!==v.resource&&p("Resolved relative resource URL:",v.resource,"\u2192",u),se=u}catch{se=v.resource}else if(v.resource&&typeof v.resource=="object"&&"url"in v.resource){let u=v.resource;try{let A=new URL(u.url,he).toString();A!==u.url&&(p("Resolved relative resource URL:",u.url,"\u2192",A),se={...u,url:A})}catch{}}let Se={x402Version:O.x402Version??2,resource:se,accepted:O,payload:Y};X.extensions&&(Se.extensions=X.extensions);let Xe=btoa(JSON.stringify(Se));if(f)try{f(O,X.settlementProbe)}catch{}p("Retrying request with payment...");let z=await _(g,{...b,headers:{...b?.headers||{},"PAYMENT-SIGNATURE":Xe,...V?{"X-Quote-Hash":V}:{}}});if(p("Retry response status:",z.status),z.status===402){let u="unknown";try{let A=await z.clone().json();u=String(A.error||A.message||JSON.stringify(A)),p("Rejection reason:",u)}catch{}throw new k("payment_rejected",`Payment was rejected by the server: ${u}`)}let ae=z.headers.get("PAYMENT-RESPONSE"),K;if(ae)try{K=JSON.parse(atob(ae))}catch{}return K??={},K.amountAtomic=J,K.assetDecimals=ye,pn.set(z,K),K.extensions&&p("Settlement extensions:",Object.keys(K.extensions).join(", ")),z}async function L(g,b){let[w,S]=await un(g,b);return re(w,S)}return{fetch:L}}function H(n){if(n instanceof Error){if(n.message&&n.message.length>0)return n.message;if(n.name&&n.name.length>0)return n.name}let e=String(n);return e.length>0?e:"unknown error"}async function Je(n){let e="";try{e=(await n.clone().text()).slice(0,600)}catch{}let t=e.toLowerCase(),r=t.includes("settle")||t.includes("facilitator"),s=e;try{let a=JSON.parse(e),o=[a.error,a.detail,a.message].filter(i=>typeof i=="string"&&i.length>0);o.length>0&&(s=o.join(" \u2014 "))}catch{}return s||(s=`HTTP ${n.status}`),{reason:r?"settlement_failed":"merchant_rejected",detail:`merchant HTTP ${n.status}: ${s}`}}var it="Payment authorization was sent, but the merchant did not respond within the timeout. ",ct=" Do not retry without checking \u2014 inspect the funding wallet for a transfer to the merchant before attempting payment again.";async function lt(n,e,t){if(!n)return{confirmed:!1,detail:it+"This payment scheme has no on-chain confirmation check, so the SDK cannot verify whether it settled."+ct};try{if(n.kind==="solana"){let o=ne(),i=t??o.getDefaultRpcUrl(e.caip2);if(!o.confirmSettlement)return Ut();let c=await o.confirmSettlement(n,i);return c.settled?{confirmed:!0,txSignature:c.txSignature}:Ot()}let r=Ce(),s=r.getDefaultRpcUrl(e.caip2);if(!r.confirmSettlement)return Ut();let a=await r.confirmSettlement(n,s);return a.settled?{confirmed:!0,txSignature:a.txSignature}:Ot()}catch(r){return{confirmed:!1,detail:it+`On-chain confirmation could not be completed (${H(r)}).`+ct}}}function Ot(){return{confirmed:!1,detail:it+"On-chain confirmation found no matching settlement yet \u2014 the payment may still be pending, or may not have settled."+ct}}function Ut(){return{confirmed:!1,detail:it+"The chain adapter does not support on-chain confirmation."+ct}}var mn=new Set(["exact","exact-approval"]);async function dn(n,e,t,r){let s;try{s=await r.signNextVoucher(t.amount)}catch{return null}let a=new Headers(e.headers??void 0);a.set("X-Tab-Voucher",Ie(s));let o={method:e.method??"GET",headers:a};e.signal&&(o.signal=e.signal),typeof e.body=="string"&&(o.body=e.body);let i;try{i=await fetch(n,o)}catch(c){return{ok:!1,reason:"error",detail:c?.message??String(c)}}return i.status===402?(r.rollbackVoucher?.call(r,s),null):i.ok?{ok:!0,paid:!0,response:i,amountPaid:t.amount,network:t.network}:{ok:!1,...await Je(i)}}var Bt={version:2,async parseChallenge(n){return Qe(n)},async pay(n,e,t,r,s){if(s.tab){let h=t.options.find(y=>y.scheme==="tab"&&y.network.family==="svm"&&y.payTo===s.tab.counterparty);if(h){let y=await dn(n,e,h,s.tab);if(y)return y}}let a=t.options.filter(h=>mn.has(h.scheme));if(a.length===0)return{ok:!1,reason:"no_payment_options",detail:`no generically payable scheme offered (got: ${t.options.map(h=>h.scheme).join(", ")})`};let o=a.find(h=>h.network.family==="evm"?!!r.evm:h.network.family==="svm"?!!r.solana:!1);if(!o)return{ok:!1,reason:"unsupported_network"};let i=s.timeoutMs??15e3,c=s.responseTimeoutMs??12e4,l=new AbortController,m=setTimeout(()=>l.abort(),i),f=!1,d,E=(h,y)=>{f=!0,d=y,clearTimeout(m),m=setTimeout(()=>l.abort(),c)},p=Nt({wallets:r,preferredNetwork:o.network.caip2,maxAmountAtomic:s.maxAmountAtomic,fetch:globalThis.fetch,onPaymentDispatched:E}),_=e.signal?AbortSignal.any([e.signal,l.signal]):l.signal,R={method:e.method??"GET",headers:e.headers,signal:_};typeof e.body=="string"&&(R.body=e.body);try{let h=await p.fetch(n,R);if(clearTimeout(m),!h.ok)return{ok:!1,...await Je(h)};let y,x=h.headers.get("PAYMENT-RESPONSE");if(x)try{let U=dt(x);U&&typeof U.transaction=="string"&&(y=U.transaction)}catch{}return{ok:!0,paid:!0,response:h,amountPaid:o.amount,network:o.network,txSignature:y}}catch(h){clearTimeout(m);let y=h;if(y?.name==="AbortError"){if(!f)return{ok:!1,reason:"timeout"};let x=await lt(d,o.network,s.solanaRpcUrl);return x.confirmed?{ok:!0,paid:!0,response:void 0,amountPaid:o.amount,network:o.network,txSignature:x.txSignature}:{ok:!1,reason:"payment_unconfirmed",detail:x.detail}}return{ok:!1,reason:"error",detail:y?.message??String(h)}}}};var Dt=require("viem");var fn={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]};async function gn(){let n=globalThis.crypto??(await import("crypto")).webcrypto,e=new Uint8Array(32);return n.getRandomValues(e),"0x"+Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}async function yn(n,e,t){if(typeof n.signTypedData!="function")throw new Error("EVM wallet does not support signTypedData");let r=Math.floor(Date.now()/1e3),s=String(r-600),a=String(r+(e.maxTimeoutSeconds??60)),o={from:n.address,to:e.payTo,value:e.amount,validAfter:s,validBefore:a,nonce:await gn()},i=je[e.network.caip2];if(i===void 0)throw new Error(`unknown chain id for network ${e.network.caip2}`);let c=e.extra,l=await n.signTypedData({domain:{name:c.name,version:c.version,chainId:i,verifyingContract:(0,Dt.getAddress)(e.asset)},types:fn,primaryType:"TransferWithAuthorization",message:o});return{payment:{x402Version:1,scheme:e.scheme,network:t,payload:{signature:l,authorization:o}},settlementProbe:{kind:"eip3009",from:o.from,nonce:o.nonce,asset:e.asset,chainId:i}}}async function yt(n,e,t){try{let r;for(let s of n.options){let a=s.network.family==="evm"&&!!e.evm||s.network.family==="svm"&&!!e.solana;if(s.scheme!=="exact"){a&&(r=s.scheme);continue}if(s.network.family==="evm"&&e.evm){let o=await e.evm;return await hn(s,o,t)}if(s.network.family==="svm"&&e.solana){let o=await e.solana;return await Sn(s,o,t)}}return r!==void 0?{ok:!1,reason:"merchant_rejected",detail:`v1 supports only the 'exact' scheme, got '${r}'`}:{ok:!1,reason:"unsupported_network"}}catch(r){return{ok:!1,reason:"error",detail:H(r)}}}async function hn(n,e,t){if(t.maxAmountAtomic!==void 0&&BigInt(n.amount)>BigInt(t.maxAmountAtomic))return{ok:!1,reason:"budget_exceeded"};let r=n.extra??{},s=r.name,a=r.version;if(typeof s!="string"||s.length===0||typeof a!="string"||a.length===0)return{ok:!1,reason:"merchant_rejected",detail:"v1 challenge missing exact-scheme EIP-712 domain (extra.name / extra.version)"};let o=n.network.bare,{payment:i,settlementProbe:c}=await yn(e,n,o);return{ok:!0,headerValue:Buffer.from(JSON.stringify(i),"utf8").toString("base64"),option:n,settlementProbe:c}}async function Sn(n,e,t){if(t.maxAmountAtomic!==void 0&&BigInt(n.amount)>BigInt(t.maxAmountAtomic))return{ok:!1,reason:"budget_exceeded"};if(n.scheme!=="exact")return{ok:!1,reason:"merchant_rejected",detail:`v1 SVM supports only the 'exact' scheme, got '${n.scheme}'`};let r=n.extra??{};if(typeof r.feePayer!="string"||r.feePayer.length===0)return{ok:!1,reason:"merchant_rejected",detail:"v1 SVM challenge missing extra.feePayer (required as the transaction fee payer)"};let s=n.network.bare,a={x402Version:1,scheme:n.scheme,network:s,asset:n.asset,payTo:n.payTo,amount:n.amount,maxAmountRequired:n.amount,maxTimeoutSeconds:n.maxTimeoutSeconds??60,extra:r},i=await ne().buildTransaction(a,e,t.solanaRpcUrl),c={x402Version:1,scheme:n.scheme,network:s,payload:{transaction:i.serialized}};return{ok:!0,headerValue:Buffer.from(JSON.stringify(c),"utf8").toString("base64"),option:n,settlementProbe:i.settlementProbe}}function An(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,s=Ne(String(r.network??""));s&&e.push({scheme:String(r.scheme??"exact"),network:s,amount:String(r.maxAmountRequired??r.amount??"0"),asset:String(r.asset??""),payTo:String(r.payTo??""),maxTimeoutSeconds:typeof r.maxTimeoutSeconds=="number"?r.maxTimeoutSeconds:void 0,extra:r.extra&&typeof r.extra=="object"?r.extra:void 0})}return e}var Mt={version:1,async parseChallenge(n){if(n.headers.get("payment-required"))return null;let e;try{e=await n.clone().json()}catch{return null}let t=Array.isArray(e.accepts)?e.accepts:[];if(t.length===0)return null;let r=An(t);return r.length===0?null:{x402Version:1,options:r}},async pay(n,e,t,r,s){let a,o=new AbortController,i=!1,c,l;try{let m=s.timeoutMs??15e3;a=setTimeout(()=>o.abort(),m);let f=await yt(t,r,s);if(!f.ok)return{ok:!1,reason:f.reason,detail:f.detail};let d=f.headerValue,E=f.option;l=E,c=f.settlementProbe;let p=new Headers(e.headers??void 0);p.set("X-PAYMENT",d);let _=e.signal!=null?AbortSignal.any([e.signal,o.signal]):o.signal,R={method:e.method,headers:p,signal:_};typeof e.body=="string"&&(R.body=e.body),i=!0,clearTimeout(a);let h=s.responseTimeoutMs??12e4;a=setTimeout(()=>o.abort(),h);let y=await fetch(n,R);return y.ok?{ok:!0,paid:!0,response:y,amountPaid:E.amount,network:E.network,txSignature:bn(y)}:{ok:!1,...await Je(y)}}catch(m){if(m instanceof Error&&m.name==="AbortError"){if(!i)return{ok:!1,reason:"timeout"};let f=await lt(c,l.network,s.solanaRpcUrl);return f.confirmed?{ok:!0,paid:!0,response:void 0,amountPaid:l.amount,network:l.network,txSignature:f.txSignature}:{ok:!1,reason:"payment_unconfirmed",detail:f.detail}}return{ok:!1,reason:"error",detail:H(m)}}finally{a!==void 0&&clearTimeout(a)}}};function bn(n){let e=n.headers.get("x-payment-response")??n.headers.get("X-PAYMENT-RESPONSE");if(e)try{let t=JSON.parse(Buffer.from(e,"base64").toString("utf8")),r=t.transaction??t.txHash??t.transactionHash;return typeof r=="string"?r:void 0}catch{return}}var Lt=G(require("tweetnacl"),1);var ht=require("@solana/web3.js"),$t=Symbol.for("x402:keypair");function St(n){let e=n.evm;if(e&&typeof e.signMessage=="function"&&typeof e.address=="string")return{address:e.address,signMessage:e.signMessage};let t=n.solana;if(t){let r=t[$t];if(r&&r.secretKey&&r.publicKey)return{publicKey:r.publicKey,signMessage:async s=>Lt.sign.detached(s,r.secretKey)}}return null}var wn=[Bt,Mt];async function Tn(n){let e=St(n);if(!e)return fetch;try{return(await import("@x402/extensions/sign-in-with-x")).wrapFetchWithSIWx(fetch,e)}catch(t){return console.warn(`[x402] SIW-X unavailable \u2014 @x402/extensions failed to load; SIW-X merchants will not authenticate. ${H(t)}`),fetch}}async function At(n,e,t,r){if(e.body!==void 0&&e.body!==null&&typeof e.body!="string")return{ok:!1,reason:"error",detail:"payAndFetch requires a string body; non-string bodies (Buffer, FormData, URLSearchParams, ReadableStream) cannot be safely re-sent on the paid retry"};let s;try{s=await(await Tn(t))(n,{...e})}catch(a){return{ok:!1,reason:"error",detail:H(a)}}if(s.status!==402)return{ok:!0,paid:!1,response:s};for(let a of wn){let o=await a.parseChallenge(s.clone());if(o)return a.pay(n,e,o,t,r)}return{ok:!1,reason:"no_payment_options"}}async function Vt(n,e={},t){let r=await Ae(n,e);if(r.kind==="free")return{result:{ok:!0,paid:!1,response:r.response},tab:null};if(r.kind==="no_tab")return{result:{ok:!1,reason:"no_payment_options",detail:`no tab option offered (schemes: ${r.schemesOffered.join(", ")})`},tab:null};if(r.kind==="error")return{result:{ok:!1,reason:"error",detail:r.detail},tab:null};let{offer:s}=r,a=BigInt(Z(t.perUnitCap));if(BigInt(s.amountAtomic)>a)return{result:{ok:!1,reason:"budget_exceeded",detail:`seller quotes ${s.amountAtomic} atomic; perUnitCap allows ${a}`},tab:null};let o=t.tabs?.get(s.payTo);return(!o||!o.state.isOpen)&&(o=await Ge({vault:t.vault,network:"solana:mainnet",seller:s.payTo,perUnitCap:t.perUnitCap,totalCap:t.totalCap,sessionDuration:t.sessionDuration,facilitatorUrl:t.facilitatorUrl}),t.tabs?.set(s.payTo,o)),{result:await At(n,e,{},{tab:o}),tab:o}}var ge=require("@dexterai/vault/instructions"),bt=require("@dexterai/vault/precompile"),F=require("@dexterai/vault/constants");function xn(n){return{counterparty:n.payTo,perRequest:{atomic:n.amountAtomic,human:ce(n.amountAtomic)},asset:n.asset,network:{caip2:n.networkCaip2},scheme:"tab",settlement:{custody:"non-custodial",protection:"freeze",settleOn:"close"},credit:null,...n.resourceUrl!==void 0?{resourceUrl:n.resourceUrl}:{}}}async function Kt(n,e={},t={}){let r=t.cache?.get(n);if(r)return{kind:"terms",terms:r};let s=await Ae(n,e,t.fetchImpl??fetch);if(s.kind!=="offer")return s;if(s.offer.asset!==He)return{kind:"error",detail:`tab offer asset is not USDC ("${s.offer.asset}"); refusing to render a human price`};let a=xn(s.offer);return t.cache?.set(n,a),{kind:"terms",terms:a}}0&&(module.exports={DEFAULT_FACILITATOR_URL,DEXTER_VAULT_PROGRAM_ID,INSTRUCTIONS_SYSVAR_ID,SECP256R1_PROGRAM_ID,SessionScopeExceededError,TabClosedError,UnsupportedNetworkError,atomicToHuman,buildRegisterSessionKeyInstruction,buildRevokeSessionKeyInstruction,buildSecp256r1VerifyInstruction,buildVoucherMessage,humanToAtomic,openTab,payUrlWithTab,resolveTabOffer,resolveTabTerms,resumeTab,sessionRegisterMessage,sessionRevokeMessage,voucherPayloadMessage,voucherToHeader});
|
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,136 @@ 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
|
+
interface TabTerms {
|
|
121
|
+
/** Seller counterparty (base58) — read off the wire, never caller-supplied. */
|
|
122
|
+
counterparty: string;
|
|
123
|
+
/**
|
|
124
|
+
* Per-request price the seller quoted. `human` is USDC-denominated
|
|
125
|
+
* (6 decimals) — guaranteed by the USDC-only guard in resolveTabTerms;
|
|
126
|
+
* a non-USDC tab offer resolves to kind 'error', never a mispriced human
|
|
127
|
+
* figure. `atomic` is always authoritative.
|
|
128
|
+
*/
|
|
129
|
+
perRequest: {
|
|
130
|
+
atomic: string;
|
|
131
|
+
human: string;
|
|
132
|
+
};
|
|
133
|
+
asset: string;
|
|
134
|
+
network: {
|
|
135
|
+
caip2: string;
|
|
136
|
+
};
|
|
137
|
+
scheme: 'tab';
|
|
138
|
+
/**
|
|
139
|
+
* How a Dexter tab settles — properties of scheme 'tab' as shipped, not
|
|
140
|
+
* seller-configurable: openTab is fail-closed on freeze arming (the buyer
|
|
141
|
+
* cannot drain mid-tab), funds stay in the buyer's vault until settle
|
|
142
|
+
* (non-custodial), and settlement happens at tab close.
|
|
143
|
+
*/
|
|
144
|
+
settlement: {
|
|
145
|
+
custody: 'non-custodial';
|
|
146
|
+
protection: 'freeze';
|
|
147
|
+
settleOn: 'close';
|
|
148
|
+
};
|
|
149
|
+
/** Credit terms (Product 2). Reserved; always null today. */
|
|
150
|
+
credit: null;
|
|
151
|
+
resourceUrl?: string;
|
|
152
|
+
}
|
|
153
|
+
type TabTermsResult = {
|
|
154
|
+
kind: 'terms';
|
|
155
|
+
terms: TabTerms;
|
|
156
|
+
}
|
|
157
|
+
/** Resource answered without demanding payment; caller owns the live body. */
|
|
158
|
+
| {
|
|
159
|
+
kind: 'free';
|
|
160
|
+
response: Response;
|
|
161
|
+
} | {
|
|
162
|
+
kind: 'no_tab';
|
|
163
|
+
schemesOffered: string[];
|
|
164
|
+
} | {
|
|
165
|
+
kind: 'error';
|
|
166
|
+
detail: string;
|
|
167
|
+
};
|
|
168
|
+
interface ResolveTabTermsOptions {
|
|
169
|
+
/** Caller-owned cache keyed by URL. Only 'terms' results are cached. */
|
|
170
|
+
cache?: Map<string, TabTerms>;
|
|
171
|
+
fetchImpl?: typeof fetch;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Resolve a URL's tab terms without paying. Never throws for expected
|
|
175
|
+
* failures (same contract as resolveTabOffer).
|
|
176
|
+
*/
|
|
177
|
+
declare function resolveTabTerms(url: string, init?: RequestInit, opts?: ResolveTabTermsOptions): Promise<TabTermsResult>;
|
|
178
|
+
|
|
179
|
+
export { DEFAULT_FACILITATOR_URL, OpenTabOptions, type PayUrlWithTabOptions, type PayUrlWithTabResult, type ResolveTabTermsOptions, ResumeTabOptions, Tab, type TabOffer, type TabOfferResult, type TabTerms, type TabTermsResult, VaultAdapter, atomicToHuman, humanToAtomic, openTab, payUrlWithTab, resolveTabOffer, resolveTabTerms, 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,136 @@ 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
|
+
interface TabTerms {
|
|
121
|
+
/** Seller counterparty (base58) — read off the wire, never caller-supplied. */
|
|
122
|
+
counterparty: string;
|
|
123
|
+
/**
|
|
124
|
+
* Per-request price the seller quoted. `human` is USDC-denominated
|
|
125
|
+
* (6 decimals) — guaranteed by the USDC-only guard in resolveTabTerms;
|
|
126
|
+
* a non-USDC tab offer resolves to kind 'error', never a mispriced human
|
|
127
|
+
* figure. `atomic` is always authoritative.
|
|
128
|
+
*/
|
|
129
|
+
perRequest: {
|
|
130
|
+
atomic: string;
|
|
131
|
+
human: string;
|
|
132
|
+
};
|
|
133
|
+
asset: string;
|
|
134
|
+
network: {
|
|
135
|
+
caip2: string;
|
|
136
|
+
};
|
|
137
|
+
scheme: 'tab';
|
|
138
|
+
/**
|
|
139
|
+
* How a Dexter tab settles — properties of scheme 'tab' as shipped, not
|
|
140
|
+
* seller-configurable: openTab is fail-closed on freeze arming (the buyer
|
|
141
|
+
* cannot drain mid-tab), funds stay in the buyer's vault until settle
|
|
142
|
+
* (non-custodial), and settlement happens at tab close.
|
|
143
|
+
*/
|
|
144
|
+
settlement: {
|
|
145
|
+
custody: 'non-custodial';
|
|
146
|
+
protection: 'freeze';
|
|
147
|
+
settleOn: 'close';
|
|
148
|
+
};
|
|
149
|
+
/** Credit terms (Product 2). Reserved; always null today. */
|
|
150
|
+
credit: null;
|
|
151
|
+
resourceUrl?: string;
|
|
152
|
+
}
|
|
153
|
+
type TabTermsResult = {
|
|
154
|
+
kind: 'terms';
|
|
155
|
+
terms: TabTerms;
|
|
156
|
+
}
|
|
157
|
+
/** Resource answered without demanding payment; caller owns the live body. */
|
|
158
|
+
| {
|
|
159
|
+
kind: 'free';
|
|
160
|
+
response: Response;
|
|
161
|
+
} | {
|
|
162
|
+
kind: 'no_tab';
|
|
163
|
+
schemesOffered: string[];
|
|
164
|
+
} | {
|
|
165
|
+
kind: 'error';
|
|
166
|
+
detail: string;
|
|
167
|
+
};
|
|
168
|
+
interface ResolveTabTermsOptions {
|
|
169
|
+
/** Caller-owned cache keyed by URL. Only 'terms' results are cached. */
|
|
170
|
+
cache?: Map<string, TabTerms>;
|
|
171
|
+
fetchImpl?: typeof fetch;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Resolve a URL's tab terms without paying. Never throws for expected
|
|
175
|
+
* failures (same contract as resolveTabOffer).
|
|
176
|
+
*/
|
|
177
|
+
declare function resolveTabTerms(url: string, init?: RequestInit, opts?: ResolveTabTermsOptions): Promise<TabTermsResult>;
|
|
178
|
+
|
|
179
|
+
export { DEFAULT_FACILITATOR_URL, OpenTabOptions, type PayUrlWithTabOptions, type PayUrlWithTabResult, type ResolveTabTermsOptions, ResumeTabOptions, Tab, type TabOffer, type TabOfferResult, type TabTerms, type TabTermsResult, VaultAdapter, atomicToHuman, humanToAtomic, openTab, payUrlWithTab, resolveTabOffer, resolveTabTerms, resumeTab, voucherToHeader };
|