@dexterai/x402 5.3.3 → 5.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- var x=class extends Error{constructor(r,n){super(`Invalid voucher: ${r}${n?` (${n})`:""}`);this.reason=r;this.name="InvalidVoucherError"}};import{promises as K}from"fs";import{join as Qe,dirname as et}from"path";var Le=new Map;function T(t,e){let n=(Le.get(t)??Promise.resolve()).then(()=>e(),()=>e());return Le.set(t,n.then(()=>{},()=>{})),n}var M=class{map=new Map;async get(e){return this.map.get(e)??null}async set(e,r){this.map.set(e,r)}async delete(e){this.map.delete(e)}async tryAcquireLease(e,r){return T(e,async()=>{let n=this.map.get(e),i=Date.now();if(n?.lease&&n.lease.heldUntilUnixMs>i)return!1;let s=n??{lastVoucher:null,deliveredCumulativeAtomic:"0",lastCrystallizedCumulativeAtomic:"0"};return this.map.set(e,{...s,lease:{heldUntilUnixMs:i+r}}),!0})}async releaseLease(e){await T(e,async()=>{let r=this.map.get(e);r&&this.map.set(e,{...r,lease:void 0})})}};function de(t){let e="";for(let r of t)e+=r.toString(16).padStart(2,"0");return e}function pe(t){if(t.length%2!==0)throw new Error(`hex length must be even, got ${t.length}`);let e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(t.substr(r*2,2),16);return e}function he(t){return Be(t)}function ye(t){return Ke(t)}function Be(t){return{lastVoucher:t.lastVoucher?{payload:t.lastVoucher.payload,sessionPublicKey:de(t.lastVoucher.sessionPublicKey),sessionRegistration:de(t.lastVoucher.sessionRegistration),sessionSignature:de(t.lastVoucher.sessionSignature)}:null,deliveredCumulativeAtomic:t.deliveredCumulativeAtomic,lastCrystallizedCumulativeAtomic:t.lastCrystallizedCumulativeAtomic,gateRefusedCumulativeAtomic:t.gateRefusedCumulativeAtomic,onChain:t.onChain,lease:t.lease}}function Ke(t){return{lastVoucher:t.lastVoucher?{payload:t.lastVoucher.payload,sessionPublicKey:pe(t.lastVoucher.sessionPublicKey),sessionRegistration:pe(t.lastVoucher.sessionRegistration),sessionSignature:pe(t.lastVoucher.sessionSignature)}:null,deliveredCumulativeAtomic:t.deliveredCumulativeAtomic,lastCrystallizedCumulativeAtomic:t.lastCrystallizedCumulativeAtomic??"0",gateRefusedCumulativeAtomic:t.gateRefusedCumulativeAtomic,onChain:t.onChain,lease:t.lease}}var ge=class{constructor(e){this.dir=e}pathFor(e){if(!/^[a-z0-9_-]+$/i.test(e))throw new Error(`unsafe channelId for filesystem: ${e}`);return Qe(this.dir,`${e}.json`)}async get(e){try{let r=await K.readFile(this.pathFor(e),"utf8");return Ke(JSON.parse(r))}catch(r){if(r?.code==="ENOENT")return null;throw r}}async set(e,r){let n=this.pathFor(e);await K.mkdir(et(n),{recursive:!0});let i=`${n}.tmp`;await K.writeFile(i,JSON.stringify(Be(r))),await K.rename(i,n)}async delete(e){try{await K.unlink(this.pathFor(e))}catch(r){if(r?.code!=="ENOENT")throw r}}async tryAcquireLease(e,r){return T(e,async()=>{let n=await this.get(e),i=Date.now();if(n?.lease&&n.lease.heldUntilUnixMs>i)return!1;let s=n??{lastVoucher:null,deliveredCumulativeAtomic:"0",lastCrystallizedCumulativeAtomic:"0"};return await this.set(e,{...s,lease:{heldUntilUnixMs:i+r}}),!0})}async releaseLease(e){await T(e,async()=>{let r=await this.get(e);r&&await this.set(e,{...r,lease:void 0})})}};import{randomUUID as tt}from"crypto";var rt='if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end',fe=class{constructor(e,r="tab:"){this.client=e;this.keyPrefix=r}leaseTokens=new Map;ledgerKey(e){return`${this.keyPrefix}ledger:${e}`}leaseKey(e){return`${this.keyPrefix}lease:${e}`}async get(e){let r=await this.client.get(this.ledgerKey(e));return r===null?null:ye(JSON.parse(r))}async set(e,r){let n=he({...r,lease:void 0});await this.client.set(this.ledgerKey(e),JSON.stringify(n))}async delete(e){this.leaseTokens.delete(e),await this.client.del(this.ledgerKey(e),this.leaseKey(e))}async tryAcquireLease(e,r){let n=tt();return await this.client.set(this.leaseKey(e),n,"PX",Math.max(1,Math.floor(r)),"NX")!=="OK"?!1:(this.leaseTokens.set(e,n),!0)}async releaseLease(e){let r=this.leaseTokens.get(e);r!==void 0&&(this.leaseTokens.delete(e),await this.client.eval(rt,1,this.leaseKey(e),r))}};import{PublicKey as mt}from"@solana/web3.js";import nt from"tweetnacl";import{sha256 as tr}from"@noble/hashes/sha256";import{p256 as nr}from"@noble/curves/p256";import{PublicKey as ve}from"@solana/web3.js";import{sessionRegisterMessage as Mt,sessionRevokeMessage as Dt,voucherPayloadMessage as Ae,buildVoucherMessage as zt}from"@dexterai/vault/messages";import{buildRegisterSessionKeyInstruction as Ft,buildRevokeSessionKeyInstruction as Wt,deriveSwigWalletAddress as jt}from"@dexterai/vault/instructions";import{buildSecp256r1VerifyInstruction as Jt}from"@dexterai/vault/precompile";import{DEXTER_VAULT_PROGRAM_ID as be,SECP256R1_PROGRAM_ID as Yt,INSTRUCTIONS_SYSVAR_ID as Zt}from"@dexterai/vault/constants";import{fetchSessionAccount as it,isSessionLive as st}from"@dexterai/vault/session";var we="OTS_SESSION_REGISTER_V2",E=class extends Error{constructor(r,n){super(`Invalid registration: ${r}${n?` (${n})`:""}`);this.reason=r;this.name="InvalidRegistrationError"}};function Se(t){if(t.length!==188)throw new E("wrong_length",`expected 188, got ${t.length}`);let e=new TextDecoder().decode(t.slice(0,we.length));if(e!==we)throw new E("wrong_domain",`got "${e}"`);for(let y=we.length;y<32;y++)if(t[y]!==0)throw new E("wrong_domain",`non-NUL padding at byte ${y}`);let r=new DataView(t.buffer,t.byteOffset,t.byteLength),n=new ve(t.slice(32,64)),i=new ve(t.slice(64,96)),s=t.slice(96,128),h=r.getBigUint64(128,!0),c=r.getBigInt64(136,!0),a=new ve(t.slice(144,176)),m=r.getUint32(176,!0),l=r.getBigUint64(180,!0);if(!n.equals(be))throw new E("wrong_program",`${n.toBase58()} is not ${be.toBase58()}`);if(h===0n)throw new E("cap_zero");let o=BigInt(Math.floor(Date.now()/1e3));if(c<=o)throw new E("expiry_in_past",`expires_at=${c}, now=${o}`);return{programId:n,vaultPda:i,sessionPubkey:new Uint8Array(s),maxAmount:h,expiresAt:c,allowedCounterparty:a,nonce:m,maxRevolvingCapacity:l}}var N=class extends Error{constructor(r,n){super(`On-chain verification failed: ${r}${n?` (${n})`:""}`);this.reason=r;this.name="OnChainVerificationError"}};async function xe(t,e){let r=await it(t,e.vaultPda,e.allowedCounterparty);if(!r||r.version===0)throw new N("session_not_active","no live SessionAccount PDA for this (vault, counterparty) \u2014 revoked, expiry-swept, or never registered");if(!st(r))throw new N("session_not_active","SessionAccount PDA is present but expired");if(!ot(r.session.sessionPubkey,e.sessionPubkey))throw new N("session_pubkey_mismatch",`on-chain ${Me(r.session.sessionPubkey)} != registration ${Me(e.sessionPubkey)}`);let n=r.session.spent,i=r.session.crystallizedCumulative;return{frontierAtomic:(n>i?n:i).toString(),spentAtomic:n.toString(),crystallizedCumulativeAtomic:i.toString()}}var _=class extends Error{constructor(e){super(`Invalid voucher signature${e?`: ${e}`:""}`),this.name="InvalidVoucherSignatureError"}};function Ce(t,e){if(e.length!==32)throw new _(`channelIdBytes must be 32 bytes, got ${e.length}`);if(t.sessionPublicKey.length!==32)throw new _(`sessionPublicKey must be 32 bytes, got ${t.sessionPublicKey.length}`);if(t.sessionSignature.length!==64)throw new _(`sessionSignature must be 64 bytes, got ${t.sessionSignature.length}`);let r=Ae({channelId:e,cumulativeAmount:BigInt(t.payload.cumulativeAmount),sequenceNumber:t.payload.sequenceNumber});if(!nt.sign.detached.verify(r,t.sessionSignature,t.sessionPublicKey))throw new _("ed25519 verify rejected")}var C=class extends Error{constructor(r,n){super(`Scope violation: ${r}${n?` (${n})`:""}`);this.reason=r;this.name="ScopeViolationError"}};function Ee(t){let e=BigInt(t.voucher.payload.cumulativeAmount);if(e>t.registration.maxAmount)throw new C("cumulative_exceeds_cap",`${e} > ${t.registration.maxAmount}`);let r=BigInt(Math.floor(Date.now()/1e3));if(r>=t.registration.expiresAt)throw new C("session_expired",`now=${r} >= expiresAt=${t.registration.expiresAt}`);if(!t.registration.allowedCounterparty.equals(t.expectedCounterparty))throw new C("wrong_counterparty",`${t.registration.allowedCounterparty.toBase58()} != ${t.expectedCounterparty.toBase58()}`);if(t.previousCumulativeAtomic!==void 0){let n=BigInt(t.previousCumulativeAtomic);if(e<=n)throw new C("non_monotonic",`cumulative=${e} not > previous=${n}`)}}function ot(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function Me(t){let e="";for(let r of t)e+=r.toString(16).padStart(2,"0");return e}import{PublicKey as Sr}from"@solana/web3.js";import{bytesToHex as Cr}from"@noble/hashes/utils";import dr from"tweetnacl";import{sha256 as hr}from"@noble/hashes/sha256";var De="https://x402.dexter.cash",ze=6;function P(t,e=ze){if(!/^\d+(\.\d+)?$/.test(t))throw new Error(`amount must be a non-negative decimal string, got "${t}"`);let[r,n=""]=t.split(".");if(n.length>e)throw new Error(`amount "${t}" has more than ${e} decimals`);let i=n.padEnd(e,"0"),s=`${r}${i}`.replace(/^0+(?=\d)/,"");return s===""?"0":s}function O(t,e=ze){if(!/^\d+$/.test(t))throw new Error(`atomic must be a non-negative integer string, got "${t}"`);let r=t.padStart(e+1,"0"),n=r.slice(0,-e).replace(/^0+(?=\d)/,"")||"0",i=r.slice(-e).replace(/0+$/,"");return i?`${n}.${i}`:n}import{bytesToHex as Pe}from"@noble/hashes/utils";var at=15e3,ct=["claim_already_exists","non_monotonic_cumulative"],lt="below_lock_cadence";function J(t){return typeof t=="string"&&t.includes(lt)}function ut(t){return`${t.slice(0,16)}\u2026`}function He(t,e,r,n){let i=ut(t);if(n.crystallized){console.info(`[tab/seller] crystallize OK channel=${i} cumulative=${e} seq=${r}${n.claimPda?` claimPda=${n.claimPda}`:""} \u2014 LockVoucher landed`);return}if(n.error){if(J(n.error)){console.warn(`[tab/seller] crystallize refused below the facilitator's cadence gate channel=${i} cumulative=${e} seq=${r}: ${n.error} \u2014 benign: this facilitator's cadence engine owns the protection cadence for the span; gate-refused watermark advanced, re-attempts after the next signed voucher`);return}if(ct.some(s=>n.error.includes(s))){console.warn(`[tab/seller] crystallize duplicate channel=${i} cumulative=${e} seq=${r}: ${n.error} \u2014 voucher already secured on-chain (benign, no action)`);return}console.error(`[tab/seller] crystallize FAILED channel=${i} cumulative=${e} seq=${r}: ${n.error} \u2014 lock NOT secured (degraded: best-effort path, no watermark advance, retries at next threshold/close; seller exposure stays unsecured until it lands)`)}}async function Re(t,e,r,n,i=fetch){let s=t.lastVoucher;if(!s)return{crystallized:!1};if(s.payload.channelId!==e){let c={crystallized:!1,error:"channel_id_mismatch"};return He(e,s.payload.cumulativeAmount,s.payload.sequenceNumber,c),c}let h=c=>(He(e,s.payload.cumulativeAmount,s.payload.sequenceNumber,c),c);try{let c=`${r.replace(/\/$/,"")}/tab/lock`,a={channelId:s.payload.channelId,cumulativeAmount:s.payload.cumulativeAmount,sequenceNumber:s.payload.sequenceNumber,sessionPublicKey:Pe(s.sessionPublicKey),sessionSignature:Pe(s.sessionSignature),sessionRegistration:Pe(s.sessionRegistration),network:n},m=await i(c,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(at)}),l=await m.text();if(!m.ok)return h({crystallized:!1,error:`tab lock ${m.status}: ${l.slice(0,200)}`});let o;try{let y=JSON.parse(l);y&&typeof y.claimPda=="string"&&(o=y.claimPda)}catch{}return h({crystallized:!0,claimPda:o})}catch(c){return h({crystallized:!1,error:String(c?.message??c)})}}async function qe(t,e,r,n,i,s={}){let h=BigInt(t.deliveredCumulativeAtomic),c=BigInt(t.lastCrystallizedCumulativeAtomic??"0"),a=BigInt(i.thresholdAtomic);if(h-c<a)return{crystallized:!1};let m=t.lastVoucher?.payload.cumulativeAmount,l=t.gateRefusedCumulativeAtomic;if(m!==void 0&&l!==void 0&&BigInt(m)<=BigInt(l))return{crystallized:!1};let o=await Re(t,e,r,n,s.fetchImpl);return o.crystallized&&m!==void 0?(t.lastCrystallizedCumulativeAtomic=m,t.gateRefusedCumulativeAtomic=void 0):J(o.error)&&m!==void 0&&(t.gateRefusedCumulativeAtomic=m),o}var $="x-tab-voucher",Te=class{map=new Map;get(e){return this.map.get(e)}set(e,r){this.map.set(e,r)}update(e,r){let n=this.map.get(e);n&&(n.lastCumulativeAtomic=r)}delete(e){this.map.delete(e)}},_e=class{constructor(e,r,n,i,s,h){this.recordDeliveredImpl=s;this.chargeImpl=h;this.channelId=e,this.network=r,this.cumulativeAtomic=n,this.deliveredBaselineAtomic=i}channelId;network;sessionPublicKey=null;cumulativeAtomic;deliveredBaselineAtomic;cumulative(){return O(this.cumulativeAtomic.toString())}deliveredCumulative(){return O(this.deliveredBaselineAtomic.toString())}async recordDelivered(e){return this.recordDeliveredImpl(e)}bumpCumulative(e){this.cumulativeAtomic=e}setSessionPublicKey(e){this.sessionPublicKey=e}async charge(e){return this.chargeImpl(e)}};function dt(t){if(typeof t!="string"||t.length===0)throw new x("signature_invalid",`missing ${$} header`);let e;try{e=Buffer.from(t,"base64").toString("utf8")}catch{throw new x("signature_invalid","malformed base64")}let r;try{r=JSON.parse(e)}catch{throw new x("signature_invalid","malformed JSON")}if(!r||typeof r!="object"||!r.payload||!r.sessionPublicKey)throw new x("signature_invalid","missing required fields");return{payload:r.payload,sessionPublicKey:G(r.sessionPublicKey),sessionRegistration:G(r.sessionRegistration),sessionSignature:G(r.sessionSignature)}}function G(t){if(typeof t!="string"||t.length%2!==0)throw new x("signature_invalid",`bad hex: ${typeof t}`);let e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(t.substr(r*2,2),16);return e}function pt(t){if(!/^[0-9a-f]{64}$/i.test(t))throw new x("signature_invalid",`channelId must be 64-char hex, got "${t}"`);return G(t)}function ke(t){let e=t.ledger??new M,r=new Te,n=typeof t.sellerPubkey=="string"?new mt(t.sellerPubkey):t.sellerPubkey,i=t.maxPerVoucherAtomic?BigInt(t.maxPerVoucherAtomic):BigInt(P(t.perUnit))*100n,s=t.facilitatorUrl??De,h={thresholdAtomic:t.lockCadence?.thresholdAtomic??P("0.10"),onClose:t.lockCadence?.onClose??!0};return async(c,a,m)=>{try{let l=dt(c.headers[$]),o=l.payload.channelId,y=pt(o),d=r.get(o),f=null;if(!d){let p=Se(l.sessionRegistration);f=(await xe(t.connection,p))?.frontierAtomic??null;let v=await e.get(o);d={registration:p,lastCumulativeAtomic:v?.lastVoucher?.payload.cumulativeAmount??"0"},r.set(o,d)}Ce(l,y),Ee({registration:d.registration,voucher:l,expectedCounterparty:n,previousCumulativeAtomic:d.lastCumulativeAtomic});let b=BigInt(l.payload.cumulativeAmount),V=BigInt(d.lastCumulativeAtomic),L=b-V;if(L>i)throw new C("cumulative_exceeds_cap",`single voucher increment ${L} exceeds maxPerVoucherAtomic ${i}`);let ue=t.leaseTtlMs??3e5;if(!await e.tryAcquireLease(o,ue))throw new x("channel_busy","another stream is live on this channel; tabs serve one stream at a time");let B=!1,j=()=>{B||(B=!0,e.releaseLease(o).catch(p=>{console.error("[tab/seller] failed to release channel lease:",p)}))};a.on("close",j),a.on("finish",j);let me=async p=>{let R=p.lastCrystallizedCumulativeAtomic??"0",v=p.gateRefusedCumulativeAtomic;await qe(p,o,s,t.network,h),(p.lastCrystallizedCumulativeAtomic!==R||p.gateRefusedCumulativeAtomic!==v)&&await T(o,async()=>{let w=await e.get(o);w&&await e.set(o,{...w,lastCrystallizedCumulativeAtomic:p.lastCrystallizedCumulativeAtomic,gateRefusedCumulativeAtomic:p.gateRefusedCumulativeAtomic})}).catch(w=>{console.error(`[tab/seller] crystallize watermark persist FAILED channel=${o.slice(0,16)}\u2026 (expect a benign duplicate/below-cadence warn on the next request):`,w)})},X=!1,u=()=>{!h.onClose||X||(X=!0,(async()=>{let p=await e.get(o);if(!p||!p.lastVoucher)return;let R=p.lastVoucher.payload.cumulativeAmount;if(p.gateRefusedCumulativeAtomic!==void 0&&BigInt(R)<=BigInt(p.gateRefusedCumulativeAtomic))return;let v=await Re(p,o,s,t.network);v.crystallized?await T(o,async()=>{let w=await e.get(o);w&&await e.set(o,{...w,lastCrystallizedCumulativeAtomic:R,gateRefusedCumulativeAtomic:void 0})}):J(v.error)&&await T(o,async()=>{let w=await e.get(o);w&&await e.set(o,{...w,gateRefusedCumulativeAtomic:R})})})().catch(p=>{console.error(`[tab/seller] close-path crystallize CRASHED channel=${o.slice(0,16)}\u2026 (final voucher NOT locked; exposure unsecured until the next request retries):`,p)}))};a.on("close",u),a.on("finish",u);let g=await e.get(o),A=!g?.lastVoucher&&BigInt(g?.deliveredCumulativeAtomic??"0")===0n,S=f!==null&&A&&BigInt(f)>0n?f:null;S!==null&&console.info(`[tab/seller] channel ${o.slice(0,16)}\u2026 resumed: seeding delivered baseline from chain frontier ${S} (session already settled/locked up to it \u2014 that span is not deliverable budget)`);let I=S!==null?BigInt(S):g?BigInt(g.deliveredCumulativeAtomic):0n;await T(o,async()=>{let p=await e.get(o);await e.set(o,{...p,lastVoucher:l,deliveredCumulativeAtomic:S??(p?p.deliveredCumulativeAtomic:"0"),lastCrystallizedCumulativeAtomic:S??p?.lastCrystallizedCumulativeAtomic??"0"})}),r.update(o,l.payload.cumulativeAmount);let U=new _e(o,t.network,b,I,async p=>{let R=null;await T(o,async()=>{let v=await e.get(o),w=v?BigInt(v.deliveredCumulativeAtomic):0n,$e=BigInt(p),Ze=$e>0n?w+$e:w,Ve={...v,lastVoucher:v?.lastVoucher??l,deliveredCumulativeAtomic:Ze.toString(),lastCrystallizedCumulativeAtomic:v?.lastCrystallizedCumulativeAtomic??"0"};await e.set(o,Ve),R=Ve}),R&&me(R).catch(v=>{console.error(`[tab/seller] crystallize cadence CRASHED channel=${o.slice(0,16)}\u2026 (threshold lock not attempted; retries at the next delivery):`,v)})},async p=>{throw new Error("SellerTab.charge() is not driven by the route handler; the buyer presents a fresh voucher per chunk. Use openSse(res, tab) for the metered-stream pattern.")});U.setSessionPublicKey(l.sessionPublicKey),c.tab=U,m()}catch(l){if(l instanceof x||l instanceof E||l instanceof N||l instanceof _||l instanceof C){a.status(402).json({error:"invalid_voucher",reason:l.reason??"unknown",detail:l.message});return}m(l)}}}function gt(t){if(!t.tab)throw new Error("req.tab is missing \u2014 did tabMiddleware run on this route?");return t.tab}function ht(t,e){if(!e.tab)throw new Error("openSse requires options.tab");t.headersSent||(t.setHeader("Content-Type","text/event-stream"),t.setHeader("Cache-Control","no-cache"),t.setHeader("Connection","keep-alive"),typeof t.flushHeaders=="function"&&t.flushHeaders());let r=e.tab,n=BigInt(P(r.cumulative())),i=BigInt(P(r.deliveredCumulative())),s=n-i;s<0n&&(s=0n);let h=e.perUnit?BigInt(P(e.perUnit)):null,c=0n,a=!1;async function m(){await r.recordDelivered(c.toString())}t.on("close",()=>{a||(a=!0,m().catch(d=>{console.error("[tab/seller] terminal persist failed on disconnect:",d)}))});async function l(d=1){if(a)throw new Error("meter ended");if(h===null)throw new Error("charge() needs options.perUnit");let f=h*BigInt(d),b=c+f;if(b>s)throw a=!0,await m(),new C("cumulative_exceeds_cap",`chunk would push delivered to ${O((i+b).toString())} beyond signed cumulative ${O(n.toString())} (per-request budget ${O(s.toString())})`);c=b}function o(d){if(a)throw new Error("meter ended");let b=(typeof d=="string"?d:Buffer.from(d).toString("utf8")).replace(/\n/g,"\\n");t.write(`data: ${b}
1
+ var x=class extends Error{constructor(r,n){super(`Invalid voucher: ${r}${n?` (${n})`:""}`);this.reason=r;this.name="InvalidVoucherError"}};import{promises as M}from"fs";import{join as rt,dirname as nt}from"path";var De=new Map;function P(t,e){let n=(De.get(t)??Promise.resolve()).then(()=>e(),()=>e());return De.set(t,n.then(()=>{},()=>{})),n}var D=class{map=new Map;async get(e){return this.map.get(e)??null}async set(e,r){this.map.set(e,r)}async delete(e){this.map.delete(e)}async tryAcquireLease(e,r){return P(e,async()=>{let n=this.map.get(e),i=Date.now();if(n?.lease&&n.lease.heldUntilUnixMs>i)return!1;let s=n??{lastVoucher:null,deliveredCumulativeAtomic:"0",lastCrystallizedCumulativeAtomic:"0"};return this.map.set(e,{...s,lease:{heldUntilUnixMs:i+r}}),!0})}async releaseLease(e){await P(e,async()=>{let r=this.map.get(e);r&&this.map.set(e,{...r,lease:void 0})})}};function he(t){let e="";for(let r of t)e+=r.toString(16).padStart(2,"0");return e}function ye(t){if(t.length%2!==0)throw new Error(`hex length must be even, got ${t.length}`);let e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(t.substr(r*2,2),16);return e}function Ae(t){return Ke(t)}function be(t){return ze(t)}function Ke(t){return{lastVoucher:t.lastVoucher?{payload:t.lastVoucher.payload,sessionPublicKey:he(t.lastVoucher.sessionPublicKey),sessionRegistration:he(t.lastVoucher.sessionRegistration),sessionSignature:he(t.lastVoucher.sessionSignature)}:null,deliveredCumulativeAtomic:t.deliveredCumulativeAtomic,lastCrystallizedCumulativeAtomic:t.lastCrystallizedCumulativeAtomic,gateRefusedCumulativeAtomic:t.gateRefusedCumulativeAtomic,onChain:t.onChain,lease:t.lease}}function ze(t){return{lastVoucher:t.lastVoucher?{payload:t.lastVoucher.payload,sessionPublicKey:ye(t.lastVoucher.sessionPublicKey),sessionRegistration:ye(t.lastVoucher.sessionRegistration),sessionSignature:ye(t.lastVoucher.sessionSignature)}:null,deliveredCumulativeAtomic:t.deliveredCumulativeAtomic,lastCrystallizedCumulativeAtomic:t.lastCrystallizedCumulativeAtomic??"0",gateRefusedCumulativeAtomic:t.gateRefusedCumulativeAtomic,onChain:t.onChain,lease:t.lease}}var fe=class{constructor(e){this.dir=e}pathFor(e){if(!/^[a-z0-9_-]+$/i.test(e))throw new Error(`unsafe channelId for filesystem: ${e}`);return rt(this.dir,`${e}.json`)}async get(e){try{let r=await M.readFile(this.pathFor(e),"utf8");return ze(JSON.parse(r))}catch(r){if(r?.code==="ENOENT")return null;throw r}}async set(e,r){let n=this.pathFor(e);await M.mkdir(nt(n),{recursive:!0});let i=`${n}.tmp`;await M.writeFile(i,JSON.stringify(Ke(r))),await M.rename(i,n)}async delete(e){try{await M.unlink(this.pathFor(e))}catch(r){if(r?.code!=="ENOENT")throw r}}async tryAcquireLease(e,r){return P(e,async()=>{let n=await this.get(e),i=Date.now();if(n?.lease&&n.lease.heldUntilUnixMs>i)return!1;let s=n??{lastVoucher:null,deliveredCumulativeAtomic:"0",lastCrystallizedCumulativeAtomic:"0"};return await this.set(e,{...s,lease:{heldUntilUnixMs:i+r}}),!0})}async releaseLease(e){await P(e,async()=>{let r=await this.get(e);r&&await this.set(e,{...r,lease:void 0})})}};import{randomUUID as it}from"crypto";var st='if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end',ve=class{constructor(e,r="tab:"){this.client=e;this.keyPrefix=r}leaseTokens=new Map;ledgerKey(e){return`${this.keyPrefix}ledger:${e}`}leaseKey(e){return`${this.keyPrefix}lease:${e}`}async get(e){let r=await this.client.get(this.ledgerKey(e));return r===null?null:be(JSON.parse(r))}async set(e,r){let n=Ae({...r,lease:void 0});await this.client.set(this.ledgerKey(e),JSON.stringify(n))}async delete(e){this.leaseTokens.delete(e),await this.client.del(this.ledgerKey(e),this.leaseKey(e))}async tryAcquireLease(e,r){let n=it();return await this.client.set(this.leaseKey(e),n,"PX",Math.max(1,Math.floor(r)),"NX")!=="OK"?!1:(this.leaseTokens.set(e,n),!0)}async releaseLease(e){let r=this.leaseTokens.get(e);r!==void 0&&(this.leaseTokens.delete(e),await this.client.eval(st,1,this.leaseKey(e),r))}};import{PublicKey as gt}from"@solana/web3.js";import ot from"tweetnacl";import{sha256 as or}from"@noble/hashes/sha256";import{p256 as cr}from"@noble/curves/p256";import{PublicKey as xe}from"@solana/web3.js";import{sessionRegisterMessage as Ft,sessionRevokeMessage as Wt,voucherPayloadMessage as we,buildVoucherMessage as jt}from"@dexterai/vault/messages";import{buildRegisterSessionKeyInstruction as Gt,buildRevokeSessionKeyInstruction as Yt,deriveSwigWalletAddress as Zt}from"@dexterai/vault/instructions";import{buildSecp256r1VerifyInstruction as er}from"@dexterai/vault/precompile";import{DEXTER_VAULT_PROGRAM_ID as Se,SECP256R1_PROGRAM_ID as rr,INSTRUCTIONS_SYSVAR_ID as nr}from"@dexterai/vault/constants";import{fetchSessionAccount as at,isSessionLive as ct}from"@dexterai/vault/session";var Ce="OTS_SESSION_REGISTER_V2",E=class extends Error{constructor(r,n){super(`Invalid registration: ${r}${n?` (${n})`:""}`);this.reason=r;this.name="InvalidRegistrationError"}};function Ee(t){if(t.length!==188)throw new E("wrong_length",`expected 188, got ${t.length}`);let e=new TextDecoder().decode(t.slice(0,Ce.length));if(e!==Ce)throw new E("wrong_domain",`got "${e}"`);for(let y=Ce.length;y<32;y++)if(t[y]!==0)throw new E("wrong_domain",`non-NUL padding at byte ${y}`);let r=new DataView(t.buffer,t.byteOffset,t.byteLength),n=new xe(t.slice(32,64)),i=new xe(t.slice(64,96)),s=t.slice(96,128),h=r.getBigUint64(128,!0),c=r.getBigInt64(136,!0),a=new xe(t.slice(144,176)),m=r.getUint32(176,!0),l=r.getBigUint64(180,!0);if(!n.equals(Se))throw new E("wrong_program",`${n.toBase58()} is not ${Se.toBase58()}`);if(h===0n)throw new E("cap_zero");let o=BigInt(Math.floor(Date.now()/1e3));if(c<=o)throw new E("expiry_in_past",`expires_at=${c}, now=${o}`);return{programId:n,vaultPda:i,sessionPubkey:new Uint8Array(s),maxAmount:h,expiresAt:c,allowedCounterparty:a,nonce:m,maxRevolvingCapacity:l}}var k=class extends Error{constructor(r,n){super(`On-chain verification failed: ${r}${n?` (${n})`:""}`);this.reason=r;this.name="OnChainVerificationError"}};async function Re(t,e){let r=await at(t,e.vaultPda,e.allowedCounterparty);if(!r||r.version===0)throw new k("session_not_active","no live SessionAccount PDA for this (vault, counterparty) \u2014 revoked, expiry-swept, or never registered");if(!ct(r))throw new k("session_not_active","SessionAccount PDA is present but expired");if(!lt(r.session.sessionPubkey,e.sessionPubkey))throw new k("session_pubkey_mismatch",`on-chain ${He(r.session.sessionPubkey)} != registration ${He(e.sessionPubkey)}`);let n=r.session.spent,i=r.session.crystallizedCumulative;return{frontierAtomic:(n>i?n:i).toString(),spentAtomic:n.toString(),crystallizedCumulativeAtomic:i.toString()}}var _=class extends Error{constructor(e){super(`Invalid voucher signature${e?`: ${e}`:""}`),this.name="InvalidVoucherSignatureError"}};function Te(t,e){if(e.length!==32)throw new _(`channelIdBytes must be 32 bytes, got ${e.length}`);if(t.sessionPublicKey.length!==32)throw new _(`sessionPublicKey must be 32 bytes, got ${t.sessionPublicKey.length}`);if(t.sessionSignature.length!==64)throw new _(`sessionSignature must be 64 bytes, got ${t.sessionSignature.length}`);let r=we({channelId:e,cumulativeAmount:BigInt(t.payload.cumulativeAmount),sequenceNumber:t.payload.sequenceNumber});if(!ot.sign.detached.verify(r,t.sessionSignature,t.sessionPublicKey))throw new _("ed25519 verify rejected")}var C=class extends Error{constructor(r,n){super(`Scope violation: ${r}${n?` (${n})`:""}`);this.reason=r;this.name="ScopeViolationError"}};function Pe(t){let e=BigInt(t.voucher.payload.cumulativeAmount);if(e>t.registration.maxAmount)throw new C("cumulative_exceeds_cap",`${e} > ${t.registration.maxAmount}`);let r=BigInt(Math.floor(Date.now()/1e3));if(r>=t.registration.expiresAt)throw new C("session_expired",`now=${r} >= expiresAt=${t.registration.expiresAt}`);if(!t.registration.allowedCounterparty.equals(t.expectedCounterparty))throw new C("wrong_counterparty",`${t.registration.allowedCounterparty.toBase58()} != ${t.expectedCounterparty.toBase58()}`);if(t.previousCumulativeAtomic!==void 0){let n=BigInt(t.previousCumulativeAtomic);if(e<=n)throw new C("non_monotonic",`cumulative=${e} not > previous=${n}`)}}function lt(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function He(t){let e="";for(let r of t)e+=r.toString(16).padStart(2,"0");return e}import{PublicKey as Tr}from"@solana/web3.js";import{bytesToHex as _r}from"@noble/hashes/utils";import fr from"tweetnacl";import{sha256 as vr}from"@noble/hashes/sha256";var qe="https://x402.dexter.cash",Fe=6;function R(t,e=Fe){if(!/^\d+(\.\d+)?$/.test(t))throw new Error(`amount must be a non-negative decimal string, got "${t}"`);let[r,n=""]=t.split(".");if(n.length>e)throw new Error(`amount "${t}" has more than ${e} decimals`);let i=n.padEnd(e,"0"),s=`${r}${i}`.replace(/^0+(?=\d)/,"");return s===""?"0":s}function U(t,e=Fe){if(!/^\d+$/.test(t))throw new Error(`atomic must be a non-negative integer string, got "${t}"`);let r=t.padStart(e+1,"0"),n=r.slice(0,-e).replace(/^0+(?=\d)/,"")||"0",i=r.slice(-e).replace(/0+$/,"");return i?`${n}.${i}`:n}import{bytesToHex as _e}from"@noble/hashes/utils";var ut=15e3,mt=["claim_already_exists","non_monotonic_cumulative"],dt="below_lock_cadence";function ee(t){return typeof t=="string"&&t.includes(dt)}function pt(t){return`${t.slice(0,16)}\u2026`}function We(t,e,r,n){let i=pt(t);if(n.crystallized){console.info(`[tab/seller] crystallize OK channel=${i} cumulative=${e} seq=${r}${n.claimPda?` claimPda=${n.claimPda}`:""} \u2014 LockVoucher landed`);return}if(n.error){if(ee(n.error)){console.warn(`[tab/seller] crystallize refused below the facilitator's cadence gate channel=${i} cumulative=${e} seq=${r}: ${n.error} \u2014 benign: this facilitator's cadence engine owns the protection cadence for the span; gate-refused watermark advanced, re-attempts after the next signed voucher`);return}if(mt.some(s=>n.error.includes(s))){console.warn(`[tab/seller] crystallize duplicate channel=${i} cumulative=${e} seq=${r}: ${n.error} \u2014 voucher already secured on-chain (benign, no action)`);return}console.error(`[tab/seller] crystallize FAILED channel=${i} cumulative=${e} seq=${r}: ${n.error} \u2014 lock NOT secured (degraded: best-effort path, no watermark advance, retries at next threshold/close; seller exposure stays unsecured until it lands)`)}}async function Ne(t,e,r,n,i=fetch){let s=t.lastVoucher;if(!s)return{crystallized:!1};if(s.payload.channelId!==e){let c={crystallized:!1,error:"channel_id_mismatch"};return We(e,s.payload.cumulativeAmount,s.payload.sequenceNumber,c),c}let h=c=>(We(e,s.payload.cumulativeAmount,s.payload.sequenceNumber,c),c);try{let c=`${r.replace(/\/$/,"")}/tab/lock`,a={channelId:s.payload.channelId,cumulativeAmount:s.payload.cumulativeAmount,sequenceNumber:s.payload.sequenceNumber,sessionPublicKey:_e(s.sessionPublicKey),sessionSignature:_e(s.sessionSignature),sessionRegistration:_e(s.sessionRegistration),network:n},m=await i(c,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(ut)}),l=await m.text();if(!m.ok)return h({crystallized:!1,error:`tab lock ${m.status}: ${l.slice(0,200)}`});let o;try{let y=JSON.parse(l);y&&typeof y.claimPda=="string"&&(o=y.claimPda)}catch{}return h({crystallized:!0,claimPda:o})}catch(c){return h({crystallized:!1,error:String(c?.message??c)})}}async function je(t,e,r,n,i,s={}){let h=BigInt(t.deliveredCumulativeAtomic),c=BigInt(t.lastCrystallizedCumulativeAtomic??"0"),a=BigInt(i.thresholdAtomic);if(h-c<a)return{crystallized:!1};let m=t.lastVoucher?.payload.cumulativeAmount,l=t.gateRefusedCumulativeAtomic;if(m!==void 0&&l!==void 0&&BigInt(m)<=BigInt(l))return{crystallized:!1};let o=await Ne(t,e,r,n,s.fetchImpl);return o.crystallized&&m!==void 0?(t.lastCrystallizedCumulativeAtomic=m,t.gateRefusedCumulativeAtomic=void 0):ee(o.error)&&m!==void 0&&(t.gateRefusedCumulativeAtomic=m),o}var $="x-tab-voucher",ke=class{map=new Map;get(e){return this.map.get(e)}set(e,r){this.map.set(e,r)}update(e,r){let n=this.map.get(e);n&&(n.lastCumulativeAtomic=r)}delete(e){this.map.delete(e)}},Ie=class{constructor(e,r,n,i,s,h){this.recordDeliveredImpl=s;this.chargeImpl=h;this.channelId=e,this.network=r,this.cumulativeAtomic=n,this.deliveredBaselineAtomic=i}channelId;network;sessionPublicKey=null;cumulativeAtomic;deliveredBaselineAtomic;cumulative(){return U(this.cumulativeAtomic.toString())}deliveredCumulative(){return U(this.deliveredBaselineAtomic.toString())}async recordDelivered(e){return this.recordDeliveredImpl(e)}bumpCumulative(e){this.cumulativeAtomic=e}setSessionPublicKey(e){this.sessionPublicKey=e}async charge(e){return this.chargeImpl(e)}};function ht(t){if(typeof t!="string"||t.length===0)throw new x("signature_invalid",`missing ${$} header`);let e;try{e=Buffer.from(t,"base64").toString("utf8")}catch{throw new x("signature_invalid","malformed base64")}let r;try{r=JSON.parse(e)}catch{throw new x("signature_invalid","malformed JSON")}if(!r||typeof r!="object"||!r.payload||!r.sessionPublicKey)throw new x("signature_invalid","missing required fields");return{payload:r.payload,sessionPublicKey:te(r.sessionPublicKey),sessionRegistration:te(r.sessionRegistration),sessionSignature:te(r.sessionSignature)}}function te(t){if(typeof t!="string"||t.length%2!==0)throw new x("signature_invalid",`bad hex: ${typeof t}`);let e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(t.substr(r*2,2),16);return e}function yt(t){if(!/^[0-9a-f]{64}$/i.test(t))throw new x("signature_invalid",`channelId must be 64-char hex, got "${t}"`);return te(t)}function Oe(t){let e=t.ledger??new D,r=new ke,n=typeof t.sellerPubkey=="string"?new gt(t.sellerPubkey):t.sellerPubkey,i=t.maxPerVoucherAtomic?BigInt(t.maxPerVoucherAtomic):BigInt(R(t.perUnit))*100n,s=t.facilitatorUrl??qe,h={thresholdAtomic:t.lockCadence?.thresholdAtomic??R("0.10"),onClose:t.lockCadence?.onClose??!0};return async(c,a,m)=>{try{let l=ht(c.headers[$]),o=l.payload.channelId,y=yt(o),d=r.get(o),f=null;if(!d){let p=Ee(l.sessionRegistration);f=(await Re(t.connection,p))?.frontierAtomic??null;let v=await e.get(o);d={registration:p,lastCumulativeAtomic:v?.lastVoucher?.payload.cumulativeAmount??"0"},r.set(o,d)}Te(l,y),Pe({registration:d.registration,voucher:l,expectedCounterparty:n,previousCumulativeAtomic:d.lastCumulativeAtomic});let b=BigInt(l.payload.cumulativeAmount),V=BigInt(d.lastCumulativeAtomic),L=b-V;if(L>i)throw new C("cumulative_exceeds_cap",`single voucher increment ${L} exceeds maxPerVoucherAtomic ${i}`);let pe=t.leaseTtlMs??3e5;if(!await e.tryAcquireLease(o,pe))throw new x("channel_busy","another stream is live on this channel; tabs serve one stream at a time");let B=!1,Z=()=>{B||(B=!0,e.releaseLease(o).catch(p=>{console.error("[tab/seller] failed to release channel lease:",p)}))};a.on("close",Z),a.on("finish",Z);let ge=async p=>{let T=p.lastCrystallizedCumulativeAtomic??"0",v=p.gateRefusedCumulativeAtomic;await je(p,o,s,t.network,h),(p.lastCrystallizedCumulativeAtomic!==T||p.gateRefusedCumulativeAtomic!==v)&&await P(o,async()=>{let w=await e.get(o);w&&await e.set(o,{...w,lastCrystallizedCumulativeAtomic:p.lastCrystallizedCumulativeAtomic,gateRefusedCumulativeAtomic:p.gateRefusedCumulativeAtomic})}).catch(w=>{console.error(`[tab/seller] crystallize watermark persist FAILED channel=${o.slice(0,16)}\u2026 (expect a benign duplicate/below-cadence warn on the next request):`,w)})},Q=!1,u=()=>{!h.onClose||Q||(Q=!0,(async()=>{let p=await e.get(o);if(!p||!p.lastVoucher)return;let T=p.lastVoucher.payload.cumulativeAmount;if(p.gateRefusedCumulativeAtomic!==void 0&&BigInt(T)<=BigInt(p.gateRefusedCumulativeAtomic))return;let v=await Ne(p,o,s,t.network);v.crystallized?await P(o,async()=>{let w=await e.get(o);w&&await e.set(o,{...w,lastCrystallizedCumulativeAtomic:T,gateRefusedCumulativeAtomic:void 0})}):ee(v.error)&&await P(o,async()=>{let w=await e.get(o);w&&await e.set(o,{...w,gateRefusedCumulativeAtomic:T})})})().catch(p=>{console.error(`[tab/seller] close-path crystallize CRASHED channel=${o.slice(0,16)}\u2026 (final voucher NOT locked; exposure unsecured until the next request retries):`,p)}))};a.on("close",u),a.on("finish",u);let g=await e.get(o),A=!g?.lastVoucher&&BigInt(g?.deliveredCumulativeAtomic??"0")===0n,S=f!==null&&A&&BigInt(f)>0n?f:null;S!==null&&console.info(`[tab/seller] channel ${o.slice(0,16)}\u2026 resumed: seeding delivered baseline from chain frontier ${S} (session already settled/locked up to it \u2014 that span is not deliverable budget)`);let I=S!==null?BigInt(S):g?BigInt(g.deliveredCumulativeAtomic):0n;await P(o,async()=>{let p=await e.get(o);await e.set(o,{...p,lastVoucher:l,deliveredCumulativeAtomic:S??(p?p.deliveredCumulativeAtomic:"0"),lastCrystallizedCumulativeAtomic:S??p?.lastCrystallizedCumulativeAtomic??"0"})}),r.update(o,l.payload.cumulativeAmount);let O=new Ie(o,t.network,b,I,async p=>{let T=null;await P(o,async()=>{let v=await e.get(o),w=v?BigInt(v.deliveredCumulativeAtomic):0n,Be=BigInt(p),tt=Be>0n?w+Be:w,Me={...v,lastVoucher:v?.lastVoucher??l,deliveredCumulativeAtomic:tt.toString(),lastCrystallizedCumulativeAtomic:v?.lastCrystallizedCumulativeAtomic??"0"};await e.set(o,Me),T=Me}),T&&ge(T).catch(v=>{console.error(`[tab/seller] crystallize cadence CRASHED channel=${o.slice(0,16)}\u2026 (threshold lock not attempted; retries at the next delivery):`,v)})},async p=>{throw new Error("SellerTab.charge() is not driven by the route handler; the buyer presents a fresh voucher per chunk. Use openSse(res, tab) for the metered-stream pattern.")});O.setSessionPublicKey(l.sessionPublicKey),c.tab=O,m()}catch(l){if(l instanceof x||l instanceof E||l instanceof k||l instanceof _||l instanceof C){a.status(402).json({error:"invalid_voucher",reason:l.reason??"unknown",detail:l.message});return}m(l)}}}function ft(t){if(!t.tab)throw new Error("req.tab is missing \u2014 did tabMiddleware run on this route?");return t.tab}function At(t,e){if(!e.tab)throw new Error("openSse requires options.tab");t.headersSent||(t.setHeader("Content-Type","text/event-stream"),t.setHeader("Cache-Control","no-cache"),t.setHeader("Connection","keep-alive"),typeof t.flushHeaders=="function"&&t.flushHeaders());let r=e.tab,n=BigInt(R(r.cumulative())),i=BigInt(R(r.deliveredCumulative())),s=n-i;s<0n&&(s=0n);let h=e.perUnit?BigInt(R(e.perUnit)):null,c=0n,a=!1;async function m(){await r.recordDelivered(c.toString())}t.on("close",()=>{a||(a=!0,m().catch(d=>{console.error("[tab/seller] terminal persist failed on disconnect:",d)}))});async function l(d=1){if(a)throw new Error("meter ended");if(h===null)throw new Error("charge() needs options.perUnit");let f=h*BigInt(d),b=c+f;if(b>s)throw a=!0,await m(),new C("cumulative_exceeds_cap",`chunk would push delivered to ${U((i+b).toString())} beyond signed cumulative ${U(n.toString())} (per-request budget ${U(s.toString())})`);c=b}function o(d){if(a)throw new Error("meter ended");let b=(typeof d=="string"?d:Buffer.from(d).toString("utf8")).replace(/\\/g,"\\\\").replace(/\n/g,"\\n");t.write(`data: ${b}
2
2
 
3
3
  `)}async function y(){a||(a=!0,await m(),t.write(`event: end
4
4
  data: {"chargedAtomic":"${c}"}
5
5
 
6
- `),t.end())}return{charge:l,send:o,end:y}}import{promises as D}from"fs";import{join as yt,dirname as ft}from"path";function At(t){return{payload:t.payload,sessionPublicKey:Ne(t.sessionPublicKey),sessionRegistration:Ne(t.sessionRegistration),sessionSignature:Ne(t.sessionSignature)}}function bt(t){return{payload:t.payload,sessionPublicKey:Ie(t.sessionPublicKey),sessionRegistration:Ie(t.sessionRegistration),sessionSignature:Ie(t.sessionSignature)}}function Ne(t){let e="";for(let r of t)e+=r.toString(16).padStart(2,"0");return e}function Ie(t){if(t.length%2!==0)throw new Error(`hex length must be even, got ${t.length}`);let e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(t.substr(r*2,2),16);return e}var Ue=class{map=new Map;async get(e){return this.map.get(e)??null}async set(e,r){this.map.set(e,r)}async delete(e){this.map.delete(e)}},Oe=class{constructor(e){this.dir=e}pathFor(e){if(!/^[a-z0-9_-]+$/i.test(e))throw new Error(`unsafe channelId for filesystem: ${e}`);return yt(this.dir,`${e}.json`)}async get(e){try{let r=await D.readFile(this.pathFor(e),"utf8");return bt(JSON.parse(r))}catch(r){if(r?.code==="ENOENT")return null;throw r}}async set(e,r){let n=this.pathFor(e);await D.mkdir(ft(n),{recursive:!0});let i=`${n}.tmp`;await D.writeFile(i,JSON.stringify(At(r))),await D.rename(i,n)}async delete(e){try{await D.unlink(this.pathFor(e))}catch(r){if(r?.code!=="ENOENT")throw r}}};import{PublicKey as Et}from"@solana/web3.js";var k="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Fe="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",We="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";var z="eip155:8453",Y="eip155:84532",Z="eip155:42161",Q="eip155:137",ee="eip155:10",te="eip155:43114",re="eip155:56",ne="eip155:1187947933",ie="eip155:324705682",se="eip155:1";var oe="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";var je="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",vt="0x55d398326f99059fF775485246999027B3197955",Xe="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",Je={[re]:Xe,[z]:je,[Y]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[Z]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[Q]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[ee]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[te]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[ne]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[ie]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[se]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},Ge={[vt]:{symbol:"USDT",decimals:18},[Xe]:{symbol:"USDC",decimals:18}};var qr={[re]:56,[z]:8453,[Y]:84532,[Z]:42161,[Q]:137,[ee]:10,[te]:43114,[ne]:1187947933,[ie]:324705682,[se]:1},Fr={[k]:"https://api.dexter.cash/api/solana/rpc",[Fe]:"https://api.devnet.solana.com",[We]:"https://api.testnet.solana.com"},Wr={[re]:"https://api.dexter.cash/api/evm/bsc/rpc",[z]:"https://api.dexter.cash/api/base/rpc",[Y]:"https://sepolia.base.org",[Z]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[Q]:"https://api.dexter.cash/api/evm/polygon/rpc",[ee]:"https://api.dexter.cash/api/evm/optimism/rpc",[te]:"https://api.dexter.cash/api/evm/avalanche/rpc",[ne]:"https://skale-base.skalenodes.com/v1/base",[ie]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[se]:"https://eth.llamarpc.com"},H="https://x402.dexter.cash";function ae(t){return t.startsWith("solana:")||t==="solana"}function wt(t){if(typeof Buffer<"u")return Buffer.from(t,"utf-8").toString("base64");let e=new TextEncoder().encode(t),r="";for(let n=0;n<e.length;n++)r+=String.fromCharCode(e[n]);return btoa(r)}function St(t){if(typeof Buffer<"u")return Buffer.from(t,"base64").toString("utf-8");let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return new TextDecoder().decode(r)}function ce(t){return wt(JSON.stringify(t))}function q(t){return JSON.parse(St(t))}function xt(t){if(t instanceof TypeError)return!0;if(t&&typeof t=="object"&&"status"in t){let e=t.status;return e>=500&&e<600}return!1}var F=class extends Error{status;body;constructor(e,r){super(`HTTP ${e}`),this.status=e,this.body=r}},le=class{facilitatorUrl;cachedSupported=null;cacheTime=0;CACHE_TTL_MS=6e4;timeoutMs;maxRetries;retryBaseMs;constructor(e=H,r){this.facilitatorUrl=e.replace(/\/$/,""),this.timeoutMs=r?.timeoutMs??1e4,this.maxRetries=r?.maxRetries??3,this.retryBaseMs=r?.retryBaseMs??500}async fetchWithTimeout(e,r){let n=new AbortController,i=setTimeout(()=>n.abort(),this.timeoutMs);try{return await fetch(e,{...r,signal:n.signal})}finally{clearTimeout(i)}}async fetchWithRetry(e,r){let n;for(let i=0;i<this.maxRetries;i++)try{let s=await this.fetchWithTimeout(e,r);if(!s.ok&&s.status>=500)throw new F(s.status,await s.text());return s}catch(s){if(n=s,i<this.maxRetries-1&&xt(s)){let h=this.retryBaseMs*Math.pow(2,i);await new Promise(c=>setTimeout(c,h));continue}throw s}throw n}async getSupported(){let e=Date.now();if(this.cachedSupported&&e-this.cacheTime<this.CACHE_TTL_MS)return this.cachedSupported;let r=await this.fetchWithTimeout(`${this.facilitatorUrl}/supported`);if(!r.ok)throw new Error(`Facilitator /supported returned ${r.status}`);return this.cachedSupported=await r.json(),this.cacheTime=e,this.cachedSupported}async getFeePayer(e){let n=(await this.getSupported()).kinds.find(i=>i.x402Version===2&&(i.scheme==="exact"||i.scheme==="exact-approval")&&i.network===e);if(!n)throw new Error(`Facilitator does not support network "${e}" with a recognized scheme`);return n.extra?.feePayer}async getNetworkExtra(e){return(await this.getSupported()).kinds.find(i=>i.x402Version===2&&(i.scheme==="exact"||i.scheme==="exact-approval"||i.scheme==="batch-settlement")&&i.network===e)?.extra}async verifyPayment(e,r){try{let n=q(e),i=await this.fetchWithRetry(`${this.facilitatorUrl}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x402Version:2,paymentPayload:n,paymentRequirements:r})});return i.ok?await i.json():{isValid:!1,invalidReason:`facilitator_error_${i.status}`}}catch(n){return{isValid:!1,invalidReason:n instanceof F?`facilitator_error_${n.status}`:n instanceof Error&&n.name==="AbortError"?"facilitator_timeout":n instanceof Error?n.message:"unexpected_verify_error"}}}async settlePayment(e,r){try{let n=q(e),i=await this.fetchWithRetry(`${this.facilitatorUrl}/settle`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x402Version:2,paymentPayload:n,paymentRequirements:r})});return i.ok?{...await i.json(),network:r.network}:{success:!1,network:r.network,errorReason:`facilitator_error_${i.status}`}}catch(n){let i=n instanceof F?`facilitator_error_${n.status}`:n instanceof Error&&n.name==="AbortError"?"facilitator_timeout":n instanceof Error?n.message:"unexpected_settle_error";return{success:!1,network:r.network,errorReason:i}}}};function Ct(t){if(ae(t))return{address:oe,decimals:6};let e=Je[t];if(e){let r=Ge[e]?.decimals??6;return{address:e,decimals:r}}return{address:oe,decimals:6}}function Ye(t){try{let e=q(t);return e?.accepted?.amount??e?.accepted?.maxAmountRequired}catch{return}}function W(t){let{payTo:e,facilitatorUrl:r=H,network:n=k,defaultTimeoutSeconds:i=60}=t,s=t.asset??Ct(n),h=t.scheme??"exact";if(h==="tab"&&!ae(n))throw new Error(`scheme 'tab' is SVM-only; got network "${n}"`);let c=new le(r),a=null,m=new Map,l=3e4,o=Date.now();function y(u){let g=(u.maxTimeoutSeconds||i)*1e3;if(m.set(u.payTo,{accept:u,expiresAt:Date.now()+g}),Date.now()-o>l){let A=Date.now();for(let[S,I]of m)I.expiresAt<A&&m.delete(S);o=A}}function d(u){let g=m.get(u);if(g){if(g.expiresAt<Date.now()){m.delete(u);return}return g.accept}}async function f(u){return typeof e=="string"?e:e(u||{})}async function b(){if(a||(a=await c.getNetworkExtra(n)),ae(n)&&!a?.feePayer)throw new Error(`Facilitator does not provide feePayer for network "${n}"`);return{...a?.feePayer?{feePayer:a.feePayer}:{},decimals:a?.decimals??s.decimals,name:a?.name,version:a?.version,...h==="batch-settlement"&&a?.receiverAuthorizer?{receiverAuthorizer:a.receiverAuthorizer}:{},...h==="tab"?{voucherHeader:"x-tab-voucher",registrationEncoding:"base64(188-byte sessionRegisterMessage)"}:{}}}async function V(u,g){let{amountAtomic:A,timeoutSeconds:S=i}=g,I=await b(),U={scheme:h,network:n,amount:A,maxAmountRequired:A,asset:s.address,payTo:u,maxTimeoutSeconds:S,extra:I};return y(U),U}async function L(u){let g=await f({amountAtomic:u.amountAtomic,resourceUrl:u.resourceUrl});return V(g,u)}async function ue(u){let{resourceUrl:g,description:A,mimeType:S="application/json"}=u,I={url:g,description:A,mimeType:S},U=await L(u);return{x402Version:2,resource:I,accepts:[U],error:"Payment required"}}function B(u){return ce(u)}function j(u){return{status:402,headers:{"PAYMENT-REQUIRED":B(u)},body:{}}}async function me(u,g){if(!g){let A=await f({paymentHeader:u});g=d(A),g||(g=await V(A,{amountAtomic:Ye(u)??"0",resourceUrl:""}))}return c.verifyPayment(u,g)}async function X(u,g){if(!g){let A=await f({paymentHeader:u});g=d(A),g||(g=await V(A,{amountAtomic:Ye(u)??"0",resourceUrl:""}))}return c.settlePayment(u,g)}return{buildRequirements:ue,encodeRequirements:B,create402Response:j,verifyPayment:me,settlePayment:X,getPaymentAccept:L,network:n,assetDecimals:s.decimals,facilitator:c}}var Pt={"solana:mainnet":k};function Rt(t){let e=Pt[t.network];if(!e)throw new Error(`tabChallengeMiddleware: unsupported network "${t.network}"`);let r=typeof t.sellerPubkey=="string"?t.sellerPubkey:t.sellerPubkey.toBase58();new Et(r);let n=W({payTo:r,network:e,scheme:"tab",facilitatorUrl:t.facilitatorUrl}),i=P(t.perUnit);return async(s,h,c)=>{if(s.headers[$])return c();try{let a=`${s.protocol}://${s.get("host")}${s.originalUrl}`,m=await n.buildRequirements({amountAtomic:i,resourceUrl:a,description:t.description}),l=n.create402Response(m);h.set(l.headers).status(l.status).json(l.body)}catch(a){let m=a?.message??String(a);h.status(503).set({"Retry-After":"5"}).json({error:"challenge_unavailable",detail:m})}}}import{PublicKey as Tt}from"@solana/web3.js";var _t={"solana:mainnet":k};function kt(t){let e=_t[t.network];if(!e)throw new Error(`tabOrExactMiddleware: unsupported network "${t.network}"`);let r=typeof t.sellerPubkey=="string"?t.sellerPubkey:t.sellerPubkey.toBase58();new Tt(r);let n=W({payTo:r,network:e,scheme:"tab",facilitatorUrl:t.facilitatorUrl}),i=W({payTo:r,network:e,scheme:"exact",facilitatorUrl:t.facilitatorUrl}),s=P(t.perUnit),h=ke({connection:t.connection,sellerPubkey:r,network:t.network,perUnit:t.perUnit,settle:"on-close",facilitatorUrl:t.facilitatorUrl,lockCadence:t.lockCadence});return async(c,a,m)=>{if(c.headers[$])return h(c,a,m);let l=`${c.protocol}://${c.get("host")}${c.originalUrl}`,o=c.headers["payment-signature"];if(o){let y;try{y=await i.getPaymentAccept({amountAtomic:s,resourceUrl:l,description:t.description})}catch(d){let f=d?.message??String(d);a.status(503).set({"Retry-After":"5"}).json({error:"challenge_unavailable",detail:f});return}try{let d=await i.verifyPayment(o,y);if(!d.isValid){a.status(402).json({error:"Payment verification failed",reason:d.invalidReason});return}let f=await i.settlePayment(o,y);if(!f.success){a.status(402).json({error:"Payment settlement failed",reason:f.errorReason});return}return c.x402={transaction:f.transaction,payer:d.payer??"",network:f.network||e},a.setHeader("PAYMENT-RESPONSE",ce({success:!0,transaction:f.transaction,network:f.network||e,payer:d.payer??""})),m()}catch{a.status(500).json({error:"Payment processing error"});return}}try{let y={amountAtomic:s,resourceUrl:l,description:t.description},[d,f]=await Promise.all([n.buildRequirements(y),i.buildRequirements(y)]),b={...d,accepts:[...d.accepts,...f.accepts]};a.set({"PAYMENT-REQUIRED":n.encodeRequirements(b)}).status(402).json({error:"Payment required",accepts:b.accepts,resource:b.resource})}catch(y){let d=y?.message??String(y);a.status(503).set({"Retry-After":"5"}).json({error:"challenge_unavailable",detail:d})}}}export{ge as FileChannelLedger,Oe as FileVoucherStore,M as InMemoryChannelLedger,Ue as InMemoryVoucherStore,E as InvalidRegistrationError,x as InvalidVoucherError,_ as InvalidVoucherSignatureError,N as OnChainVerificationError,fe as RedisChannelLedger,C as ScopeViolationError,$ as TAB_VOUCHER_HEADER,ye as deserializeChannelLedgerEntry,Ee as enforceScope,ht as openSse,Se as parseRegistration,gt as requireTab,he as serializeChannelLedgerEntry,Rt as tabChallengeMiddleware,ke as tabMiddleware,kt as tabOrExactMiddleware,xe as verifyRegistrationOnChain,Ce as verifyVoucherSignature};
6
+ `),t.end())}return{charge:l,send:o,end:y}}import{promises as K}from"fs";import{join as bt,dirname as vt}from"path";function wt(t){return{payload:t.payload,sessionPublicKey:Ue(t.sessionPublicKey),sessionRegistration:Ue(t.sessionRegistration),sessionSignature:Ue(t.sessionSignature)}}function St(t){return{payload:t.payload,sessionPublicKey:$e(t.sessionPublicKey),sessionRegistration:$e(t.sessionRegistration),sessionSignature:$e(t.sessionSignature)}}function Ue(t){let e="";for(let r of t)e+=r.toString(16).padStart(2,"0");return e}function $e(t){if(t.length%2!==0)throw new Error(`hex length must be even, got ${t.length}`);let e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(t.substr(r*2,2),16);return e}var Ve=class{map=new Map;async get(e){return this.map.get(e)??null}async set(e,r){this.map.set(e,r)}async delete(e){this.map.delete(e)}},Le=class{constructor(e){this.dir=e}pathFor(e){if(!/^[a-z0-9_-]+$/i.test(e))throw new Error(`unsafe channelId for filesystem: ${e}`);return bt(this.dir,`${e}.json`)}async get(e){try{let r=await K.readFile(this.pathFor(e),"utf8");return St(JSON.parse(r))}catch(r){if(r?.code==="ENOENT")return null;throw r}}async set(e,r){let n=this.pathFor(e);await K.mkdir(vt(n),{recursive:!0});let i=`${n}.tmp`;await K.writeFile(i,JSON.stringify(wt(r))),await K.rename(i,n)}async delete(e){try{await K.unlink(this.pathFor(e))}catch(r){if(r?.code!=="ENOENT")throw r}}};import{PublicKey as Nt}from"@solana/web3.js";var N="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Xe="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Je="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";var z="eip155:8453",re="eip155:84532",ne="eip155:42161",ie="eip155:137",se="eip155:10",oe="eip155:43114",ae="eip155:56",H="eip155:480",q="eip155:143",F="eip155:4663",W="eip155:1187947933",j="eip155:324705682",ce="eip155:1";var le="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";var Ge="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",xt="0x55d398326f99059fF775485246999027B3197955",Ye="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",Ct="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",Ze={[ae]:Ye,[z]:Ge,[re]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[ne]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[ie]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[se]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[oe]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[H]:"0x79A02482A880bCE3F13e09Da970dC34db4CD24d1",[q]:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",[F]:Ct,[W]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[j]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[ce]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},Qe={[xt]:{symbol:"USDT",decimals:18},[Ye]:{symbol:"USDC",decimals:18}};var Jr={[H]:{name:"USDC",version:"2"},[q]:{name:"USDC",version:"2"},[F]:{name:"Global Dollar",version:"1"},[W]:{name:"Bridged USDC (SKALE Bridge)",version:"2"},[j]:{name:"Bridged USDC (SKALE Bridge)",version:"2"}};var Gr={[ae]:56,[z]:8453,[re]:84532,[ne]:42161,[ie]:137,[se]:10,[oe]:43114,[H]:480,[q]:143,[F]:4663,[W]:1187947933,[j]:324705682,[ce]:1},Yr={[N]:"https://api.dexter.cash/api/solana/rpc",[Xe]:"https://api.devnet.solana.com",[Je]:"https://api.testnet.solana.com"},Et={[ae]:"https://api.dexter.cash/api/evm/bsc/rpc",[z]:"https://api.dexter.cash/api/base/rpc",[re]:"https://sepolia.base.org",[ne]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[ie]:"https://api.dexter.cash/api/evm/polygon/rpc",[se]:"https://api.dexter.cash/api/evm/optimism/rpc",[oe]:"https://api.dexter.cash/api/evm/avalanche/rpc",[H]:"https://worldchain-mainnet.g.alchemy.com/public",[q]:"https://rpc.monad.xyz",[F]:"https://rpc.mainnet.chain.robinhood.com",[W]:"https://skale-base.skalenodes.com/v1/base",[j]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[ce]:"https://eth.llamarpc.com"},X="https://x402.dexter.cash";function ue(t){return t.startsWith("solana:")||t==="solana"}function Rt(t){if(typeof Buffer<"u")return Buffer.from(t,"utf-8").toString("base64");let e=new TextEncoder().encode(t),r="";for(let n=0;n<e.length;n++)r+=String.fromCharCode(e[n]);return btoa(r)}function Tt(t){if(typeof Buffer<"u")return Buffer.from(t,"base64").toString("utf-8");let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return new TextDecoder().decode(r)}function me(t){return Rt(JSON.stringify(t))}function J(t){return JSON.parse(Tt(t))}function Pt(t){if(t instanceof TypeError)return!0;if(t&&typeof t=="object"&&"status"in t){let e=t.status;return e>=500&&e<600}return!1}var G=class extends Error{status;body;constructor(e,r){super(`HTTP ${e}`),this.status=e,this.body=r}},de=class{facilitatorUrl;cachedSupported=null;cacheTime=0;CACHE_TTL_MS=6e4;timeoutMs;maxRetries;retryBaseMs;constructor(e=X,r){this.facilitatorUrl=e.replace(/\/$/,""),this.timeoutMs=r?.timeoutMs??1e4,this.maxRetries=r?.maxRetries??3,this.retryBaseMs=r?.retryBaseMs??500}async fetchWithTimeout(e,r){let n=new AbortController,i=setTimeout(()=>n.abort(),this.timeoutMs);try{return await fetch(e,{...r,signal:n.signal})}finally{clearTimeout(i)}}async fetchWithRetry(e,r){let n;for(let i=0;i<this.maxRetries;i++)try{let s=await this.fetchWithTimeout(e,r);if(!s.ok&&s.status>=500)throw new G(s.status,await s.text());return s}catch(s){if(n=s,i<this.maxRetries-1&&Pt(s)){let h=this.retryBaseMs*Math.pow(2,i);await new Promise(c=>setTimeout(c,h));continue}throw s}throw n}async getSupported(){let e=Date.now();if(this.cachedSupported&&e-this.cacheTime<this.CACHE_TTL_MS)return this.cachedSupported;let r=await this.fetchWithTimeout(`${this.facilitatorUrl}/supported`);if(!r.ok)throw new Error(`Facilitator /supported returned ${r.status}`);return this.cachedSupported=await r.json(),this.cacheTime=e,this.cachedSupported}async getFeePayer(e){let n=(await this.getSupported()).kinds.find(i=>i.x402Version===2&&(i.scheme==="exact"||i.scheme==="exact-approval")&&i.network===e);if(!n)throw new Error(`Facilitator does not support network "${e}" with a recognized scheme`);return n.extra?.feePayer}async getNetworkExtra(e){return(await this.getSupported()).kinds.find(i=>i.x402Version===2&&(i.scheme==="exact"||i.scheme==="exact-approval"||i.scheme==="batch-settlement")&&i.network===e)?.extra}async verifyPayment(e,r){try{let n=J(e),i=await this.fetchWithRetry(`${this.facilitatorUrl}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x402Version:2,paymentPayload:n,paymentRequirements:r})});return i.ok?await i.json():{isValid:!1,invalidReason:`facilitator_error_${i.status}`}}catch(n){return{isValid:!1,invalidReason:n instanceof G?`facilitator_error_${n.status}`:n instanceof Error&&n.name==="AbortError"?"facilitator_timeout":n instanceof Error?n.message:"unexpected_verify_error"}}}async settlePayment(e,r){try{let n=J(e),i=await this.fetchWithRetry(`${this.facilitatorUrl}/settle`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x402Version:2,paymentPayload:n,paymentRequirements:r})});return i.ok?{...await i.json(),network:r.network}:{success:!1,network:r.network,errorReason:`facilitator_error_${i.status}`}}catch(n){let i=n instanceof G?`facilitator_error_${n.status}`:n instanceof Error&&n.name==="AbortError"?"facilitator_timeout":n instanceof Error?n.message:"unexpected_settle_error";return{success:!1,network:r.network,errorReason:i}}}};function _t(t){if(ue(t))return{address:le,decimals:6};let e=Ze[t];if(e){let r=Qe[e]?.decimals??6;return{address:e,decimals:r}}return{address:le,decimals:6}}function et(t){try{let e=J(t);return e?.accepted?.amount??e?.accepted?.maxAmountRequired}catch{return}}function Y(t){let{payTo:e,facilitatorUrl:r=X,network:n=N,defaultTimeoutSeconds:i=60}=t,s=t.asset??_t(n),h=t.scheme??"exact";if(h==="tab"&&!ue(n))throw new Error(`scheme 'tab' is SVM-only; got network "${n}"`);let c=new de(r),a=null,m=new Map,l=3e4,o=Date.now();function y(u){let g=(u.maxTimeoutSeconds||i)*1e3;if(m.set(u.payTo,{accept:u,expiresAt:Date.now()+g}),Date.now()-o>l){let A=Date.now();for(let[S,I]of m)I.expiresAt<A&&m.delete(S);o=A}}function d(u){let g=m.get(u);if(g){if(g.expiresAt<Date.now()){m.delete(u);return}return g.accept}}async function f(u){return typeof e=="string"?e:e(u||{})}async function b(){if(a||(a=await c.getNetworkExtra(n)),ue(n)&&!a?.feePayer)throw new Error(`Facilitator does not provide feePayer for network "${n}"`);return{...a?.feePayer?{feePayer:a.feePayer}:{},decimals:a?.decimals??s.decimals,name:a?.name,version:a?.version,...h==="batch-settlement"&&a?.receiverAuthorizer?{receiverAuthorizer:a.receiverAuthorizer}:{},...h==="tab"?{voucherHeader:"x-tab-voucher",registrationEncoding:"base64(188-byte sessionRegisterMessage)"}:{}}}async function V(u,g){let{amountAtomic:A,timeoutSeconds:S=i}=g,I=await b(),O={scheme:h,network:n,amount:A,maxAmountRequired:A,asset:s.address,payTo:u,maxTimeoutSeconds:S,extra:I};return y(O),O}async function L(u){let g=await f({amountAtomic:u.amountAtomic,resourceUrl:u.resourceUrl});return V(g,u)}async function pe(u){let{resourceUrl:g,description:A,mimeType:S="application/json"}=u,I={url:g,description:A,mimeType:S},O=await L(u);return{x402Version:2,resource:I,accepts:[O],error:"Payment required"}}function B(u){return me(u)}function Z(u){return{status:402,headers:{"PAYMENT-REQUIRED":B(u)},body:{}}}async function ge(u,g){if(!g){let A=await f({paymentHeader:u});g=d(A),g||(g=await V(A,{amountAtomic:et(u)??"0",resourceUrl:""}))}return c.verifyPayment(u,g)}async function Q(u,g){if(!g){let A=await f({paymentHeader:u});g=d(A),g||(g=await V(A,{amountAtomic:et(u)??"0",resourceUrl:""}))}return c.settlePayment(u,g)}return{buildRequirements:pe,encodeRequirements:B,create402Response:Z,verifyPayment:ge,settlePayment:Q,getPaymentAccept:L,network:n,assetDecimals:s.decimals,facilitator:c}}var kt={"solana:mainnet":N};function It(t){let e=kt[t.network];if(!e)throw new Error(`tabChallengeMiddleware: unsupported network "${t.network}"`);let r=typeof t.sellerPubkey=="string"?t.sellerPubkey:t.sellerPubkey.toBase58();new Nt(r);let n=Y({payTo:r,network:e,scheme:"tab",facilitatorUrl:t.facilitatorUrl}),i=R(t.perUnit);return async(s,h,c)=>{if(s.headers[$])return c();try{let a=`${s.protocol}://${s.get("host")}${s.originalUrl}`,m=await n.buildRequirements({amountAtomic:i,resourceUrl:a,description:t.description}),l=n.create402Response(m);h.set(l.headers).status(l.status).json(l.body)}catch(a){let m=a?.message??String(a);h.status(503).set({"Retry-After":"5"}).json({error:"challenge_unavailable",detail:m})}}}import{PublicKey as Ot}from"@solana/web3.js";var Ut={"solana:mainnet":N};function $t(t){let e=Ut[t.network];if(!e)throw new Error(`tabOrExactMiddleware: unsupported network "${t.network}"`);let r=typeof t.sellerPubkey=="string"?t.sellerPubkey:t.sellerPubkey.toBase58();new Ot(r);let n=Y({payTo:r,network:e,scheme:"tab",facilitatorUrl:t.facilitatorUrl}),i=Y({payTo:r,network:e,scheme:"exact",facilitatorUrl:t.facilitatorUrl}),s=R(t.perUnit),h=Oe({connection:t.connection,sellerPubkey:r,network:t.network,perUnit:t.perUnit,settle:"on-close",facilitatorUrl:t.facilitatorUrl,lockCadence:t.lockCadence});return async(c,a,m)=>{if(c.headers[$])return h(c,a,m);let l=`${c.protocol}://${c.get("host")}${c.originalUrl}`,o=c.headers["payment-signature"];if(o){let y;try{y=await i.getPaymentAccept({amountAtomic:s,resourceUrl:l,description:t.description})}catch(d){let f=d?.message??String(d);a.status(503).set({"Retry-After":"5"}).json({error:"challenge_unavailable",detail:f});return}try{let d=await i.verifyPayment(o,y);if(!d.isValid){a.status(402).json({error:"Payment verification failed",reason:d.invalidReason});return}let f=await i.settlePayment(o,y);if(!f.success){a.status(402).json({error:"Payment settlement failed",reason:f.errorReason});return}return c.x402={transaction:f.transaction,payer:d.payer??"",network:f.network||e},a.setHeader("PAYMENT-RESPONSE",me({success:!0,transaction:f.transaction,network:f.network||e,payer:d.payer??""})),m()}catch{a.status(500).json({error:"Payment processing error"});return}}try{let y={amountAtomic:s,resourceUrl:l,description:t.description},[d,f]=await Promise.all([n.buildRequirements(y),i.buildRequirements(y)]),b={...d,accepts:[...d.accepts,...f.accepts]};a.set({"PAYMENT-REQUIRED":n.encodeRequirements(b)}).status(402).json({error:"Payment required",accepts:b.accepts,resource:b.resource})}catch(y){let d=y?.message??String(y);a.status(503).set({"Retry-After":"5"}).json({error:"challenge_unavailable",detail:d})}}}export{fe as FileChannelLedger,Le as FileVoucherStore,D as InMemoryChannelLedger,Ve as InMemoryVoucherStore,E as InvalidRegistrationError,x as InvalidVoucherError,_ as InvalidVoucherSignatureError,k as OnChainVerificationError,ve as RedisChannelLedger,C as ScopeViolationError,$ as TAB_VOUCHER_HEADER,be as deserializeChannelLedgerEntry,Pe as enforceScope,At as openSse,Ee as parseRegistration,ft as requireTab,Ae as serializeChannelLedgerEntry,It as tabChallengeMiddleware,Oe as tabMiddleware,$t as tabOrExactMiddleware,Re as verifyRegistrationOnChain,Te as verifyVoucherSignature};
@@ -1 +1 @@
1
- "use strict";var T=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var P=Object.prototype.hasOwnProperty;var F=(t,e)=>{for(var s in e)T(t,s,{get:e[s],enumerable:!0})},$=(t,e,s,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of y(e))!P.call(t,r)&&r!==s&&T(t,r,{get:()=>e[r],enumerable:!(n=W(e,r))||n.enumerable});return t};var V=t=>$(T({},"__esModule",{value:!0}),t);var X={};F(X,{EVM_RPC_URLS:()=>B,SOLANA_RPC_URLS:()=>D,fromAtomicUnits:()=>L,getChainDisplayName:()=>M,getChainFamily:()=>_,getChainName:()=>g,getDefaultRpcUrl:()=>K,getExplorerUrl:()=>U,toAtomicUnits:()=>I});module.exports=V(X);var d="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",i="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",b="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";var c="eip155:8453",p="eip155:84532",E="eip155:42161",l="eip155:137",A="eip155:10",h="eip155:43114",m="eip155:56",u="eip155:1187947933",f="eip155:324705682",N="eip155:1";var H="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",J="0x55d398326f99059fF775485246999027B3197955",C="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",Z={[m]:C,[c]:H,[p]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[E]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[l]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[A]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[h]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[u]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[f]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[N]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},j={[J]:{symbol:"USDT",decimals:18},[C]:{symbol:"USDC",decimals:18}};var Q={[m]:56,[c]:8453,[p]:84532,[E]:42161,[l]:137,[A]:10,[h]:43114,[u]:1187947933,[f]:324705682,[N]:1},D={[d]:"https://api.dexter.cash/api/solana/rpc",[i]:"https://api.devnet.solana.com",[b]:"https://api.testnet.solana.com"},B={[m]:"https://api.dexter.cash/api/evm/bsc/rpc",[c]:"https://api.dexter.cash/api/base/rpc",[p]:"https://sepolia.base.org",[E]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[l]:"https://api.dexter.cash/api/evm/polygon/rpc",[A]:"https://api.dexter.cash/api/evm/optimism/rpc",[h]:"https://api.dexter.cash/api/evm/avalanche/rpc",[u]:"https://skale-base.skalenodes.com/v1/base",[f]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[N]:"https://eth.llamarpc.com"};function I(t,e){if(!Number.isFinite(t))throw new Error(`toAtomicUnits: amount must be finite, got ${t}`);if(t<0)throw new Error(`toAtomicUnits: amount must be non-negative, got ${t}`);if(!Number.isInteger(e)||e<0)throw new Error(`toAtomicUnits: decimals must be a non-negative integer, got ${e}`);let s=Y(Math.abs(t)),[n,r=""]=s.split("."),x=r.slice(0,e).padEnd(e,"0");return BigInt(n+x).toString()}function Y(t){let e=t.toString();if(!/[eE]/.test(e))return e;let[s,n]=e.split(/[eE]/),r=parseInt(n,10),x=s.startsWith("-"),R=x?s.slice(1):s,[O,v=""]=R.split("."),a=O+v,o=O.length+r,S;return o<=0?S="0."+"0".repeat(-o)+a:o>=a.length?S=a+"0".repeat(o-a.length):S=a.slice(0,o)+"."+a.slice(o),(x?"-":"")+S}function L(t,e){let s=Math.pow(10,e);return Number(t)/s}function G(t){return t.startsWith("solana:")||t==="solana"}function q(t){return t.startsWith("eip155:")||["base","ethereum","arbitrum"].includes(t)}function _(t){return G(t)?"solana":q(t)?"evm":"unknown"}function K(t){let e=_(t);if(e==="solana")return t.includes("devnet")||t===i?"https://api.devnet.solana.com":t.includes("testnet")||t===b?"https://api.testnet.solana.com":"https://api.dexter.cash/api/solana/rpc";if(e==="evm"){if(t.startsWith("eip155:"))switch(t.split(":")[1]){case"8453":return"https://api.dexter.cash/api/base/rpc";case"84532":return"https://sepolia.base.org";case"1":return"https://eth.llamarpc.com";case"42161":return"https://arb1.arbitrum.io/rpc";default:return"https://api.dexter.cash/api/base/rpc"}return t==="base"?"https://api.dexter.cash/api/base/rpc":t==="ethereum"?"https://eth.llamarpc.com":t==="arbitrum"?"https://arb1.arbitrum.io/rpc":"https://api.dexter.cash/api/base/rpc"}return"https://api.dexter.cash/api/solana/rpc"}function g(t){return{[d]:"Solana",[i]:"Solana Devnet",[b]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[c]:"Base",[p]:"Base Sepolia",[N]:"Ethereum",[E]:"Arbitrum",[l]:"Polygon",[A]:"Optimism",[h]:"Avalanche",[m]:"BSC",[u]:"SKALE Base",[f]:"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"}[t]||t}function M(t,e){let s=g(t);return s===t?e:s}function U(t,e){let s=_(e);if(s==="solana")return e.includes("devnet")||e===i?`https://solscan.io/tx/${t}?cluster=devnet`:`https://www.orbmarkets.io/tx/${t}`;if(s==="evm"){let n="8453";switch(e.startsWith("eip155:")?n=e.split(":")[1]:e==="ethereum"?n="1":e==="arbitrum"?n="42161":e==="polygon"?n="137":e==="optimism"?n="10":e==="avalanche"?n="43114":e==="bsc"?n="56":e==="skale-base"?n="1187947933":e==="skale-base-sepolia"&&(n="324705682"),n){case"8453":return`https://basescan.org/tx/${t}`;case"84532":return`https://sepolia.basescan.org/tx/${t}`;case"1":return`https://etherscan.io/tx/${t}`;case"42161":return`https://arbiscan.io/tx/${t}`;case"137":return`https://polygonscan.com/tx/${t}`;case"10":return`https://optimistic.etherscan.io/tx/${t}`;case"43114":return`https://snowtrace.io/tx/${t}`;case"56":return`https://bscscan.com/tx/${t}`;case"1187947933":return`https://elated-tan-skat.explorer.mainnet.skalenodes.com/tx/${t}`;case"324705682":return`https://base-sepolia-testnet.explorer.skalenodes.com/tx/${t}`;default:return`https://basescan.org/tx/${t}`}}return`https://solscan.io/tx/${t}`}0&&(module.exports={EVM_RPC_URLS,SOLANA_RPC_URLS,fromAtomicUnits,getChainDisplayName,getChainFamily,getChainName,getDefaultRpcUrl,getExplorerUrl,toAtomicUnits});
1
+ "use strict";var g=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var V=(t,e)=>{for(var o in e)g(t,o,{get:e[o],enumerable:!0})},G=(t,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of $(e))!H.call(t,n)&&n!==o&&g(t,n,{get:()=>e[n],enumerable:!(s=F(e,n))||s.enumerable});return t};var J=t=>G(g({},"__esModule",{value:!0}),t);var Q={};V(Q,{EVM_RPC_URLS:()=>E,SOLANA_RPC_URLS:()=>K,fromAtomicUnits:()=>v,getChainDisplayName:()=>U,getChainFamily:()=>R,getChainName:()=>C,getDefaultRpcUrl:()=>W,getExplorerUrl:()=>y,toAtomicUnits:()=>L});module.exports=J(Q);var D="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",T="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",O="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";var N="eip155:8453",m="eip155:84532",h="eip155:42161",d="eip155:137",_="eip155:10",f="eip155:43114",x="eip155:56",r="eip155:480",a="eip155:143",i="eip155:4663",c="eip155:1187947933",p="eip155:324705682",b="eip155:1";var Y="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",q="0x55d398326f99059fF775485246999027B3197955",M="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",X="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",tt={[x]:M,[N]:Y,[m]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[h]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[d]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[_]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[f]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[r]:"0x79A02482A880bCE3F13e09Da970dC34db4CD24d1",[a]:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",[i]:X,[c]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[p]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[b]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},et={[q]:{symbol:"USDT",decimals:18},[M]:{symbol:"USDC",decimals:18}};var st={[r]:{name:"USDC",version:"2"},[a]:{name:"USDC",version:"2"},[i]:{name:"Global Dollar",version:"1"},[c]:{name:"Bridged USDC (SKALE Bridge)",version:"2"},[p]:{name:"Bridged USDC (SKALE Bridge)",version:"2"}};var ot={[x]:56,[N]:8453,[m]:84532,[h]:42161,[d]:137,[_]:10,[f]:43114,[r]:480,[a]:143,[i]:4663,[c]:1187947933,[p]:324705682,[b]:1},K={[D]:"https://api.dexter.cash/api/solana/rpc",[T]:"https://api.devnet.solana.com",[O]:"https://api.testnet.solana.com"},E={[x]:"https://api.dexter.cash/api/evm/bsc/rpc",[N]:"https://api.dexter.cash/api/base/rpc",[m]:"https://sepolia.base.org",[h]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[d]:"https://api.dexter.cash/api/evm/polygon/rpc",[_]:"https://api.dexter.cash/api/evm/optimism/rpc",[f]:"https://api.dexter.cash/api/evm/avalanche/rpc",[r]:"https://worldchain-mainnet.g.alchemy.com/public",[a]:"https://rpc.monad.xyz",[i]:"https://rpc.mainnet.chain.robinhood.com",[c]:"https://skale-base.skalenodes.com/v1/base",[p]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[b]:"https://eth.llamarpc.com"};function L(t,e){if(!Number.isFinite(t))throw new Error(`toAtomicUnits: amount must be finite, got ${t}`);if(t<0)throw new Error(`toAtomicUnits: amount must be non-negative, got ${t}`);if(!Number.isInteger(e)||e<0)throw new Error(`toAtomicUnits: decimals must be a non-negative integer, got ${e}`);let o=z(Math.abs(t)),[s,n=""]=o.split("."),S=n.slice(0,e).padEnd(e,"0");return BigInt(s+S).toString()}function z(t){let e=t.toString();if(!/[eE]/.test(e))return e;let[o,s]=e.split(/[eE]/),n=parseInt(s,10),S=o.startsWith("-"),B=S?o.slice(1):o,[I,P=""]=B.split("."),l=I+P,A=I.length+n,u;return A<=0?u="0."+"0".repeat(-A)+l:A>=l.length?u=l+"0".repeat(A-l.length):u=l.slice(0,A)+"."+l.slice(A),(S?"-":"")+u}function v(t,e){let o=Math.pow(10,e);return Number(t)/o}function Z(t){return t.startsWith("solana:")||t==="solana"}var w=["base","base-sepolia","ethereum","arbitrum","polygon","optimism","avalanche","bsc","world","monad","robinhood","skale-base","skale-base-sepolia"];function j(t){return t.startsWith("eip155:")||w.includes(t)}function R(t){return Z(t)?"solana":j(t)?"evm":"unknown"}function W(t){let e=R(t);if(e==="solana")return t.includes("devnet")||t===T?"https://api.devnet.solana.com":t.includes("testnet")||t===O?"https://api.testnet.solana.com":"https://api.dexter.cash/api/solana/rpc";if(e==="evm"){if(E[t])return E[t];let s={base:N,"base-sepolia":m,ethereum:b,arbitrum:h,polygon:d,optimism:_,avalanche:f,bsc:x,world:r,monad:a,robinhood:i,"skale-base":c,"skale-base-sepolia":p}[t];return s&&E[s]?E[s]:"https://api.dexter.cash/api/base/rpc"}return"https://api.dexter.cash/api/solana/rpc"}function C(t){return{[D]:"Solana",[T]:"Solana Devnet",[O]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[N]:"Base",[m]:"Base Sepolia",[b]:"Ethereum",[h]:"Arbitrum",[d]:"Polygon",[_]:"Optimism",[f]:"Avalanche",[x]:"BSC",[r]:"World Chain",[a]:"Monad",[i]:"Robinhood Chain",[c]:"SKALE Base",[p]:"SKALE Base Sepolia",base:"Base","base-sepolia":"Base Sepolia",ethereum:"Ethereum",arbitrum:"Arbitrum",polygon:"Polygon",optimism:"Optimism",avalanche:"Avalanche",bsc:"BSC",world:"World Chain",monad:"Monad",robinhood:"Robinhood Chain","skale-base":"SKALE Base","skale-base-sepolia":"SKALE Base Sepolia"}[t]||t}function U(t,e){let o=C(t);return o===t?e:o}function y(t,e){let o=R(e);if(o==="solana")return e.includes("devnet")||e===T?`https://solscan.io/tx/${t}?cluster=devnet`:`https://www.orbmarkets.io/tx/${t}`;if(o==="evm"){let s="8453";switch(e.startsWith("eip155:")?s=e.split(":")[1]:e==="ethereum"?s="1":e==="arbitrum"?s="42161":e==="polygon"?s="137":e==="optimism"?s="10":e==="avalanche"?s="43114":e==="bsc"?s="56":e==="world"?s="480":e==="monad"?s="143":e==="robinhood"?s="4663":e==="skale-base"?s="1187947933":e==="skale-base-sepolia"&&(s="324705682"),s){case"8453":return`https://basescan.org/tx/${t}`;case"84532":return`https://sepolia.basescan.org/tx/${t}`;case"1":return`https://etherscan.io/tx/${t}`;case"42161":return`https://arbiscan.io/tx/${t}`;case"137":return`https://polygonscan.com/tx/${t}`;case"10":return`https://optimistic.etherscan.io/tx/${t}`;case"43114":return`https://snowtrace.io/tx/${t}`;case"56":return`https://bscscan.com/tx/${t}`;case"480":return`https://worldscan.org/tx/${t}`;case"143":return`https://monadvision.com/tx/${t}`;case"4663":return`https://robinhoodchain.blockscout.com/tx/${t}`;case"1187947933":return`https://elated-tan-skat.explorer.mainnet.skalenodes.com/tx/${t}`;case"324705682":return`https://base-sepolia-testnet.explorer.skalenodes.com/tx/${t}`;default:return`https://basescan.org/tx/${t}`}}return`https://solscan.io/tx/${t}`}0&&(module.exports={EVM_RPC_URLS,SOLANA_RPC_URLS,fromAtomicUnits,getChainDisplayName,getChainFamily,getChainName,getDefaultRpcUrl,getExplorerUrl,toAtomicUnits});
@@ -1,4 +1,4 @@
1
- export { q as EVM_RPC_URLS, p as SOLANA_RPC_URLS } from '../constants-D41hDAG6.cjs';
1
+ export { s as EVM_RPC_URLS, r as SOLANA_RPC_URLS } from '../constants-Icc4CXNG.cjs';
2
2
 
3
3
  /**
4
4
  * Utility Functions
@@ -1,4 +1,4 @@
1
- export { q as EVM_RPC_URLS, p as SOLANA_RPC_URLS } from '../constants-D41hDAG6.js';
1
+ export { s as EVM_RPC_URLS, r as SOLANA_RPC_URLS } from '../constants-Icc4CXNG.js';
2
2
 
3
3
  /**
4
4
  * Utility Functions
@@ -1 +1 @@
1
- var _="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",o="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",S="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";var i="eip155:8453",c="eip155:84532",p="eip155:42161",E="eip155:137",l="eip155:10",A="eip155:43114",h="eip155:56",m="eip155:1187947933",u="eip155:324705682",f="eip155:1";var D="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",B="0x55d398326f99059fF775485246999027B3197955",R="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",$={[h]:R,[i]:D,[c]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[p]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[E]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[l]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[A]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[m]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[u]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[f]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},V={[B]:{symbol:"USDT",decimals:18},[R]:{symbol:"USDC",decimals:18}};var H={[h]:56,[i]:8453,[c]:84532,[p]:42161,[E]:137,[l]:10,[A]:43114,[m]:1187947933,[u]:324705682,[f]:1},I={[_]:"https://api.dexter.cash/api/solana/rpc",[o]:"https://api.devnet.solana.com",[S]:"https://api.testnet.solana.com"},L={[h]:"https://api.dexter.cash/api/evm/bsc/rpc",[i]:"https://api.dexter.cash/api/base/rpc",[c]:"https://sepolia.base.org",[p]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[E]:"https://api.dexter.cash/api/evm/polygon/rpc",[l]:"https://api.dexter.cash/api/evm/optimism/rpc",[A]:"https://api.dexter.cash/api/evm/avalanche/rpc",[m]:"https://skale-base.skalenodes.com/v1/base",[u]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[f]:"https://eth.llamarpc.com"};function K(t,e){if(!Number.isFinite(t))throw new Error(`toAtomicUnits: amount must be finite, got ${t}`);if(t<0)throw new Error(`toAtomicUnits: amount must be non-negative, got ${t}`);if(!Number.isInteger(e)||e<0)throw new Error(`toAtomicUnits: decimals must be a non-negative integer, got ${e}`);let n=M(Math.abs(t)),[s,b=""]=n.split("."),N=b.slice(0,e).padEnd(e,"0");return BigInt(s+N).toString()}function M(t){let e=t.toString();if(!/[eE]/.test(e))return e;let[n,s]=e.split(/[eE]/),b=parseInt(s,10),N=n.startsWith("-"),d=N?n.slice(1):n,[g,C=""]=d.split("."),r=g+C,a=g.length+b,x;return a<=0?x="0."+"0".repeat(-a)+r:a>=r.length?x=r+"0".repeat(a-r.length):x=r.slice(0,a)+"."+r.slice(a),(N?"-":"")+x}function U(t,e){let n=Math.pow(10,e);return Number(t)/n}function v(t){return t.startsWith("solana:")||t==="solana"}function W(t){return t.startsWith("eip155:")||["base","ethereum","arbitrum"].includes(t)}function T(t){return v(t)?"solana":W(t)?"evm":"unknown"}function y(t){let e=T(t);if(e==="solana")return t.includes("devnet")||t===o?"https://api.devnet.solana.com":t.includes("testnet")||t===S?"https://api.testnet.solana.com":"https://api.dexter.cash/api/solana/rpc";if(e==="evm"){if(t.startsWith("eip155:"))switch(t.split(":")[1]){case"8453":return"https://api.dexter.cash/api/base/rpc";case"84532":return"https://sepolia.base.org";case"1":return"https://eth.llamarpc.com";case"42161":return"https://arb1.arbitrum.io/rpc";default:return"https://api.dexter.cash/api/base/rpc"}return t==="base"?"https://api.dexter.cash/api/base/rpc":t==="ethereum"?"https://eth.llamarpc.com":t==="arbitrum"?"https://arb1.arbitrum.io/rpc":"https://api.dexter.cash/api/base/rpc"}return"https://api.dexter.cash/api/solana/rpc"}function O(t){return{[_]:"Solana",[o]:"Solana Devnet",[S]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[i]:"Base",[c]:"Base Sepolia",[f]:"Ethereum",[p]:"Arbitrum",[E]:"Polygon",[l]:"Optimism",[A]:"Avalanche",[h]:"BSC",[m]:"SKALE Base",[u]:"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"}[t]||t}function P(t,e){let n=O(t);return n===t?e:n}function F(t,e){let n=T(e);if(n==="solana")return e.includes("devnet")||e===o?`https://solscan.io/tx/${t}?cluster=devnet`:`https://www.orbmarkets.io/tx/${t}`;if(n==="evm"){let s="8453";switch(e.startsWith("eip155:")?s=e.split(":")[1]:e==="ethereum"?s="1":e==="arbitrum"?s="42161":e==="polygon"?s="137":e==="optimism"?s="10":e==="avalanche"?s="43114":e==="bsc"?s="56":e==="skale-base"?s="1187947933":e==="skale-base-sepolia"&&(s="324705682"),s){case"8453":return`https://basescan.org/tx/${t}`;case"84532":return`https://sepolia.basescan.org/tx/${t}`;case"1":return`https://etherscan.io/tx/${t}`;case"42161":return`https://arbiscan.io/tx/${t}`;case"137":return`https://polygonscan.com/tx/${t}`;case"10":return`https://optimistic.etherscan.io/tx/${t}`;case"43114":return`https://snowtrace.io/tx/${t}`;case"56":return`https://bscscan.com/tx/${t}`;case"1187947933":return`https://elated-tan-skat.explorer.mainnet.skalenodes.com/tx/${t}`;case"324705682":return`https://base-sepolia-testnet.explorer.skalenodes.com/tx/${t}`;default:return`https://basescan.org/tx/${t}`}}return`https://solscan.io/tx/${t}`}export{L as EVM_RPC_URLS,I as SOLANA_RPC_URLS,U as fromAtomicUnits,P as getChainDisplayName,T as getChainFamily,O as getChainName,y as getDefaultRpcUrl,F as getExplorerUrl,K as toAtomicUnits};
1
+ var R="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",b="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",u="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";var l="eip155:8453",A="eip155:84532",N="eip155:42161",m="eip155:137",h="eip155:10",d="eip155:43114",_="eip155:56",n="eip155:480",r="eip155:143",a="eip155:4663",i="eip155:1187947933",c="eip155:324705682",f="eip155:1";var K="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",L="0x55d398326f99059fF775485246999027B3197955",B="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",v="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",Y={[_]:B,[l]:K,[A]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[N]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[m]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[h]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[d]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[n]:"0x79A02482A880bCE3F13e09Da970dC34db4CD24d1",[r]:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",[a]:v,[i]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[c]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[f]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},q={[L]:{symbol:"USDT",decimals:18},[B]:{symbol:"USDC",decimals:18}};var X={[n]:{name:"USDC",version:"2"},[r]:{name:"USDC",version:"2"},[a]:{name:"Global Dollar",version:"1"},[i]:{name:"Bridged USDC (SKALE Bridge)",version:"2"},[c]:{name:"Bridged USDC (SKALE Bridge)",version:"2"}};var z={[_]:56,[l]:8453,[A]:84532,[N]:42161,[m]:137,[h]:10,[d]:43114,[n]:480,[r]:143,[a]:4663,[i]:1187947933,[c]:324705682,[f]:1},W={[R]:"https://api.dexter.cash/api/solana/rpc",[b]:"https://api.devnet.solana.com",[u]:"https://api.testnet.solana.com"},x={[_]:"https://api.dexter.cash/api/evm/bsc/rpc",[l]:"https://api.dexter.cash/api/base/rpc",[A]:"https://sepolia.base.org",[N]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[m]:"https://api.dexter.cash/api/evm/polygon/rpc",[h]:"https://api.dexter.cash/api/evm/optimism/rpc",[d]:"https://api.dexter.cash/api/evm/avalanche/rpc",[n]:"https://worldchain-mainnet.g.alchemy.com/public",[r]:"https://rpc.monad.xyz",[a]:"https://rpc.mainnet.chain.robinhood.com",[i]:"https://skale-base.skalenodes.com/v1/base",[c]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[f]:"https://eth.llamarpc.com"};function U(t,e){if(!Number.isFinite(t))throw new Error(`toAtomicUnits: amount must be finite, got ${t}`);if(t<0)throw new Error(`toAtomicUnits: amount must be non-negative, got ${t}`);if(!Number.isInteger(e)||e<0)throw new Error(`toAtomicUnits: decimals must be a non-negative integer, got ${e}`);let o=y(Math.abs(t)),[s,O=""]=o.split("."),T=O.slice(0,e).padEnd(e,"0");return BigInt(s+T).toString()}function y(t){let e=t.toString();if(!/[eE]/.test(e))return e;let[o,s]=e.split(/[eE]/),O=parseInt(s,10),T=o.startsWith("-"),D=T?o.slice(1):o,[C,M=""]=D.split("."),p=C+M,E=C.length+O,S;return E<=0?S="0."+"0".repeat(-E)+p:E>=p.length?S=p+"0".repeat(E-p.length):S=p.slice(0,E)+"."+p.slice(E),(T?"-":"")+S}function P(t,e){let o=Math.pow(10,e);return Number(t)/o}function F(t){return t.startsWith("solana:")||t==="solana"}var $=["base","base-sepolia","ethereum","arbitrum","polygon","optimism","avalanche","bsc","world","monad","robinhood","skale-base","skale-base-sepolia"];function H(t){return t.startsWith("eip155:")||$.includes(t)}function g(t){return F(t)?"solana":H(t)?"evm":"unknown"}function V(t){let e=g(t);if(e==="solana")return t.includes("devnet")||t===b?"https://api.devnet.solana.com":t.includes("testnet")||t===u?"https://api.testnet.solana.com":"https://api.dexter.cash/api/solana/rpc";if(e==="evm"){if(x[t])return x[t];let s={base:l,"base-sepolia":A,ethereum:f,arbitrum:N,polygon:m,optimism:h,avalanche:d,bsc:_,world:n,monad:r,robinhood:a,"skale-base":i,"skale-base-sepolia":c}[t];return s&&x[s]?x[s]:"https://api.dexter.cash/api/base/rpc"}return"https://api.dexter.cash/api/solana/rpc"}function I(t){return{[R]:"Solana",[b]:"Solana Devnet",[u]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[l]:"Base",[A]:"Base Sepolia",[f]:"Ethereum",[N]:"Arbitrum",[m]:"Polygon",[h]:"Optimism",[d]:"Avalanche",[_]:"BSC",[n]:"World Chain",[r]:"Monad",[a]:"Robinhood Chain",[i]:"SKALE Base",[c]:"SKALE Base Sepolia",base:"Base","base-sepolia":"Base Sepolia",ethereum:"Ethereum",arbitrum:"Arbitrum",polygon:"Polygon",optimism:"Optimism",avalanche:"Avalanche",bsc:"BSC",world:"World Chain",monad:"Monad",robinhood:"Robinhood Chain","skale-base":"SKALE Base","skale-base-sepolia":"SKALE Base Sepolia"}[t]||t}function G(t,e){let o=I(t);return o===t?e:o}function J(t,e){let o=g(e);if(o==="solana")return e.includes("devnet")||e===b?`https://solscan.io/tx/${t}?cluster=devnet`:`https://www.orbmarkets.io/tx/${t}`;if(o==="evm"){let s="8453";switch(e.startsWith("eip155:")?s=e.split(":")[1]:e==="ethereum"?s="1":e==="arbitrum"?s="42161":e==="polygon"?s="137":e==="optimism"?s="10":e==="avalanche"?s="43114":e==="bsc"?s="56":e==="world"?s="480":e==="monad"?s="143":e==="robinhood"?s="4663":e==="skale-base"?s="1187947933":e==="skale-base-sepolia"&&(s="324705682"),s){case"8453":return`https://basescan.org/tx/${t}`;case"84532":return`https://sepolia.basescan.org/tx/${t}`;case"1":return`https://etherscan.io/tx/${t}`;case"42161":return`https://arbiscan.io/tx/${t}`;case"137":return`https://polygonscan.com/tx/${t}`;case"10":return`https://optimistic.etherscan.io/tx/${t}`;case"43114":return`https://snowtrace.io/tx/${t}`;case"56":return`https://bscscan.com/tx/${t}`;case"480":return`https://worldscan.org/tx/${t}`;case"143":return`https://monadvision.com/tx/${t}`;case"4663":return`https://robinhoodchain.blockscout.com/tx/${t}`;case"1187947933":return`https://elated-tan-skat.explorer.mainnet.skalenodes.com/tx/${t}`;case"324705682":return`https://base-sepolia-testnet.explorer.skalenodes.com/tx/${t}`;default:return`https://basescan.org/tx/${t}`}}return`https://solscan.io/tx/${t}`}export{x as EVM_RPC_URLS,W as SOLANA_RPC_URLS,P as fromAtomicUnits,G as getChainDisplayName,g as getChainFamily,I as getChainName,V as getDefaultRpcUrl,J as getExplorerUrl,U as toAtomicUnits};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@dexterai/x402",
3
- "version": "5.3.3",
4
- "description": "Full-stack x402 SDK - add paid API monetization to any endpoint. Express middleware, React hooks, Access Pass, dynamic pricing. Solana, Base, Polygon, Arbitrum, Optimism, Avalanche, SKALE.",
3
+ "version": "5.4.0",
4
+ "description": "Full-stack x402 SDK - add paid API monetization to any endpoint. Express middleware, React hooks, Access Pass, dynamic pricing. Solana, Base, Polygon, Arbitrum, Optimism, Avalanche, World Chain, Monad, Robinhood Chain, SKALE.",
5
5
  "author": "Dexter",
6
6
  "license": "MIT",
7
7
  "type": "module",
@@ -142,6 +142,9 @@
142
142
  "optimism",
143
143
  "avalanche",
144
144
  "bsc",
145
+ "worldchain",
146
+ "monad",
147
+ "robinhood-chain",
145
148
  "skale",
146
149
  "payments",
147
150
  "dexter",