@dexterai/x402 6.0.0-rc.4 → 6.0.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +5 -1
  3. package/REFERENCE.md +33 -3
  4. package/dist/adapters/index.d.cts +3 -2
  5. package/dist/adapters/index.d.ts +3 -2
  6. package/dist/batch-settlement/index.cjs +1 -1
  7. package/dist/batch-settlement/index.d.cts +4 -3
  8. package/dist/batch-settlement/index.d.ts +4 -3
  9. package/dist/batch-settlement/index.js +1 -1
  10. package/dist/batch-settlement/seller/index.cjs +1 -1
  11. package/dist/batch-settlement/seller/index.d.cts +5 -4
  12. package/dist/batch-settlement/seller/index.d.ts +5 -4
  13. package/dist/batch-settlement/seller/index.js +1 -1
  14. package/dist/client/index.d.cts +5 -3
  15. package/dist/client/index.d.ts +5 -3
  16. package/dist/mcp/index.cjs +1 -0
  17. package/dist/mcp/index.d.cts +183 -0
  18. package/dist/mcp/index.d.ts +183 -0
  19. package/dist/mcp/index.js +1 -0
  20. package/dist/react/index.d.cts +2 -2
  21. package/dist/react/index.d.ts +2 -2
  22. package/dist/server/index.cjs +1 -1
  23. package/dist/server/index.d.cts +5 -4
  24. package/dist/server/index.d.ts +5 -4
  25. package/dist/server/index.js +1 -1
  26. package/dist/tab/adapters/solana/index.cjs +1 -1
  27. package/dist/tab/adapters/solana/index.d.cts +3 -2
  28. package/dist/tab/adapters/solana/index.d.ts +3 -2
  29. package/dist/tab/adapters/solana/index.js +1 -1
  30. package/dist/tab/index.cjs +4 -4
  31. package/dist/tab/index.d.cts +3 -2
  32. package/dist/tab/index.d.ts +3 -2
  33. package/dist/tab/index.js +1 -1
  34. package/dist/tab/seller/index.cjs +7 -7
  35. package/dist/tab/seller/index.js +1 -1
  36. package/dist/{types-CHQzNDR6.d.ts → types-BvK5UjA9.d.ts} +1 -1
  37. package/dist/{types-BvQpNtFw.d.cts → types-C08JT9MG.d.ts} +2 -236
  38. package/dist/{types-CkcNYx1Q.d.ts → types-C6IbRTpi.d.ts} +1 -1
  39. package/dist/{types-BvQpNtFw.d.ts → types-CRs5sEcb.d.cts} +2 -236
  40. package/dist/{types-CBQKKFxJ.d.cts → types-Cyyl3Cw_.d.cts} +1 -1
  41. package/dist/{types-DwVhPqOZ.d.ts → types-DGVtb7cl.d.cts} +4 -2
  42. package/dist/{types-BbvuPNXl.d.cts → types-DjDjuUc6.d.ts} +4 -2
  43. package/dist/types-DolSK-3d.d.cts +237 -0
  44. package/dist/types-DolSK-3d.d.ts +237 -0
  45. package/dist/{types-JpkrtFbZ.d.cts → types-RauRuMb7.d.cts} +1 -1
  46. package/docs/mcp.md +98 -0
  47. package/examples/mcp-paid-tool.ts +39 -0
  48. package/package.json +16 -10
@@ -1,27 +1,27 @@
1
- "use strict";var Xn=Object.create;var Fe=Object.defineProperty;var Jn=Object.getOwnPropertyDescriptor;var Yn=Object.getOwnPropertyNames;var Zn=Object.getPrototypeOf,Qn=Object.prototype.hasOwnProperty;var er=(t,e)=>{for(var n in e)Fe(t,n,{get:e[n],enumerable:!0})},rn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Yn(e))!Qn.call(t,i)&&i!==n&&Fe(t,i,{get:()=>e[i],enumerable:!(r=Jn(e,i))||r.enumerable});return t};var on=(t,e,n)=>(n=t!=null?Xn(Zn(t)):{},rn(e||!t||!t.__esModule?Fe(n,"default",{value:t,enumerable:!0}):n,t)),tr=t=>rn(Fe({},"__esModule",{value:!0}),t);var Qr={};er(Qr,{ChannelLeaseLostError:()=>M,FileChannelLedger:()=>ze,FileVoucherStore:()=>mt,InMemoryChannelLedger:()=>ye,InMemoryVoucherStore:()=>dt,InvalidRegistrationError:()=>W,InvalidVoucherError:()=>w,InvalidVoucherSignatureError:()=>T,OnChainVerificationError:()=>K,RedisChannelLedger:()=>Je,RedisKeyspaceMigrationRequiredError:()=>Ee,ScopeViolationError:()=>N,TAB_VOUCHER_HEADER:()=>ie,deserializeChannelLedgerEntry:()=>Ge,enforceScope:()=>Ve,openSse:()=>Vn,parseRegistration:()=>Pe,requireTab:()=>Pn,serializeChannelLedgerEntry:()=>We,tabChallengeMiddleware:()=>Fn,tabMiddleware:()=>ut,tabOrExactMiddleware:()=>zn,verifyRegistrationOnChain:()=>Ze,verifyVoucherSignature:()=>Qe});module.exports=tr(Qr);var w=class extends Error{constructor(n,r){super(`Invalid voucher: ${n}${r?` (${r})`:""}`);this.reason=n;this.name="InvalidVoucherError"}reason};var Y=require("fs"),qe=require("crypto"),He=require("path"),sn=new Map;function E(t,e){let r=(sn.get(t)??Promise.resolve()).then(()=>e(),()=>e());return sn.set(t,r.then(()=>{},()=>{})),r}var M=class extends Error{code="channel_lease_lost";constructor(e){super(`channel lease lost for ${e}`),this.name="ChannelLeaseLostError"}};function Z(t){if(!Number.isSafeInteger(t)||t<3||t>2147483647)throw new Error("channel lease TTL must be an integer from 3 to 2147483647 milliseconds");return t}function V(t){if(!/^[0-9a-f]{64}$/.test(t))throw new Error("channelId must be canonical lowercase 64-character hex")}function It(t,e){return t!==void 0&&t.ownerToken===e.ownerToken&&t.fence===e.fence}function fe(t,e,n){if(!e||!It(e,n)||e.heldUntilUnixMs<=Date.now())throw new M(t)}var ye=class{capabilities={adapter:"memory",restartSafe:!1,multiInstanceSafe:!1,conditionalWrites:!0,canonicalChannelIds:!0};map=new Map;leases=new Map;fences=new Map;async get(e){V(e);let n=this.map.get(e);return n?ae(ne(n)):null}async set(e,n,r){V(e),await E(e,async()=>{fe(e,this.leases.get(e),r),this.map.set(e,ae(ne(n)))})}async update(e,n,r){return V(e),E(e,async()=>{fe(e,this.leases.get(e),n);let i=this.map.get(e),o=r(i?ae(ne(i)):null),s=ae(ne(o));return this.map.set(e,s),ae(ne(s))})}async delete(e,n){V(e),await E(e,async()=>{fe(e,this.leases.get(e),n),this.map.delete(e)})}async tryAcquireLease(e,n){return V(e),E(e,async()=>{let r=Z(n),i=Date.now(),o=this.leases.get(e);if(o&&o.heldUntilUnixMs>i)return null;let s=(this.fences.get(e)??0n)+1n;this.fences.set(e,s);let c={ownerToken:(0,qe.randomUUID)(),fence:s.toString(),heldUntilUnixMs:i+r};return this.leases.set(e,c),{...c}})}async releaseLease(e,n){return V(e),E(e,async()=>{let r=this.leases.get(e);return!r||!It(r,n)||r.heldUntilUnixMs<=Date.now()?!1:(this.leases.delete(e),!0)})}async renewLease(e,n,r){return V(e),E(e,async()=>{let i=Z(r),o=this.leases.get(e);fe(e,o,n);let s={...o,heldUntilUnixMs:Date.now()+i};return this.leases.set(e,s),{...s}})}};function Vt(t){let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}function Tt(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 n=0;n<e.length;n++)e[n]=parseInt(t.substr(n*2,2),16);return e}function We(t){return ne(t)}function Ge(t){return ae(t)}function ne(t){return{lastVoucher:t.lastVoucher?{payload:t.lastVoucher.payload,sessionPublicKey:Vt(t.lastVoucher.sessionPublicKey),sessionRegistration:Vt(t.lastVoucher.sessionRegistration),sessionSignature:Vt(t.lastVoucher.sessionSignature)}:null,deliveredCumulativeAtomic:t.deliveredCumulativeAtomic,lastCrystallizedCumulativeAtomic:t.lastCrystallizedCumulativeAtomic,gateRefusedCumulativeAtomic:t.gateRefusedCumulativeAtomic,onChain:t.onChain}}function ae(t){return{lastVoucher:t.lastVoucher?{payload:t.lastVoucher.payload,sessionPublicKey:Tt(t.lastVoucher.sessionPublicKey),sessionRegistration:Tt(t.lastVoucher.sessionRegistration),sessionSignature:Tt(t.lastVoucher.sessionSignature)}:null,deliveredCumulativeAtomic:t.deliveredCumulativeAtomic,lastCrystallizedCumulativeAtomic:t.lastCrystallizedCumulativeAtomic??"0",gateRefusedCumulativeAtomic:t.gateRefusedCumulativeAtomic,onChain:t.onChain}}var ze=class{constructor(e,n={}){this.dir=e;if(n===null||typeof n!="object"||Array.isArray(n))throw new Error("FileChannelLedger options must be an object");if(n.channelIdCutover!==void 0&&n.channelIdCutover!=="legacy-case-aliases-migrated-or-empty")throw new Error("invalid FileChannelLedger channelIdCutover acknowledgement");this.capabilities={adapter:"file",restartSafe:!0,multiInstanceSafe:!1,conditionalWrites:!0,canonicalChannelIds:n.channelIdCutover==="legacy-case-aliases-migrated-or-empty"}}dir;capabilities;pathFor(e,n=".json"){return V(e),(0,He.join)(this.dir,`${e}${n}`)}async writeAtomic(e,n){await Y.promises.mkdir((0,He.dirname)(e),{recursive:!0});let r=`${e}.${(0,qe.randomUUID)()}.tmp`;await Y.promises.writeFile(r,n),await Y.promises.rename(r,e)}async readLease(e){try{return JSON.parse(await Y.promises.readFile(this.pathFor(e,".lease.json"),"utf8"))}catch(n){if(n?.code==="ENOENT")return;throw n}}async requireLease(e,n){fe(e,await this.readLease(e),n)}async get(e){V(e);try{let n=await Y.promises.readFile(this.pathFor(e),"utf8");return ae(JSON.parse(n))}catch(n){if(n?.code==="ENOENT")return null;throw n}}async set(e,n,r){V(e),await E(e,async()=>{await this.requireLease(e,r),await this.writeAtomic(this.pathFor(e),JSON.stringify(ne(n)))})}async update(e,n,r){return V(e),E(e,async()=>{await this.requireLease(e,n);let i=r(await this.get(e));return await this.writeAtomic(this.pathFor(e),JSON.stringify(ne(i))),i})}async delete(e,n){V(e),await E(e,async()=>{await this.requireLease(e,n);try{await Y.promises.unlink(this.pathFor(e))}catch(r){if(r?.code!=="ENOENT")throw r}})}async tryAcquireLease(e,n){return V(e),E(e,async()=>{let r=Z(n),i=Date.now(),o=await this.readLease(e);if(o&&o.heldUntilUnixMs>i)return null;let s=0n;try{s=BigInt(await Y.promises.readFile(this.pathFor(e,".fence"),"utf8"))}catch(p){if(p?.code!=="ENOENT")throw p}let c=s+1n;await this.writeAtomic(this.pathFor(e,".fence"),c.toString());let l={ownerToken:(0,qe.randomUUID)(),fence:c.toString(),heldUntilUnixMs:i+r};return await this.writeAtomic(this.pathFor(e,".lease.json"),JSON.stringify(l)),l})}async releaseLease(e,n){return V(e),E(e,async()=>{let r=await this.readLease(e);return!r||!It(r,n)||r.heldUntilUnixMs<=Date.now()?!1:(await Y.promises.unlink(this.pathFor(e,".lease.json")),!0)})}async renewLease(e,n,r){return V(e),E(e,async()=>{let i=Z(r),o=await this.readLease(e);fe(e,o,n);let s={...o,heldUntilUnixMs:Date.now()+i};return await this.writeAtomic(this.pathFor(e,".lease.json"),JSON.stringify(s)),s})}};var cn=require("crypto");function an(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let e=t;return e.persistence==="aof-always"&&e.failover==="no-data-loss"&&e.maxmemoryPolicy==="noeviction"&&e.isolation==="dedicated-instance"}var nr=`
1
+ "use strict";var jn=Object.create;var qe=Object.defineProperty;var Xn=Object.getOwnPropertyDescriptor;var Jn=Object.getOwnPropertyNames;var Yn=Object.getPrototypeOf,Zn=Object.prototype.hasOwnProperty;var Qn=(t,e)=>{for(var n in e)qe(t,n,{get:e[n],enumerable:!0})},rn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Jn(e))!Zn.call(t,i)&&i!==n&&qe(t,i,{get:()=>e[i],enumerable:!(r=Xn(e,i))||r.enumerable});return t};var on=(t,e,n)=>(n=t!=null?jn(Yn(t)):{},rn(e||!t||!t.__esModule?qe(n,"default",{value:t,enumerable:!0}):n,t)),er=t=>rn(qe({},"__esModule",{value:!0}),t);var Zr={};Qn(Zr,{ChannelLeaseLostError:()=>M,FileChannelLedger:()=>He,FileVoucherStore:()=>mt,InMemoryChannelLedger:()=>ve,InMemoryVoucherStore:()=>dt,InvalidRegistrationError:()=>W,InvalidVoucherError:()=>w,InvalidVoucherSignatureError:()=>T,OnChainVerificationError:()=>K,RedisChannelLedger:()=>Ye,RedisKeyspaceMigrationRequiredError:()=>Pe,ScopeViolationError:()=>N,TAB_VOUCHER_HEADER:()=>ie,deserializeChannelLedgerEntry:()=>je,enforceScope:()=>Te,openSse:()=>Pn,parseRegistration:()=>Ve,requireTab:()=>En,serializeChannelLedgerEntry:()=>Ge,tabChallengeMiddleware:()=>Dn,tabMiddleware:()=>ut,tabOrExactMiddleware:()=>qn,verifyRegistrationOnChain:()=>Qe,verifyVoucherSignature:()=>et});module.exports=er(Zr);var w=class extends Error{constructor(n,r){super(`Invalid voucher: ${n}${r?` (${r})`:""}`);this.reason=n;this.name="InvalidVoucherError"}reason};var Y=require("fs"),ze=require("crypto"),We=require("path"),sn=new Map;function E(t,e){let r=(sn.get(t)??Promise.resolve()).then(()=>e(),()=>e());return sn.set(t,r.then(()=>{},()=>{})),r}var M=class extends Error{code="channel_lease_lost";constructor(e){super(`channel lease lost for ${e}`),this.name="ChannelLeaseLostError"}};function Z(t){if(!Number.isSafeInteger(t)||t<3||t>2147483647)throw new Error("channel lease TTL must be an integer from 3 to 2147483647 milliseconds");return t}function V(t){if(!/^[0-9a-f]{64}$/.test(t))throw new Error("channelId must be canonical lowercase 64-character hex")}function It(t,e){return t!==void 0&&t.ownerToken===e.ownerToken&&t.fence===e.fence}function ye(t,e,n){if(!e||!It(e,n)||e.heldUntilUnixMs<=Date.now())throw new M(t)}var ve=class{capabilities={adapter:"memory",restartSafe:!1,multiInstanceSafe:!1,conditionalWrites:!0,canonicalChannelIds:!0};map=new Map;leases=new Map;fences=new Map;async get(e){V(e);let n=this.map.get(e);return n?ae(ne(n)):null}async set(e,n,r){V(e),await E(e,async()=>{ye(e,this.leases.get(e),r),this.map.set(e,ae(ne(n)))})}async update(e,n,r){return V(e),E(e,async()=>{ye(e,this.leases.get(e),n);let i=this.map.get(e),o=r(i?ae(ne(i)):null),s=ae(ne(o));return this.map.set(e,s),ae(ne(s))})}async delete(e,n){V(e),await E(e,async()=>{ye(e,this.leases.get(e),n),this.map.delete(e)})}async tryAcquireLease(e,n){return V(e),E(e,async()=>{let r=Z(n),i=Date.now(),o=this.leases.get(e);if(o&&o.heldUntilUnixMs>i)return null;let s=(this.fences.get(e)??0n)+1n;this.fences.set(e,s);let c={ownerToken:(0,ze.randomUUID)(),fence:s.toString(),heldUntilUnixMs:i+r};return this.leases.set(e,c),{...c}})}async releaseLease(e,n){return V(e),E(e,async()=>{let r=this.leases.get(e);return!r||!It(r,n)||r.heldUntilUnixMs<=Date.now()?!1:(this.leases.delete(e),!0)})}async renewLease(e,n,r){return V(e),E(e,async()=>{let i=Z(r),o=this.leases.get(e);ye(e,o,n);let s={...o,heldUntilUnixMs:Date.now()+i};return this.leases.set(e,s),{...s}})}};function Vt(t){let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}function Tt(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 n=0;n<e.length;n++)e[n]=parseInt(t.substr(n*2,2),16);return e}function Ge(t){return ne(t)}function je(t){return ae(t)}function ne(t){return{lastVoucher:t.lastVoucher?{payload:t.lastVoucher.payload,sessionPublicKey:Vt(t.lastVoucher.sessionPublicKey),sessionRegistration:Vt(t.lastVoucher.sessionRegistration),sessionSignature:Vt(t.lastVoucher.sessionSignature)}:null,deliveredCumulativeAtomic:t.deliveredCumulativeAtomic,lastCrystallizedCumulativeAtomic:t.lastCrystallizedCumulativeAtomic,gateRefusedCumulativeAtomic:t.gateRefusedCumulativeAtomic,onChain:t.onChain}}function ae(t){return{lastVoucher:t.lastVoucher?{payload:t.lastVoucher.payload,sessionPublicKey:Tt(t.lastVoucher.sessionPublicKey),sessionRegistration:Tt(t.lastVoucher.sessionRegistration),sessionSignature:Tt(t.lastVoucher.sessionSignature)}:null,deliveredCumulativeAtomic:t.deliveredCumulativeAtomic,lastCrystallizedCumulativeAtomic:t.lastCrystallizedCumulativeAtomic??"0",gateRefusedCumulativeAtomic:t.gateRefusedCumulativeAtomic,onChain:t.onChain}}var He=class{constructor(e,n={}){this.dir=e;if(n===null||typeof n!="object"||Array.isArray(n))throw new Error("FileChannelLedger options must be an object");if(n.channelIdCutover!==void 0&&n.channelIdCutover!=="legacy-case-aliases-migrated-or-empty")throw new Error("invalid FileChannelLedger channelIdCutover acknowledgement");this.capabilities={adapter:"file",restartSafe:!0,multiInstanceSafe:!1,conditionalWrites:!0,canonicalChannelIds:n.channelIdCutover==="legacy-case-aliases-migrated-or-empty"}}dir;capabilities;pathFor(e,n=".json"){return V(e),(0,We.join)(this.dir,`${e}${n}`)}async writeAtomic(e,n){await Y.promises.mkdir((0,We.dirname)(e),{recursive:!0});let r=`${e}.${(0,ze.randomUUID)()}.tmp`;await Y.promises.writeFile(r,n),await Y.promises.rename(r,e)}async readLease(e){try{return JSON.parse(await Y.promises.readFile(this.pathFor(e,".lease.json"),"utf8"))}catch(n){if(n?.code==="ENOENT")return;throw n}}async requireLease(e,n){ye(e,await this.readLease(e),n)}async get(e){V(e);try{let n=await Y.promises.readFile(this.pathFor(e),"utf8");return ae(JSON.parse(n))}catch(n){if(n?.code==="ENOENT")return null;throw n}}async set(e,n,r){V(e),await E(e,async()=>{await this.requireLease(e,r),await this.writeAtomic(this.pathFor(e),JSON.stringify(ne(n)))})}async update(e,n,r){return V(e),E(e,async()=>{await this.requireLease(e,n);let i=r(await this.get(e));return await this.writeAtomic(this.pathFor(e),JSON.stringify(ne(i))),i})}async delete(e,n){V(e),await E(e,async()=>{await this.requireLease(e,n);try{await Y.promises.unlink(this.pathFor(e))}catch(r){if(r?.code!=="ENOENT")throw r}})}async tryAcquireLease(e,n){return V(e),E(e,async()=>{let r=Z(n),i=Date.now(),o=await this.readLease(e);if(o&&o.heldUntilUnixMs>i)return null;let s=0n;try{s=BigInt(await Y.promises.readFile(this.pathFor(e,".fence"),"utf8"))}catch(p){if(p?.code!=="ENOENT")throw p}let c=s+1n;await this.writeAtomic(this.pathFor(e,".fence"),c.toString());let l={ownerToken:(0,ze.randomUUID)(),fence:c.toString(),heldUntilUnixMs:i+r};return await this.writeAtomic(this.pathFor(e,".lease.json"),JSON.stringify(l)),l})}async releaseLease(e,n){return V(e),E(e,async()=>{let r=await this.readLease(e);return!r||!It(r,n)||r.heldUntilUnixMs<=Date.now()?!1:(await Y.promises.unlink(this.pathFor(e,".lease.json")),!0)})}async renewLease(e,n,r){return V(e),E(e,async()=>{let i=Z(r),o=await this.readLease(e);ye(e,o,n);let s={...o,heldUntilUnixMs:Date.now()+i};return await this.writeAtomic(this.pathFor(e,".lease.json"),JSON.stringify(s)),s})}};var cn=require("crypto");function an(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let e=t;return e.persistence==="aof-always"&&e.failover==="no-data-loss"&&e.maxmemoryPolicy==="noeviction"&&e.isolation==="dedicated-instance"}var tr=`
2
2
  if redis.call("exists", KEYS[1]) == 1 then return false end
3
3
  redis.call("incr", KEYS[2])
4
4
  local fence = redis.call("get", KEYS[2])
5
5
  redis.call("set", KEYS[1], ARGV[1] .. ":" .. tostring(fence), "PX", ARGV[2])
6
6
  return tostring(fence)
7
- `,rr=`
7
+ `,nr=`
8
8
  if redis.call("get", KEYS[1]) ~= ARGV[1] then return 0 end
9
9
  redis.call("set", KEYS[2], ARGV[2])
10
10
  return 1
11
- `,ir=`
11
+ `,rr=`
12
12
  if redis.call("get", KEYS[1]) ~= ARGV[1] then return 0 end
13
13
  redis.call("del", KEYS[2])
14
14
  return 1
15
- `,or=`
15
+ `,ir=`
16
16
  if redis.call("get", KEYS[1]) ~= ARGV[1] then return 0 end
17
17
  return redis.call("del", KEYS[1])
18
- `,sr=`
18
+ `,or=`
19
19
  if redis.call("get", KEYS[1]) ~= ARGV[1] then return 0 end
20
20
  redis.call("pexpire", KEYS[1], ARGV[2])
21
21
  return 1
22
- `,ar='return redis.call("get", KEYS[1])',Ee=class extends Error{constructor(e){super(`legacy Redis seller state exists for channel ${e}; stop all legacy writers, migrate/delete the legacy ledger, lease, and fence keys, then retry cluster-v1`),this.name="RedisKeyspaceMigrationRequiredError"}};function je(t){return`${t.ownerToken}:${t.fence}`}function Xe(t){return t===1||t==="1"}var Je=class{constructor(e,n="tab:"){this.client=e;if(typeof n!="string"&&(n===null||typeof n!="object"||Array.isArray(n)))throw new Error("RedisChannelLedger options must be a key prefix or options object");let r=typeof n=="string"?{keyPrefix:n}:n;if(r.keyPrefix!==void 0&&typeof r.keyPrefix!="string")throw new Error("RedisChannelLedger keyPrefix must be a string");if(this.keyPrefix=r.keyPrefix??"tab:",this.keyLayout=r.keyLayout??"legacy-v0",!["legacy-v0","cluster-v1"].includes(this.keyLayout))throw new Error(`invalid RedisChannelLedger keyLayout: ${String(this.keyLayout)}`);if(this.keyLayout==="cluster-v1"&&(this.keyPrefix.includes("{")||this.keyPrefix.includes("}")))throw new Error("cluster-v1 keyPrefix must not contain Redis hash-tag braces");if(r.writerCutover!==void 0&&r.writerCutover!=="all-legacy-writers-stopped")throw new Error("invalid RedisChannelLedger writerCutover acknowledgement");if(r.channelIdCutover!==void 0&&r.channelIdCutover!=="legacy-case-aliases-migrated-or-empty")throw new Error("invalid RedisChannelLedger channelIdCutover acknowledgement");if(this.keyLayout==="cluster-v1"&&r.keyspaceCutover!=="legacy-state-migrated-or-empty")throw new Error("cluster-v1 requires keyspaceCutover: legacy-state-migrated-or-empty");let i=r.durability;if(i!==void 0&&!an(i))throw new Error("RedisChannelLedger durability attestation must confirm aof-always, no-data-loss failover, noeviction, and dedicated-instance isolation");this.capabilities={adapter:"redis",restartSafe:an(i)&&r.writerCutover==="all-legacy-writers-stopped",multiInstanceSafe:!0,conditionalWrites:!0,canonicalChannelIds:r.channelIdCutover==="legacy-case-aliases-migrated-or-empty"}}client;capabilities;keyPrefix;keyLayout;assertChannelId(e){V(e)}legacyKey(e,n){return this.assertChannelId(e),`${this.keyPrefix}${n}:${e}`}channelKey(e,n){return this.assertChannelId(e),this.keyLayout==="cluster-v1"?`${this.keyPrefix}{${e}}:${n}`:this.legacyKey(e,n)}ledgerKey(e){return this.channelKey(e,"ledger")}leaseKey(e){return this.channelKey(e,"lease")}fenceKey(e){return this.channelKey(e,"fence")}async primaryGet(e){let n=await this.client.eval(ar,1,e);if(n===null||n===!1)return null;if(typeof n!="string")throw new Error(`Redis primary GET returned invalid value type: ${typeof n}`);return n}async assertClusterCutover(e){if(this.keyLayout!=="cluster-v1")return;let n=await this.primaryGet(this.legacyKey(e,"ledger")),r=await this.primaryGet(this.legacyKey(e,"lease")),i=await this.primaryGet(this.legacyKey(e,"fence"));if(n!==null||r!==null||i!==null)throw new Ee(e)}async get(e){this.assertChannelId(e),await this.assertClusterCutover(e);let n=await this.primaryGet(this.ledgerKey(e));return n===null?null:Ge(JSON.parse(n))}async writeIfOwned(e,n,r){let i=We(n),o=await this.client.eval(rr,2,this.leaseKey(e),this.ledgerKey(e),je(r),JSON.stringify(i));if(!Xe(o))throw new M(e)}async set(e,n,r){this.assertChannelId(e),await E(e,()=>this.writeIfOwned(e,n,r))}async update(e,n,r){return this.assertChannelId(e),E(e,async()=>{let i=r(await this.get(e));return await this.writeIfOwned(e,i,n),i})}async delete(e,n){this.assertChannelId(e),await E(e,async()=>{let r=await this.client.eval(ir,2,this.leaseKey(e),this.ledgerKey(e),je(n));if(!Xe(r))throw new M(e)})}async tryAcquireLease(e,n){return this.assertChannelId(e),E(e,async()=>{await this.assertClusterCutover(e);let r=(0,cn.randomUUID)(),i=Z(n),o=await this.client.eval(nr,2,this.leaseKey(e),this.fenceKey(e),r,i);if(o===null||o===!1||o===0||o==="0")return null;let s=String(o);if(!/^[1-9][0-9]*$/.test(s))throw new Error(`Redis returned invalid channel fence: ${s}`);return{ownerToken:r,fence:s,heldUntilUnixMs:Date.now()+i}})}async releaseLease(e,n){return this.assertChannelId(e),E(e,async()=>{let r=await this.client.eval(or,1,this.leaseKey(e),je(n));return Xe(r)})}async renewLease(e,n,r){return this.assertChannelId(e),E(e,async()=>{let i=Z(r),o=await this.client.eval(sr,1,this.leaseKey(e),je(n),i);if(!Xe(o))throw new M(e);return{...n,heldUntilUnixMs:Date.now()+i}})}};var Rn=require("@solana/web3.js");var un=on(require("tweetnacl"),1),lr=require("@noble/hashes/sha256"),ur=require("@noble/curves/p256"),Ye=require("@solana/web3.js");var D=require("@dexterai/vault/messages");var Nt=require("@dexterai/vault/instructions"),cr=require("@dexterai/vault/precompile"),ce=require("@dexterai/vault/constants");var le=require("@dexterai/vault/session"),ve=require("@dexterai/vault/messages"),Lt="OTS_SESSION_REGISTER_V2";function re(t){return t>=2147483648?2:1}var W=class extends Error{constructor(n,r){super(`Invalid registration: ${n}${r?` (${r})`:""}`);this.reason=n;this.name="InvalidRegistrationError"}reason};function Pe(t){if(t.length!==188)throw new W("wrong_length",`expected 188, got ${t.length}`);let e=new TextDecoder().decode(t.slice(0,Lt.length));if(e!==Lt)throw new W("wrong_domain",`got "${e}"`);for(let v=Lt.length;v<32;v++)if(t[v]!==0)throw new W("wrong_domain",`non-NUL padding at byte ${v}`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=new Ye.PublicKey(t.slice(32,64)),i=new Ye.PublicKey(t.slice(64,96)),o=t.slice(96,128),s=n.getBigUint64(128,!0),c=n.getBigInt64(136,!0),l=new Ye.PublicKey(t.slice(144,176)),p=n.getUint32(176,!0),y=n.getBigUint64(180,!0);if(!r.equals(ce.DEXTER_VAULT_PROGRAM_ID))throw new W("wrong_program",`${r.toBase58()} is not ${ce.DEXTER_VAULT_PROGRAM_ID.toBase58()}`);if(s===0n)throw new W("cap_zero");return{programId:r,vaultPda:i,sessionPubkey:new Uint8Array(o),maxAmount:s,expiresAt:c,allowedCounterparty:l,nonce:p,maxRevolvingCapacity:y}}var K=class extends Error{constructor(n,r){super(`On-chain verification failed: ${n}${r?` (${r})`:""}`);this.reason=n;this.name="OnChainVerificationError"}reason};async function Ze(t,e){let[n]=(0,le.deriveSessionPda)(e.vaultPda,e.allowedCounterparty,e.programId),r=await t.getAccountInfo(n,"finalized");if(!r)throw new K("session_not_active","no finalized SessionAccount PDA for this (vault, counterparty) \u2014 registration may be confirmed-only, revoked, expiry-swept, or never registered");if(!r.owner.equals(e.programId))throw new K("wrong_program",`SessionAccount owner ${r.owner.toBase58()} != ${e.programId.toBase58()}`);let i;try{i=(0,le.decodeSessionAccount)(n,r.data)}catch(h){throw new K("registration_state_mismatch",`finalized SessionAccount decode failed: ${h instanceof Error?h.message:String(h)}`)}if(i.version===0)throw new K("session_not_active","finalized SessionAccount is cleared");if(!(0,le.isSessionLive)(i))throw new K("session_not_active","SessionAccount PDA is present but expired");if(!dn(i.session.sessionPubkey,e.sessionPubkey))throw new K("session_pubkey_mismatch",`on-chain ${ln(i.session.sessionPubkey)} != registration ${ln(e.sessionPubkey)}`);let o=re(e.nonce),s=re(i.session.nonce);if(s!==o)throw new K("wire_version_mismatch",`active SessionAccount is V${s}, voucher registration is V${o}`);let c=Number.isSafeInteger(i.session.expiresAt)&&BigInt(i.session.expiresAt)===e.expiresAt;if(!(i.address===n.toBase58()&&i.vault===e.vaultPda.toBase58()&&i.session.maxAmount===e.maxAmount&&c&&i.session.allowedCounterparty===e.allowedCounterparty.toBase58()&&i.session.nonce===e.nonce&&i.session.maxRevolvingCapacity===e.maxRevolvingCapacity))throw new K("registration_state_mismatch","188-byte registration does not exactly match the active SessionAccount immutable fields");let p=i.session.spent,y=i.session.crystallizedCumulative,v=p>y?p:y;return{sessionAccountVersion:i.version,wireVersion:s,frontierAtomic:v.toString(),spentAtomic:p.toString(),currentOutstandingAtomic:i.session.currentOutstanding.toString(),crystallizedCumulativeAtomic:y.toString()}}var T=class extends Error{constructor(e){super(`Invalid voucher signature${e?`: ${e}`:""}`),this.name="InvalidVoucherSignatureError"}};function Qe(t,e){if(e.length!==32)throw new T(`channelIdBytes must be 32 bytes, got ${e.length}`);if(t.sessionPublicKey.length!==32)throw new T(`sessionPublicKey must be 32 bytes, got ${t.sessionPublicKey.length}`);if(t.sessionSignature.length!==64)throw new T(`sessionSignature must be 64 bytes, got ${t.sessionSignature.length}`);let n=Pe(t.sessionRegistration);if(!dn(n.sessionPubkey,t.sessionPublicKey))throw new T("registration session key does not match voucher session key");let r=n.nonce>=2147483648,i=re(n.nonce),o=re(t.payload.sequenceNumber);if(i!==o)throw new T(`voucher wire V${o} does not match registration wire V${i}`);let s;if(r){(0,ve.sessionVoucherV2AuthorizationNonce)(n.nonce),(0,ve.voucherV2SequenceOrdinal)(t.payload.sequenceNumber);let[l]=(0,le.deriveSessionPda)(n.vaultPda,n.allowedCounterparty,n.programId);s=(0,ve.contextBoundVoucherV2Message)({programId:n.programId,vaultPda:n.vaultPda,sessionPda:l,seller:n.allowedCounterparty,sessionNonce:n.nonce,channelId:e,cumulativeAmount:BigInt(t.payload.cumulativeAmount),sequenceNumber:t.payload.sequenceNumber})}else s=(0,D.voucherPayloadMessage)({channelId:e,cumulativeAmount:BigInt(t.payload.cumulativeAmount),sequenceNumber:t.payload.sequenceNumber});if(!un.default.sign.detached.verify(s,t.sessionSignature,t.sessionPublicKey))throw new T("ed25519 verify rejected")}var N=class extends Error{constructor(n,r){super(`Scope violation: ${n}${r?` (${r})`:""}`);this.reason=n;this.name="ScopeViolationError"}reason};function Ve(t){let e=BigInt(t.voucher.payload.cumulativeAmount);if(e>t.registration.maxAmount)throw new N("cumulative_exceeds_cap",`${e} > ${t.registration.maxAmount}`);let n=BigInt(Math.floor(Date.now()/1e3));if(n>=t.registration.expiresAt)throw new N("session_expired",`now=${n} >= expiresAt=${t.registration.expiresAt}`);if(!t.registration.allowedCounterparty.equals(t.expectedCounterparty))throw new N("wrong_counterparty",`${t.registration.allowedCounterparty.toBase58()} != ${t.expectedCounterparty.toBase58()}`);if(t.previousCumulativeAtomic!==void 0){let r=BigInt(t.previousCumulativeAtomic);if(e<=r)throw new N("non_monotonic",`cumulative=${e} not > previous=${r}`)}}function dn(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function ln(t){let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}var Ar=require("@solana/web3.js"),br=require("@noble/hashes/utils");var dr=on(require("tweetnacl"),1),mr=require("@solana/web3.js"),et=require("@dexterai/vault/messages"),pr=require("@dexterai/vault/session");var gr=require("@noble/hashes/sha256");var gi=(1n<<64n)-1n;var Bt=require("@noble/hashes/sha256"),ue=require("@noble/hashes/utils"),mn=/^[0-9a-f]{64}$/,pn=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/,hr=/^[1-9A-HJ-NP-Za-km-z]{32,100}$/,gn="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",hn="dexter-native-tab-v2-reservation/v1",fr=`${hn}:`;function Ot(t){if(t===null||typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number"){if(!Number.isFinite(t))throw new Error("canonical_non_finite_number");return t}if(typeof t=="bigint")return t.toString();if(Array.isArray(t))return t.map(Ot);if(typeof t=="object")return Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,Ot(n)]));throw new Error("canonical_value_unsupported")}function fn(t){return JSON.stringify(Ot(t))}function kt(t){if(t==="solana:mainnet"||t===gn)return gn;throw new Error("native_tab_v2_reservation_network_unsupported")}function Ut(t){return(0,ue.bytesToHex)((0,Bt.sha256)(new TextEncoder().encode(fn({channelId:t.payload.channelId,cumulativeAmount:t.payload.cumulativeAmount,sequenceNumber:t.payload.sequenceNumber,sessionPublicKey:(0,ue.bytesToHex)(t.sessionPublicKey),sessionSignature:(0,ue.bytesToHex)(t.sessionSignature),sessionRegistration:(0,ue.bytesToHex)(t.sessionRegistration)}))))}function Kt(t){let e=Ut(t);return{voucherDigest:e,idempotencyKey:`native-tab-v2:${e}`}}function yr(t){return(0,ue.bytesToHex)((0,Bt.sha256)(new TextEncoder().encode(fn({contract:hn,network:kt(t.network),programId:t.programId,buyerSwigAddress:t.buyerSwigAddress,vaultPda:t.vaultPda,sessionPda:t.sessionPda,seller:t.seller,channelId:t.channelId,sessionNonce:t.sessionNonce,reservationAmountAtomic:t.reservationAmountAtomic,previousCumulativeAtomic:t.previousCumulativeAtomic,voucherDigest:t.voucherDigest,cumulativeAmountAtomic:t.cumulativeAmountAtomic,sequenceNumber:t.sequenceNumber}))))}function vr(t){let e=Ut(t.voucher);return yr({network:t.network,programId:t.programId,buyerSwigAddress:t.buyerSwigAddress,vaultPda:t.vaultPda,sessionPda:t.sessionPda,seller:t.seller,channelId:t.channelId,sessionNonce:t.sessionNonce,reservationAmountAtomic:t.reservationAmountAtomic,previousCumulativeAtomic:t.previousCumulativeAtomic,voucherDigest:e,cumulativeAmountAtomic:t.voucher.payload.cumulativeAmount,sequenceNumber:t.voucher.payload.sequenceNumber})}function yn(t){return`${fr}${vr(t)}`}function L(t){throw new Error(`native_tab_v2_reservation_receipt_invalid:${t}`)}function tt(t,e){(!Number.isSafeInteger(t)||t<0)&&L(e)}function $t(t,e){(!e||typeof e!="object")&&L("missing");let n=Ut(t.voucher);(!mn.test(t.voucherDigest)||t.voucherDigest!==n)&&L("input_voucher_digest"),t.idempotencyKey!==`native-tab-v2:${n}`&&L("input_idempotency_identity");let r=BigInt(t.voucher.payload.cumulativeAmount),i=BigInt(t.previousCumulativeAtomic),o=BigInt(t.reservationAmountAtomic);(r<=i||r-i!==o||o<=0n)&&L("input_reservation_delta"),(t.voucher.payload.channelId!==t.channelId||(t.voucher.payload.sequenceNumber&2147483648)===0||(t.sessionNonce&2147483648)===0||t.voucher.sessionPublicKey.length!==32||t.voucher.sessionSignature.length!==64||t.voucher.sessionRegistration.length!==188)&&L("input_voucher_identity"),e.contract!=="dexter-native-tab-open-receipt/v1"&&e.contract!=="dexter-native-tab-open-receipt/v2"&&L("contract"),mn.test(e.operationId)||L("operation_id"),pn.test(e.callerOperationId)||L("caller_operation_id"),hr.test(e.transaction)||L("transaction"),e.commitment!=="confirmed"&&e.commitment!=="finalized"&&L("commitment"),tt(e.confirmationSlot,"confirmation_slot"),tt(e.postStateSlot,"post_state_slot"),(e.confirmationSlot===0||e.postStateSlot<e.confirmationSlot)&&L("post_state_slot");let s,c;try{s=kt(t.network),c=kt(e.network)}catch{return L("network")}(c!==s||e.buyerSwigAddress!==t.buyerSwigAddress||e.vaultPda!==t.vaultPda||e.sessionPda!==t.sessionPda||e.seller!==t.seller||e.channelId!==t.channelId||e.sessionPublicKey!==(0,ue.bytesToHex)(t.voucher.sessionPublicKey)||e.voucherDigest!==n||e.cumulativeAmountAtomic!==t.voucher.payload.cumulativeAmount||e.sequenceNumber!==t.voucher.payload.sequenceNumber||!pn.test(e.providerReceiptId)||e.reservationAmountAtomic!==t.reservationAmountAtomic||e.currentOutstandingBeforeAtomic!=="0"||e.currentOutstandingAfterAtomic!==t.reservationAmountAtomic)&&L("economic_identity"),tt(e.pendingVoucherCountBefore,"pending_voucher_count_before"),tt(e.pendingVoucherCountAfter,"pending_voucher_count_after"),e.contract==="dexter-native-tab-open-receipt/v1"?e.callerOperationId!==t.idempotencyKey&&L("idempotency_key"):(e.rootOperationId!==t.idempotencyKey||!Number.isSafeInteger(e.generation)||Number(e.generation)<2||!e.predecessorCallerOperationId||!e.predecessorLifecycleOperationId||!e.predecessorReleaseDigest||!e.stableReservationId||!e.economicEffectDigest)&&L("successor_identity")}var wr=require("@dexterai/vault/session");var vn="https://x402.dexter.cash",An=6;function G(t,e=An){if(!/^\d+(\.\d+)?$/.test(t))throw new Error(`amount must be a non-negative decimal string, got "${t}"`);let[n,r=""]=t.split(".");if(r.length>e)throw new Error(`amount "${t}" has more than ${e} decimals`);let i=r.padEnd(e,"0"),o=`${n}${i}`.replace(/^0+(?=\d)/,"");return o===""?"0":o}function de(t,e=An){if(!/^\d+$/.test(t))throw new Error(`atomic must be a non-negative integer string, got "${t}"`);let n=t.padStart(e+1,"0"),r=n.slice(0,-e).replace(/^0+(?=\d)/,"")||"0",i=n.slice(-e).replace(/0+$/,"");return i?`${r}.${i}`:r}var Q=require("@solana/web3.js"),rt=require("@noble/hashes/utils"),be=require("@dexterai/vault/credit"),it=require("@dexterai/vault/constants"),bn=require("@dexterai/vault/instructions"),wn=require("@dexterai/vault/reader"),we=require("@dexterai/vault/session");var Sr=Uint8Array.from([56,67,4,209,238,143,0,129]),_r=74,Sn=new Set([1,2]),Cr=188,xr=new Q.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Rr=(()=>{let t=Buffer.alloc(32);return t.write("OTS_SESSION_REGISTER_V2","ascii"),t})(),Te=class extends Error{constructor(n,r){super(`native_tab_v2_solana_reservation_invalid:${n}`+(r?`:${r}`:""));this.code=n;this.name="SolanaFinalVoucherV2ReservationError"}code};function m(t,e){throw new Te(t,e)}function F(t,e){try{return new Q.PublicKey(t)}catch{return m(e)}}function nt(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}async function Er(t){let n=(await t.connection.getSignatureStatuses([t.signature],{searchTransactionHistory:!0})).value[0]??null;if(!n)return null;n.confirmationStatus!=="confirmed"&&n.confirmationStatus!=="finalized"&&m("transaction_commitment"),n.err!==null&&m("transaction_failed");let r=await t.connection.getTransaction(t.signature,{commitment:t.commitment,maxSupportedTransactionVersion:0});if(!r)return null;r.meta||m("transaction_meta_missing"),r.slot!==n.slot&&m("transaction_status_slot");let i=r.transaction.message,o=i.version===0?i.getAccountKeys({accountKeysFromLookups:r.meta.loadedAddresses??null}):i.getAccountKeys(),s=(c,l)=>{let p=o.get(c);return p||m(l),p};return{slot:r.slot,confirmationStatus:n.confirmationStatus,err:r.meta.err,signatures:[...r.transaction.signatures],accountKeys:Array.from({length:o.length},(c,l)=>({address:s(l,"transaction_account_key").toBase58(),signer:i.isAccountSigner(l),writable:i.isAccountWritable(l)})),instructions:i.compiledInstructions.map(c=>({programId:s(c.programIdIndex,"transaction_program_id").toBase58(),accounts:c.accountKeyIndexes.map(l=>s(l,"transaction_instruction_account").toBase58()),data:Uint8Array.from(c.data)}))}}function Pr(t,e,n,r){r.length!==_r&&m("binding_length"),nt(r.subarray(0,8),Sr)||m("binding_discriminator");let i=r.readUInt8(8),o=r.readUInt8(9);return Sn.has(i)||m("binding_version"),o!==e&&m("binding_bump"),{address:t.toBase58(),owner:n.toBase58(),version:i,bump:o,swig:new Q.PublicKey(r.subarray(10,42)).toBase58(),vault:new Q.PublicKey(r.subarray(42,74)).toBase58()}}async function Vr(t){let e=F(t.input.programId,"program_id"),n=F(t.input.buyerSwigAddress,"buyer_swig"),r=F(t.input.vaultPda,"vault_pda"),i=F(t.input.seller,"seller"),[o,s]=(0,be.deriveSwigVaultBindingPda)(n,e),[c]=(0,we.deriveSessionPda)(r,i,e),l=await t.connection.getMultipleAccountsInfoAndContext([o,r,c],{commitment:t.commitment,minContextSlot:t.minimumSlot}),[p,y,v]=l.value;p||m("binding_missing"),y||m("vault_missing"),v||m("session_missing");let h,f;try{h=(0,wn.decodeVaultFull)(Buffer.from(y.data)),f=(0,we.decodeSessionAccount)(c,v.data)}catch(S){return m("post_state_decode",S instanceof Error?S.message:String(S))}let g=f.session;return{contextSlot:l.context.slot,binding:Pr(o,s,p.owner,Buffer.from(p.data)),vault:{owner:y.owner.toBase58(),exists:h.exists,version:h.version,swigAddress:h.swigAddress,dexterAuthority:h.dexterAuthority,pendingVoucherCount:h.pendingVoucherCount},session:{owner:v.owner.toBase58(),version:f.version,bump:f.bump,vault:f.vault,sessionPublicKey:(0,rt.bytesToHex)(g.sessionPubkey),maxAmount:g.maxAmount,expiresAt:g.expiresAt,seller:g.allowedCounterparty,nonce:g.nonce,spent:g.spent,currentOutstanding:g.currentOutstanding,maxRevolvingCapacity:g.maxRevolvingCapacity,crystallizedCumulative:g.crystallizedCumulative}}}function Tr(t){let e=Buffer.from(t.voucher.sessionRegistration);return e.length!==Cr&&m("registration_length"),nt(e.subarray(0,32),Rr)||m("registration_domain"),{programId:new Q.PublicKey(e.subarray(32,64)).toBase58(),vaultPda:new Q.PublicKey(e.subarray(64,96)).toBase58(),sessionPublicKey:(0,rt.bytesToHex)(e.subarray(96,128)),maxAmount:e.readBigUInt64LE(128),expiresAt:e.readBigInt64LE(136),seller:new Q.PublicKey(e.subarray(144,176)).toBase58(),nonce:e.readUInt32LE(176),maxRevolvingCapacity:e.readBigUInt64LE(180)}}function Ae(t,e,n){let r=t.accountKeys.filter(i=>i.address===e);return r.length!==1&&m(`${n}_account_key`),r[0]}function Ir(t,e,n){(!Number.isSafeInteger(n.slot)||n.slot<=0)&&m("transaction_slot"),n.slot!==e.confirmationSlot&&m("transaction_confirmation_slot"),n.err!==null&&m("transaction_failed"),n.signatures[0]!==e.transaction&&m("transaction_signature"),n.instructions.length!==2&&m("transaction_instruction_count");let r=F(t.programId,"program_id"),i=F(t.buyerSwigAddress,"buyer_swig"),o=F(t.vaultPda,"vault_pda"),s=F(t.seller,"seller"),c=F(t.sessionPda,"session_pda"),[l]=(0,we.deriveSessionPda)(o,s,r),p=(0,be.deriveSwigVaultBindingPda)(i,r)[0],y=(0,bn.deriveSwigWalletAddress)(i),v=(0,be.deriveGraphConfigPda)(r)[0];c.equals(l)||m("session_pda_derivation");let h=Buffer.from(it.DISCRIMINATORS.settle_voucher),f=n.instructions.filter(a=>{if(a.programId!==t.programId)return!1;let x=a.data;return x.length>=h.length&&nt(x.subarray(0,h.length),h)});f.length!==1&&m("settle_voucher_instruction_count");let g=f[0];n.instructions[0]!==g&&m("settle_voucher_instruction_order");let S=Buffer.from(g.data);S.length!==49&&m("settle_voucher_instruction_length"),S.readBigUInt64LE(8).toString()!==t.reservationAmountAtomic&&m("settle_voucher_amount"),S.readUInt8(16)!==1&&m("settle_voucher_increment"),new Q.PublicKey(S.subarray(17,49)).equals(s)||m("settle_voucher_seller"),g.accounts.length<8&&m("settle_voucher_accounts"),[o.toBase58(),null,c.toBase58(),null,i.toBase58(),y.toBase58(),p.toBase58(),v.toBase58()].forEach((a,x)=>{a!==null&&g.accounts[x]!==a&&m(`settle_voucher_account_${x}`)});let I=g.accounts[1];I||m("dexter_authority");let j=Ae(n,g.accounts[0],"vault"),te=Ae(n,I,"dexter_authority"),oe=Ae(n,g.accounts[2],"session");(!j.writable||j.signer)&&m("vault_privileges"),te.signer||m("dexter_authority_signature"),(!oe.writable||oe.signer)&&m("session_privileges");for(let a=3;a<Math.min(g.accounts.length,8);a+=1)Ae(n,g.accounts[a],`account_${a}`).signer&&m(`settle_voucher_account_${a}_signer`);for(let a=8;a<g.accounts.length;a+=1){let x=Ae(n,g.accounts[a],`sibling_${a-8}`);(!x.writable||x.signer)&&m("settle_voucher_sibling_privileges")}let q=n.instructions[1];q.programId!==xr.toBase58()&&m("reservation_memo_program"),(q.accounts.length!==1||q.accounts[0]!==I)&&m("reservation_memo_authority"),Ae(n,I,"reservation_memo_authority").signer||m("reservation_memo_authority_signature");let d=new TextEncoder().encode(yn(t));return nt(q.data,d)||m("reservation_memo_digest"),I}function Nr(t,e,n,r){let i=F(t.programId,"program_id"),o=F(t.buyerSwigAddress,"buyer_swig"),s=F(t.vaultPda,"vault_pda"),c=F(t.seller,"seller"),[l,p]=(0,be.deriveSwigVaultBindingPda)(o,i),[y,v]=(0,we.deriveSessionPda)(s,c,i);(!Number.isSafeInteger(r.contextSlot)||r.contextSlot<e)&&m("post_state_slot"),(r.binding.address!==l.toBase58()||r.binding.owner!==t.programId||r.binding.bump!==p||!Sn.has(r.binding.version)||r.binding.swig!==t.buyerSwigAddress||r.binding.vault!==t.vaultPda)&&m("binding_identity"),(r.vault.owner!==t.programId||!r.vault.exists||r.vault.version!==7||r.vault.swigAddress!==t.buyerSwigAddress||r.vault.dexterAuthority!==n)&&m("vault_post_state"),(t.sessionPda!==y.toBase58()||r.session.owner!==t.programId||r.session.version!==1||r.session.bump!==v||r.session.vault!==t.vaultPda||r.session.sessionPublicKey!==(0,rt.bytesToHex)(t.voucher.sessionPublicKey)||r.session.seller!==t.seller||r.session.nonce!==t.sessionNonce||r.session.currentOutstanding.toString()!==t.reservationAmountAtomic)&&m("session_post_state");let h=Tr(t);(h.programId!==t.programId||h.vaultPda!==t.vaultPda||h.sessionPublicKey!==r.session.sessionPublicKey||h.seller!==t.seller||h.nonce!==t.sessionNonce||h.maxAmount!==r.session.maxAmount||h.expiresAt!==BigInt(r.session.expiresAt)||h.maxRevolvingCapacity!==r.session.maxRevolvingCapacity)&&m("registration_post_state");let f=r.session.spent>r.session.crystallizedCumulative?r.session.spent:r.session.crystallizedCumulative;return f.toString()!==t.previousCumulativeAtomic&&m("session_frontier"),{commitment:"confirmed",confirmationSlot:e,postStateSlot:r.contextSlot,sessionAccountVersion:r.session.version,wireVersion:2,frontierAtomic:f.toString(),spentAtomic:r.session.spent.toString(),currentOutstandingAtomic:r.session.currentOutstanding.toString(),crystallizedCumulativeAtomic:r.session.crystallizedCumulative.toString()}}async function _n(t,e,n,r={}){try{$t(e,n)}catch(c){return m("provider_receipt",c instanceof Error?c.message:String(c))}e.network!=="solana:mainnet"&&m("network"),e.programId!==it.DEXTER_VAULT_PROGRAM_ID.toBase58()&&m("program_id");let i=await(r.readTransaction??Er)({connection:t,signature:n.transaction,commitment:"confirmed"});i||m("transaction_missing"),i.confirmationStatus!=="confirmed"&&i.confirmationStatus!=="finalized"&&m("transaction_commitment");let o=Ir(e,n,i),s=await(r.readPostState??Vr)({connection:t,input:e,minimumSlot:i.slot,commitment:"confirmed"});return{...Nr(e,i.slot,o,s),commitment:i.confirmationStatus}}var En=require("@dexterai/vault/session");var ot=require("@noble/hashes/utils"),Lr=15e3,Or=["claim_already_exists","non_monotonic_cumulative"],kr="below_lock_cadence";function st(t){return typeof t=="string"&&t.includes(kr)}function Br(t){return`${t.slice(0,16)}\u2026`}function Cn(t,e,n,r){let i=Br(t);if(r.crystallized){console.info(`[tab/seller] crystallize OK channel=${i} cumulative=${e} seq=${n}${r.claimPda?` claimPda=${r.claimPda}`:""} \u2014 LockVoucher landed`);return}if(r.error){if(st(r.error)){console.warn(`[tab/seller] crystallize refused below the facilitator's cadence gate channel=${i} cumulative=${e} seq=${n}: ${r.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(Or.some(o=>r.error.includes(o))){console.warn(`[tab/seller] crystallize duplicate channel=${i} cumulative=${e} seq=${n}: ${r.error} \u2014 voucher already secured on-chain (benign, no action)`);return}console.error(`[tab/seller] crystallize FAILED channel=${i} cumulative=${e} seq=${n}: ${r.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 Mt(t,e,n,r,i=fetch){let o=t.lastVoucher;if(!o)return{crystallized:!1};if(o.payload.channelId!==e){let c={crystallized:!1,error:"channel_id_mismatch"};return Cn(e,o.payload.cumulativeAmount,o.payload.sequenceNumber,c),c}let s=c=>(Cn(e,o.payload.cumulativeAmount,o.payload.sequenceNumber,c),c);try{let c=`${n.replace(/\/$/,"")}/tab/lock`,l={channelId:o.payload.channelId,cumulativeAmount:o.payload.cumulativeAmount,sequenceNumber:o.payload.sequenceNumber,sessionPublicKey:(0,ot.bytesToHex)(o.sessionPublicKey),sessionSignature:(0,ot.bytesToHex)(o.sessionSignature),sessionRegistration:(0,ot.bytesToHex)(o.sessionRegistration),network:r},p=await i(c,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(Lr)}),y=await p.text();if(!p.ok)return s({crystallized:!1,error:`tab lock ${p.status}: ${y.slice(0,200)}`});let v;try{let h=JSON.parse(y);h&&typeof h.claimPda=="string"&&(v=h.claimPda)}catch{}return s({crystallized:!0,claimPda:v})}catch(c){return s({crystallized:!1,error:String(c?.message??c)})}}async function xn(t,e,n,r,i,o={}){let s=BigInt(t.deliveredCumulativeAtomic),c=BigInt(t.lastCrystallizedCumulativeAtomic??"0"),l=BigInt(i.thresholdAtomic);if(s-c<l)return{crystallized:!1};let p=t.lastVoucher?.payload.cumulativeAmount,y=t.gateRefusedCumulativeAtomic;if(p!==void 0&&y!==void 0&&BigInt(p)<=BigInt(y))return{crystallized:!1};let v=await Mt(t,e,n,r,o.fetchImpl);return v.crystallized&&p!==void 0?(t.lastCrystallizedCumulativeAtomic=p,t.gateRefusedCumulativeAtomic=void 0):st(v.error)&&p!==void 0&&(t.gateRefusedCumulativeAtomic=p),v}var ie="x-tab-voucher",lt=class extends Error{constructor(){super("response terminated before tab admission completed"),this.name="ResponseTerminatedError"}};function Ur(t){if(t!==void 0)return t;if(process.env.NODE_ENV==="test"||process.env.NODE_ENV==="development")return"development";throw new Error("tab seller ledgerSafetyMode must be explicit outside NODE_ENV=test/development; choose production-single-instance or production-multi-instance for deployment")}function Kr(t,e){if(!["development","production-single-instance","production-multi-instance"].includes(e))throw new Error(`invalid tab seller ledgerSafetyMode: ${String(e)}`);let n=t.capabilities;if(!n||n.conditionalWrites!==!0)throw new Error("tab seller ledger must declare conditional owner-token/fence writes");if(e!=="development"&&!n.restartSafe)throw new Error(`tab seller ${e} requires restart-safe durable ledger state; ${n.adapter} is not restart-safe`);if(e!=="development"&&!n.canonicalChannelIds)throw new Error(`tab seller ${e} requires the legacy channel-id alias migration or an empty-store proof; ${n.adapter} has no canonical channel-id cutover acknowledgement`);if(e==="production-multi-instance"&&!n.multiInstanceSafe)throw new Error(`tab seller production-multi-instance requires cross-process atomic fencing; ${n.adapter} is single-instance only`)}var Dt=class{map=new Map;get(e){return this.map.get(e)}set(e,n){this.map.set(e,n)}deleteIfSame(e,n){this.map.get(e)===n&&this.map.delete(e)}update(e,n){let r=this.map.get(e);r&&(r.lastCumulativeAtomic=n)}delete(e){this.map.delete(e)}},Ft=class{constructor(e,n,r,i,o,s){this.recordDeliveredImpl=o;this.chargeImpl=s;this.channelId=e,this.network=n,this.cumulativeAtomic=r,this.deliveredBaselineAtomic=i}recordDeliveredImpl;chargeImpl;channelId;network;sessionPublicKey=null;cumulativeAtomic;deliveredBaselineAtomic;cumulative(){return de(this.cumulativeAtomic.toString())}deliveredCumulative(){return de(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 $r(t){if(typeof t!="string"||t.length===0)throw new w("signature_invalid",`missing ${ie} header`);let e;try{e=Buffer.from(t,"base64").toString("utf8")}catch{throw new w("signature_invalid","malformed base64")}let n;try{n=JSON.parse(e)}catch{throw new w("signature_invalid","malformed JSON")}if(!n||typeof n!="object"||!n.payload||!n.sessionPublicKey)throw new w("signature_invalid","missing required fields");return{voucher:{payload:n.payload,sessionPublicKey:ct(n.sessionPublicKey),sessionRegistration:ct(n.sessionRegistration),sessionSignature:ct(n.sessionSignature)},reservationReceipt:n.reservationReceipt}}function ct(t){if(typeof t!="string"||t.length%2!==0)throw new w("signature_invalid",`bad hex: ${typeof t}`);let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.substr(n*2,2),16);return e}function Mr(t){if(!/^[0-9a-f]{64}$/.test(t))throw new w("signature_invalid",`channelId must be canonical lowercase 64-char hex, got "${t}"`);return ct(t)}function ut(t){let e=t.ledger??new ye,n=Ur(t.ledgerSafetyMode);Kr(e,n);let r=Z(t.leaseTtlMs??3e5),i=new Dt,o=typeof t.sellerPubkey=="string"?new Rn.PublicKey(t.sellerPubkey):t.sellerPubkey,s=t.maxPerVoucherAtomic?BigInt(t.maxPerVoucherAtomic):BigInt(G(t.perUnit))*100n,c=t.facilitatorUrl??vn,l={thresholdAtomic:t.lockCadence?.thresholdAtomic??G("0.10"),onClose:t.lockCadence?.onClose??!0};return async(p,y,v)=>{let h=null,f=null,g=null,S=null,P=null,I=!1,j=async()=>{if(P)throw P},te=async()=>{if(!f||f.releaseStarted)return;let _=f;_.releaseStarted=!0,g&&(clearInterval(g),g=null),S&&await S.catch(()=>{});try{await e.releaseLease(_.channelId,f?.lease??_.lease)}catch(d){throw _.releaseStarted=!1,d}},oe=()=>{I||(I=!0,setImmediate(()=>{te().catch(_=>{console.error("[tab/seller] failed to release channel lease on response termination:",_)})}))},q=()=>{if(I)throw new lt};y.on("close",oe),y.on("finish",oe);try{let _=$r(p.headers[ie]),d=_.voucher,a=d.payload.channelId,x=Mr(a),A=i.get(a),O=null,$,xt=!1;if(A){if(!me(A.registrationBytes,d.sessionRegistration))throw new T("voucher registration does not match the channel's verified registration")}else{xt=!0;let u=Pe(d.sessionRegistration);re(u.nonce)===1&&($=await Ze(t.connection,u),O=$?.frontierAtomic??null);let C=await e.get(a);A={registration:u,registrationBytes:d.sessionRegistration.slice(),lastCumulativeAtomic:C?.lastVoucher?.payload.cumulativeAmount??"0"}}let z=re(A.registration.nonce),Ht=re(d.payload.sequenceNumber);if(Ht!==z)throw new w("wire_version_mismatch",`voucher is V${Ht}, active registration is V${z}`);let _e;if(z===2){if(_.reservationReceipt===void 0)throw new w("reservation_proof_missing","Native Tab V2 requires the verified reservation receipt in the voucher envelope");if(_.reservationReceipt===null||typeof _.reservationReceipt!="object"||Array.isArray(_.reservationReceipt))throw new w("reservation_proof_invalid","reservationReceipt must be an object");_e=_.reservationReceipt}Qe(d,x);let k=BigInt(d.payload.cumulativeAmount),X=BigInt(A.lastCumulativeAtomic),Ce=null,J=null,Rt=null;if(z===2){if(!_e)throw new w("reservation_proof_missing","Native Tab V2 reservation proof was not carried through admission");if(J=at(_e.reservationAmountAtomic,"receipt.reservationAmountAtomic"),J<=0n||J>k)throw new w("reservation_mismatch","reservation amount does not fit the voucher cumulative");let u=k-J,[C]=(0,En.deriveSessionPda)(A.registration.vaultPda,A.registration.allowedCounterparty,A.registration.programId),R=Kt(d);try{let U=await _n(t.connection,{network:t.network,programId:A.registration.programId.toBase58(),buyerSwigAddress:_e.buyerSwigAddress,vaultPda:A.registration.vaultPda.toBase58(),sessionPda:C.toBase58(),seller:A.registration.allowedCounterparty.toBase58(),channelId:a,sessionNonce:A.registration.nonce,reservationAmountAtomic:J.toString(),previousCumulativeAtomic:u.toString(),...R,voucher:d},_e);$=U,O=U.frontierAtomic}catch(U){throw U instanceof Te?new w("reservation_proof_invalid",U.message):U}if($?.wireVersion!==2)throw new w("wire_version_mismatch",`active SessionAccount is V${$?.wireVersion??"unknown"}, voucher is V2`);if($.sessionAccountVersion!==1||O===null||$.currentOutstandingAtomic===void 0)throw new w("reservation_mismatch","authoritative V2 SessionAccount reservation evidence is incomplete");let b=at(O,"frontierAtomic");if(b>X&&(X=b),k<=X)throw new w("voucher_already_covered",`cumulative ${k} is not above covered frontier ${X}`);Ce=k-X;let B=at($.currentOutstandingAtomic,"currentOutstandingAtomic");if(Rt=B,B!==Ce)throw new w("reservation_mismatch",`currentOutstanding ${B} does not equal voucher delta ${Ce}`);if(J!==Ce)throw new w("reservation_mismatch",`receipt reservation ${J} does not equal voucher delta ${Ce}`)}let Hn=z===1&&k===X;Ve({registration:A.registration,voucher:d,expectedCounterparty:o,previousCumulativeAtomic:Hn?void 0:X.toString()});let se=k-X;if(se>s)throw new N("cumulative_exceeds_cap",`single voucher increment ${se} exceeds maxPerVoucherAtomic ${s}`);if(xt){let u=i.get(a);if(u){if(!me(u.registrationBytes,A.registrationBytes))throw new T("voucher registration lost the channel admission race to a different verified registration");if(BigInt(u.lastCumulativeAtomic)>BigInt(A.lastCumulativeAtomic))throw new N("non_monotonic","channel admission advanced while reservation proof was in flight");A=u}}q();let xe=await e.tryAcquireLease(a,r);if(!xe)throw new w("channel_busy","another stream is live on this channel; tabs serve one stream at a time");f={channelId:a,lease:xe,releaseStarted:!1},q();let Wt=Math.max(1,Math.floor(r/3)),Gt=async()=>{if(P)throw P;if(!f||f.releaseStarted)throw new M(a);return S||(S=(async()=>{let u=await e.renewLease(a,f.lease,r);f&&!f.releaseStarted&&(f.lease=u)})().catch(u=>{let C=u instanceof Error?u:new Error(String(u));throw P=C,console.error(`[tab/seller] channel lease renewal FAILED channel=${a.slice(0,16)}\u2026; stream terminated before further delivery:`,C),typeof y.destroy=="function"&&y.destroy(C),C}).finally(()=>{S=null}),S)};j=async()=>{if(P)throw P;if(!f||f.releaseStarted)throw new M(a);f.lease.heldUntilUnixMs-Date.now()<=Wt&&await Gt()},g=setInterval(()=>{Gt().catch(()=>{})},Wt),g.unref?.();let Re=await e.get(a);if(q(),Re?.lastVoucher&&!me(Re.lastVoucher.sessionRegistration,d.sessionRegistration))throw new T("durable channel registration changed while reservation proof was in flight");let jt=BigInt(Re?.lastVoucher?.payload.cumulativeAmount??"0"),H=BigInt(A.lastCumulativeAtomic);if(jt>H&&(H=jt),z===2&&O!==null){let u=at(O,"frontierAtomic");u>H&&(H=u)}let Xt=z===1&&k===H;if(k<H||z===2&&k===H)throw new w(z===2?"voucher_already_covered":"non_monotonic",`cumulative ${k} is not above post-lease covered frontier ${H}`);if(Xt){let u=Re?.lastVoucher;if(!u||BigInt(u.payload.cumulativeAmount)!==k||d.payload.sequenceNumber<=u.payload.sequenceNumber)throw new w("non_monotonic","same-cumulative V1 reconnect requires a strictly newer sequence than the durable voucher")}if(Ve({registration:A.registration,voucher:d,expectedCounterparty:o,previousCumulativeAtomic:Xt?void 0:H.toString()}),se=k-H,se>s)throw new N("cumulative_exceeds_cap",`post-lease voucher increment ${se} exceeds maxPerVoucherAtomic ${s}`);if(z===2&&(J===null||Rt===null||J!==se||Rt!==se))throw new w("reservation_mismatch","durable channel frontier advanced while reservation proof was in flight");if(X=H,xt){let u=i.get(a);if(u){if(!me(u.registrationBytes,A.registrationBytes))throw await te(),new T("voucher registration lost the channel lease race to a different verified registration");A=u}else i.set(a,A),h={channelId:a,entry:A}}let Et=async u=>{try{return await e.update(a,xe,u)}catch(C){if(!(C instanceof M))throw C;let R=await e.tryAcquireLease(a,Math.min(r,15e3));if(!R)throw C;try{return await e.update(a,R,u)}finally{await e.releaseLease(a,R)}}},Wn=async u=>{let C=u.lastCrystallizedCumulativeAtomic??"0",R=u.gateRefusedCumulativeAtomic;await xn(u,a,c,t.network,l),(u.lastCrystallizedCumulativeAtomic!==C||u.gateRefusedCumulativeAtomic!==R)&&await Et(b=>{if(!b)throw new Error("channel ledger entry missing during crystallize persist");let B=BigInt(b.lastCrystallizedCumulativeAtomic??"0")>=BigInt(u.lastCrystallizedCumulativeAtomic??"0")?b.lastCrystallizedCumulativeAtomic??"0":u.lastCrystallizedCumulativeAtomic??"0",ge=[b.gateRefusedCumulativeAtomic,u.gateRefusedCumulativeAtomic].filter(he=>he!==void 0).reduce((he,nn)=>he===void 0||BigInt(nn)>BigInt(he)?nn:he,void 0);return{...b,lastCrystallizedCumulativeAtomic:B,gateRefusedCumulativeAtomic:ge!==void 0&&BigInt(ge)>BigInt(B)?ge:void 0}}).catch(b=>{console.error(`[tab/seller] crystallize watermark persist FAILED channel=${a.slice(0,16)}\u2026 (expect a benign duplicate/below-cadence warn on the next request):`,b)})},Jt=Promise.resolve(),Yt=u=>{let C=Jt.then(u,u);return Jt=C.catch(()=>{}),C},Zt=!1,Qt=()=>{!l.onClose||Zt||(Zt=!0,Yt(async()=>{let u=await e.get(a);if(!u||!u.lastVoucher)return;let C=u.lastVoucher.payload.cumulativeAmount;if(u.gateRefusedCumulativeAtomic!==void 0&&BigInt(C)<=BigInt(u.gateRefusedCumulativeAtomic))return;let R=await Mt(u,a,c,t.network);R.crystallized?await Et(b=>{if(!b)throw new Error("channel ledger entry missing during close crystallize");let B=BigInt(b.lastCrystallizedCumulativeAtomic??"0")>=BigInt(C)?b.lastCrystallizedCumulativeAtomic??"0":C;return{...b,lastCrystallizedCumulativeAtomic:B,gateRefusedCumulativeAtomic:b.gateRefusedCumulativeAtomic!==void 0&&BigInt(b.gateRefusedCumulativeAtomic)>BigInt(B)?b.gateRefusedCumulativeAtomic:void 0}}):st(R.error)&&await Et(b=>{if(!b)throw new Error("channel ledger entry missing during close refusal persist");let B=BigInt(b.lastCrystallizedCumulativeAtomic??"0"),U=b.gateRefusedCumulativeAtomic!==void 0&&BigInt(b.gateRefusedCumulativeAtomic)>=BigInt(C)?b.gateRefusedCumulativeAtomic:C;return{...b,gateRefusedCumulativeAtomic:BigInt(U)>B?U:void 0}})}).catch(u=>{console.error(`[tab/seller] close-path crystallize CRASHED channel=${a.slice(0,16)}\u2026 (final voucher NOT locked; exposure unsecured until the next request retries):`,u)}))};y.on("close",Qt),y.on("finish",Qt);let De=Re,en=BigInt(De?.deliveredCumulativeAtomic??"0"),Gn=!De?.lastVoucher&&en===0n,Pt=O===null?null:BigInt(O),pe=Pt!==null&&Pt>en&&(z===2||Gn)?Pt.toString():null;pe!==null&&console.info(`[tab/seller] channel ${a.slice(0,16)}\u2026 resumed: seeding delivered baseline from chain frontier ${pe} (session already settled/locked up to it \u2014 that span is not deliverable budget)`);let jn=pe!==null?BigInt(pe):De?BigInt(De.deliveredCumulativeAtomic):0n;await e.update(a,xe,u=>({...u??{},lastVoucher:d,deliveredCumulativeAtomic:pe??(u?u.deliveredCumulativeAtomic:"0"),lastCrystallizedCumulativeAtomic:pe??u?.lastCrystallizedCumulativeAtomic??"0"})),h=null,q(),i.update(a,d.payload.cumulativeAmount);let tn=new Ft(a,t.network,k,jn,async u=>{await j();let C=null;C=await e.update(a,xe,R=>{if(!R?.lastVoucher||!Dr(R.lastVoucher,d))throw new T("durable voucher identity changed before delivery accounting");let b=BigInt(R.deliveredCumulativeAtomic),B=BigInt(u),U=B>0n?b+B:b,ge=BigInt(R.lastVoucher.payload.cumulativeAmount);if(U>ge)throw new N("cumulative_exceeds_cap",`durable delivered cumulative ${U} exceeds signed cumulative ${ge}`);return{...R,lastVoucher:R.lastVoucher,deliveredCumulativeAtomic:U.toString(),lastCrystallizedCumulativeAtomic:R.lastCrystallizedCumulativeAtomic??"0"}}),C&&Yt(async()=>{let R=await e.get(a);R&&await Wn(R)}).catch(R=>{console.error(`[tab/seller] crystallize cadence CRASHED channel=${a.slice(0,16)}\u2026 (threshold lock not attempted; retries at the next delivery):`,R)})},async u=>{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.")});tn.setSessionPublicKey(d.sessionPublicKey),p.tab=tn,v()}catch(_){if(f&&!f.releaseStarted&&await te().catch(d=>{console.error("[tab/seller] failed to release channel lease after request error:",d)}),h&&i.deleteIfSame(h.channelId,h.entry),_ instanceof lt)return;if(_ instanceof w||_ instanceof W||_ instanceof K||_ instanceof T||_ instanceof N){y.status(402).json({error:"invalid_voucher",reason:_.reason??"unknown",detail:_.message});return}v(_)}}}function me(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r+=1)n|=t[r]^e[r];return n===0}function Dr(t,e){return t.payload.channelId===e.payload.channelId&&t.payload.cumulativeAmount===e.payload.cumulativeAmount&&t.payload.sequenceNumber===e.payload.sequenceNumber&&me(t.sessionPublicKey,e.sessionPublicKey)&&me(t.sessionRegistration,e.sessionRegistration)&&me(t.sessionSignature,e.sessionSignature)}function at(t,e){if(!/^(0|[1-9][0-9]*)$/.test(t))throw new w("reservation_mismatch",`authoritative ${e} is not a canonical atomic amount`);return BigInt(t)}function Pn(t){if(!t.tab)throw new Error("req.tab is missing \u2014 did tabMiddleware run on this route?");return t.tab}function Vn(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 n=e.tab,r=BigInt(G(n.cumulative())),i=BigInt(G(n.deliveredCumulative())),o=r-i;o<0n&&(o=0n);let s=e.perUnit?BigInt(G(e.perUnit)):null,c=0n,l=!1,p=0,y=Promise.resolve();t.prependListener("close",()=>{l||(l=!0)});function v(g=1){if(l)return Promise.reject(new Error("meter ended"));if(s===null)return Promise.reject(new Error("charge() needs options.perUnit"));if(!Number.isSafeInteger(g)||g<=0)return Promise.reject(new Error("charge() units must be a positive safe integer"));let S=s*BigInt(g);p+=1;let P=y.then(async()=>{if(l)throw new Error("meter ended");let I=c+S;if(I>o)throw l=!0,new N("cumulative_exceeds_cap",`chunk would push delivered to ${de((i+I).toString())} beyond signed cumulative ${de(r.toString())} (per-request budget ${de(o.toString())})`);try{await n.recordDelivered(S.toString()),c=I}catch(j){throw l=!0,j}});return y=P.catch(()=>{}),P.finally(()=>{p-=1})}function h(g){if(l)throw new Error("meter ended");if(p>0)throw new Error("charge still pending; await meter.charge() before send()");let P=(typeof g=="string"?g:Buffer.from(g).toString("utf8")).replace(/\\/g,"\\\\").replace(/\n/g,"\\n");t.write(`data: ${P}
22
+ `,sr='return redis.call("get", KEYS[1])',Pe=class extends Error{constructor(e){super(`legacy Redis seller state exists for channel ${e}; stop all legacy writers, migrate/delete the legacy ledger, lease, and fence keys, then retry cluster-v1`),this.name="RedisKeyspaceMigrationRequiredError"}};function Xe(t){return`${t.ownerToken}:${t.fence}`}function Je(t){return t===1||t==="1"}var Ye=class{constructor(e,n="tab:"){this.client=e;if(typeof n!="string"&&(n===null||typeof n!="object"||Array.isArray(n)))throw new Error("RedisChannelLedger options must be a key prefix or options object");let r=typeof n=="string"?{keyPrefix:n}:n;if(r.keyPrefix!==void 0&&typeof r.keyPrefix!="string")throw new Error("RedisChannelLedger keyPrefix must be a string");if(this.keyPrefix=r.keyPrefix??"tab:",this.keyLayout=r.keyLayout??"legacy-v0",!["legacy-v0","cluster-v1"].includes(this.keyLayout))throw new Error(`invalid RedisChannelLedger keyLayout: ${String(this.keyLayout)}`);if(this.keyLayout==="cluster-v1"&&(this.keyPrefix.includes("{")||this.keyPrefix.includes("}")))throw new Error("cluster-v1 keyPrefix must not contain Redis hash-tag braces");if(r.writerCutover!==void 0&&r.writerCutover!=="all-legacy-writers-stopped")throw new Error("invalid RedisChannelLedger writerCutover acknowledgement");if(r.channelIdCutover!==void 0&&r.channelIdCutover!=="legacy-case-aliases-migrated-or-empty")throw new Error("invalid RedisChannelLedger channelIdCutover acknowledgement");if(this.keyLayout==="cluster-v1"&&r.keyspaceCutover!=="legacy-state-migrated-or-empty")throw new Error("cluster-v1 requires keyspaceCutover: legacy-state-migrated-or-empty");let i=r.durability;if(i!==void 0&&!an(i))throw new Error("RedisChannelLedger durability attestation must confirm aof-always, no-data-loss failover, noeviction, and dedicated-instance isolation");this.capabilities={adapter:"redis",restartSafe:an(i)&&r.writerCutover==="all-legacy-writers-stopped",multiInstanceSafe:!0,conditionalWrites:!0,canonicalChannelIds:r.channelIdCutover==="legacy-case-aliases-migrated-or-empty"}}client;capabilities;keyPrefix;keyLayout;assertChannelId(e){V(e)}legacyKey(e,n){return this.assertChannelId(e),`${this.keyPrefix}${n}:${e}`}channelKey(e,n){return this.assertChannelId(e),this.keyLayout==="cluster-v1"?`${this.keyPrefix}{${e}}:${n}`:this.legacyKey(e,n)}ledgerKey(e){return this.channelKey(e,"ledger")}leaseKey(e){return this.channelKey(e,"lease")}fenceKey(e){return this.channelKey(e,"fence")}async primaryGet(e){let n=await this.client.eval(sr,1,e);if(n===null||n===!1)return null;if(typeof n!="string")throw new Error(`Redis primary GET returned invalid value type: ${typeof n}`);return n}async assertClusterCutover(e){if(this.keyLayout!=="cluster-v1")return;let n=await this.primaryGet(this.legacyKey(e,"ledger")),r=await this.primaryGet(this.legacyKey(e,"lease")),i=await this.primaryGet(this.legacyKey(e,"fence"));if(n!==null||r!==null||i!==null)throw new Pe(e)}async get(e){this.assertChannelId(e),await this.assertClusterCutover(e);let n=await this.primaryGet(this.ledgerKey(e));return n===null?null:je(JSON.parse(n))}async writeIfOwned(e,n,r){let i=Ge(n),o=await this.client.eval(nr,2,this.leaseKey(e),this.ledgerKey(e),Xe(r),JSON.stringify(i));if(!Je(o))throw new M(e)}async set(e,n,r){this.assertChannelId(e),await E(e,()=>this.writeIfOwned(e,n,r))}async update(e,n,r){return this.assertChannelId(e),E(e,async()=>{let i=r(await this.get(e));return await this.writeIfOwned(e,i,n),i})}async delete(e,n){this.assertChannelId(e),await E(e,async()=>{let r=await this.client.eval(rr,2,this.leaseKey(e),this.ledgerKey(e),Xe(n));if(!Je(r))throw new M(e)})}async tryAcquireLease(e,n){return this.assertChannelId(e),E(e,async()=>{await this.assertClusterCutover(e);let r=(0,cn.randomUUID)(),i=Z(n),o=await this.client.eval(tr,2,this.leaseKey(e),this.fenceKey(e),r,i);if(o===null||o===!1||o===0||o==="0")return null;let s=String(o);if(!/^[1-9][0-9]*$/.test(s))throw new Error(`Redis returned invalid channel fence: ${s}`);return{ownerToken:r,fence:s,heldUntilUnixMs:Date.now()+i}})}async releaseLease(e,n){return this.assertChannelId(e),E(e,async()=>{let r=await this.client.eval(ir,1,this.leaseKey(e),Xe(n));return Je(r)})}async renewLease(e,n,r){return this.assertChannelId(e),E(e,async()=>{let i=Z(r),o=await this.client.eval(or,1,this.leaseKey(e),Xe(n),i);if(!Je(o))throw new M(e);return{...n,heldUntilUnixMs:Date.now()+i}})}};var xn=require("@solana/web3.js");var un=on(require("tweetnacl"),1),cr=require("@noble/hashes/sha256"),lr=require("@noble/curves/p256"),Ze=require("@solana/web3.js");var D=require("@dexterai/vault/messages");var Nt=require("@dexterai/vault/instructions"),ar=require("@dexterai/vault/precompile"),ce=require("@dexterai/vault/constants");var le=require("@dexterai/vault/session"),Ae=require("@dexterai/vault/messages"),Lt="OTS_SESSION_REGISTER_V2";function re(t){return t>=2147483648?2:1}var W=class extends Error{constructor(n,r){super(`Invalid registration: ${n}${r?` (${r})`:""}`);this.reason=n;this.name="InvalidRegistrationError"}reason};function Ve(t){if(t.length!==188)throw new W("wrong_length",`expected 188, got ${t.length}`);let e=new TextDecoder().decode(t.slice(0,Lt.length));if(e!==Lt)throw new W("wrong_domain",`got "${e}"`);for(let v=Lt.length;v<32;v++)if(t[v]!==0)throw new W("wrong_domain",`non-NUL padding at byte ${v}`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=new Ze.PublicKey(t.slice(32,64)),i=new Ze.PublicKey(t.slice(64,96)),o=t.slice(96,128),s=n.getBigUint64(128,!0),c=n.getBigInt64(136,!0),l=new Ze.PublicKey(t.slice(144,176)),p=n.getUint32(176,!0),y=n.getBigUint64(180,!0);if(!r.equals(ce.DEXTER_VAULT_PROGRAM_ID))throw new W("wrong_program",`${r.toBase58()} is not ${ce.DEXTER_VAULT_PROGRAM_ID.toBase58()}`);if(s===0n)throw new W("cap_zero");return{programId:r,vaultPda:i,sessionPubkey:new Uint8Array(o),maxAmount:s,expiresAt:c,allowedCounterparty:l,nonce:p,maxRevolvingCapacity:y}}var K=class extends Error{constructor(n,r){super(`On-chain verification failed: ${n}${r?` (${r})`:""}`);this.reason=n;this.name="OnChainVerificationError"}reason};async function Qe(t,e){let[n]=(0,le.deriveSessionPda)(e.vaultPda,e.allowedCounterparty,e.programId),r=await t.getAccountInfo(n,"finalized");if(!r)throw new K("session_not_active","no finalized SessionAccount PDA for this (vault, counterparty) \u2014 registration may be confirmed-only, revoked, expiry-swept, or never registered");if(!r.owner.equals(e.programId))throw new K("wrong_program",`SessionAccount owner ${r.owner.toBase58()} != ${e.programId.toBase58()}`);let i;try{i=(0,le.decodeSessionAccount)(n,r.data)}catch(h){throw new K("registration_state_mismatch",`finalized SessionAccount decode failed: ${h instanceof Error?h.message:String(h)}`)}if(i.version===0)throw new K("session_not_active","finalized SessionAccount is cleared");if(!(0,le.isSessionLive)(i))throw new K("session_not_active","SessionAccount PDA is present but expired");if(!dn(i.session.sessionPubkey,e.sessionPubkey))throw new K("session_pubkey_mismatch",`on-chain ${ln(i.session.sessionPubkey)} != registration ${ln(e.sessionPubkey)}`);let o=re(e.nonce),s=re(i.session.nonce);if(s!==o)throw new K("wire_version_mismatch",`active SessionAccount is V${s}, voucher registration is V${o}`);let c=Number.isSafeInteger(i.session.expiresAt)&&BigInt(i.session.expiresAt)===e.expiresAt;if(!(i.address===n.toBase58()&&i.vault===e.vaultPda.toBase58()&&i.session.maxAmount===e.maxAmount&&c&&i.session.allowedCounterparty===e.allowedCounterparty.toBase58()&&i.session.nonce===e.nonce&&i.session.maxRevolvingCapacity===e.maxRevolvingCapacity))throw new K("registration_state_mismatch","188-byte registration does not exactly match the active SessionAccount immutable fields");let p=i.session.spent,y=i.session.crystallizedCumulative,v=p>y?p:y;return{sessionAccountVersion:i.version,wireVersion:s,frontierAtomic:v.toString(),spentAtomic:p.toString(),currentOutstandingAtomic:i.session.currentOutstanding.toString(),crystallizedCumulativeAtomic:y.toString()}}var T=class extends Error{constructor(e){super(`Invalid voucher signature${e?`: ${e}`:""}`),this.name="InvalidVoucherSignatureError"}};function et(t,e){if(e.length!==32)throw new T(`channelIdBytes must be 32 bytes, got ${e.length}`);if(t.sessionPublicKey.length!==32)throw new T(`sessionPublicKey must be 32 bytes, got ${t.sessionPublicKey.length}`);if(t.sessionSignature.length!==64)throw new T(`sessionSignature must be 64 bytes, got ${t.sessionSignature.length}`);let n=Ve(t.sessionRegistration);if(!dn(n.sessionPubkey,t.sessionPublicKey))throw new T("registration session key does not match voucher session key");let r=n.nonce>=2147483648,i=re(n.nonce),o=re(t.payload.sequenceNumber);if(i!==o)throw new T(`voucher wire V${o} does not match registration wire V${i}`);let s;if(r){(0,Ae.sessionVoucherV2AuthorizationNonce)(n.nonce),(0,Ae.voucherV2SequenceOrdinal)(t.payload.sequenceNumber);let[l]=(0,le.deriveSessionPda)(n.vaultPda,n.allowedCounterparty,n.programId);s=(0,Ae.contextBoundVoucherV2Message)({programId:n.programId,vaultPda:n.vaultPda,sessionPda:l,seller:n.allowedCounterparty,sessionNonce:n.nonce,channelId:e,cumulativeAmount:BigInt(t.payload.cumulativeAmount),sequenceNumber:t.payload.sequenceNumber})}else s=(0,D.voucherPayloadMessage)({channelId:e,cumulativeAmount:BigInt(t.payload.cumulativeAmount),sequenceNumber:t.payload.sequenceNumber});if(!un.default.sign.detached.verify(s,t.sessionSignature,t.sessionPublicKey))throw new T("ed25519 verify rejected")}var N=class extends Error{constructor(n,r){super(`Scope violation: ${n}${r?` (${r})`:""}`);this.reason=n;this.name="ScopeViolationError"}reason};function Te(t){let e=BigInt(t.voucher.payload.cumulativeAmount);if(e>t.registration.maxAmount)throw new N("cumulative_exceeds_cap",`${e} > ${t.registration.maxAmount}`);let n=BigInt(Math.floor(Date.now()/1e3));if(n>=t.registration.expiresAt)throw new N("session_expired",`now=${n} >= expiresAt=${t.registration.expiresAt}`);if(!t.registration.allowedCounterparty.equals(t.expectedCounterparty))throw new N("wrong_counterparty",`${t.registration.allowedCounterparty.toBase58()} != ${t.expectedCounterparty.toBase58()}`);if(t.previousCumulativeAtomic!==void 0){let r=BigInt(t.previousCumulativeAtomic);if(e<=r)throw new N("non_monotonic",`cumulative=${e} not > previous=${r}`)}}function dn(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function ln(t){let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}var vr=require("@solana/web3.js"),Ar=require("@noble/hashes/utils");var ur=on(require("tweetnacl"),1),dr=require("@solana/web3.js"),tt=require("@dexterai/vault/messages"),mr=require("@dexterai/vault/session");var pr=require("@noble/hashes/sha256");var pi=(1n<<64n)-1n;var Bt=require("@noble/hashes/sha256"),ue=require("@noble/hashes/utils"),mn=/^[0-9a-f]{64}$/,pn=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/,gr=/^[1-9A-HJ-NP-Za-km-z]{32,100}$/,gn="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",hn="dexter-native-tab-v2-reservation/v1",hr=`${hn}:`;function Ot(t){if(t===null||typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number"){if(!Number.isFinite(t))throw new Error("canonical_non_finite_number");return t}if(typeof t=="bigint")return t.toString();if(Array.isArray(t))return t.map(Ot);if(typeof t=="object")return Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,Ot(n)]));throw new Error("canonical_value_unsupported")}function fn(t){return JSON.stringify(Ot(t))}function kt(t){if(t==="solana:mainnet"||t===gn)return gn;throw new Error("native_tab_v2_reservation_network_unsupported")}function Ut(t){return(0,ue.bytesToHex)((0,Bt.sha256)(new TextEncoder().encode(fn({channelId:t.payload.channelId,cumulativeAmount:t.payload.cumulativeAmount,sequenceNumber:t.payload.sequenceNumber,sessionPublicKey:(0,ue.bytesToHex)(t.sessionPublicKey),sessionSignature:(0,ue.bytesToHex)(t.sessionSignature),sessionRegistration:(0,ue.bytesToHex)(t.sessionRegistration)}))))}function Kt(t){let e=Ut(t);return{voucherDigest:e,idempotencyKey:`native-tab-v2:${e}`}}function fr(t){return(0,ue.bytesToHex)((0,Bt.sha256)(new TextEncoder().encode(fn({contract:hn,network:kt(t.network),programId:t.programId,buyerSwigAddress:t.buyerSwigAddress,vaultPda:t.vaultPda,sessionPda:t.sessionPda,seller:t.seller,channelId:t.channelId,sessionNonce:t.sessionNonce,reservationAmountAtomic:t.reservationAmountAtomic,previousCumulativeAtomic:t.previousCumulativeAtomic,voucherDigest:t.voucherDigest,cumulativeAmountAtomic:t.cumulativeAmountAtomic,sequenceNumber:t.sequenceNumber}))))}function yr(t){let e=Ut(t.voucher);return fr({network:t.network,programId:t.programId,buyerSwigAddress:t.buyerSwigAddress,vaultPda:t.vaultPda,sessionPda:t.sessionPda,seller:t.seller,channelId:t.channelId,sessionNonce:t.sessionNonce,reservationAmountAtomic:t.reservationAmountAtomic,previousCumulativeAtomic:t.previousCumulativeAtomic,voucherDigest:e,cumulativeAmountAtomic:t.voucher.payload.cumulativeAmount,sequenceNumber:t.voucher.payload.sequenceNumber})}function yn(t){return`${hr}${yr(t)}`}function L(t){throw new Error(`native_tab_v2_reservation_receipt_invalid:${t}`)}function nt(t,e){(!Number.isSafeInteger(t)||t<0)&&L(e)}function $t(t,e){(!e||typeof e!="object")&&L("missing");let n=Ut(t.voucher);(!mn.test(t.voucherDigest)||t.voucherDigest!==n)&&L("input_voucher_digest"),t.idempotencyKey!==`native-tab-v2:${n}`&&L("input_idempotency_identity");let r=BigInt(t.voucher.payload.cumulativeAmount),i=BigInt(t.previousCumulativeAtomic),o=BigInt(t.reservationAmountAtomic);(r<=i||r-i!==o||o<=0n)&&L("input_reservation_delta"),(t.voucher.payload.channelId!==t.channelId||(t.voucher.payload.sequenceNumber&2147483648)===0||(t.sessionNonce&2147483648)===0||t.voucher.sessionPublicKey.length!==32||t.voucher.sessionSignature.length!==64||t.voucher.sessionRegistration.length!==188)&&L("input_voucher_identity"),e.contract!=="dexter-native-tab-open-receipt/v1"&&e.contract!=="dexter-native-tab-open-receipt/v2"&&L("contract"),mn.test(e.operationId)||L("operation_id"),pn.test(e.callerOperationId)||L("caller_operation_id"),gr.test(e.transaction)||L("transaction"),e.commitment!=="confirmed"&&e.commitment!=="finalized"&&L("commitment"),nt(e.confirmationSlot,"confirmation_slot"),nt(e.postStateSlot,"post_state_slot"),(e.confirmationSlot===0||e.postStateSlot<e.confirmationSlot)&&L("post_state_slot");let s,c;try{s=kt(t.network),c=kt(e.network)}catch{return L("network")}(c!==s||e.buyerSwigAddress!==t.buyerSwigAddress||e.vaultPda!==t.vaultPda||e.sessionPda!==t.sessionPda||e.seller!==t.seller||e.channelId!==t.channelId||e.sessionPublicKey!==(0,ue.bytesToHex)(t.voucher.sessionPublicKey)||e.voucherDigest!==n||e.cumulativeAmountAtomic!==t.voucher.payload.cumulativeAmount||e.sequenceNumber!==t.voucher.payload.sequenceNumber||!pn.test(e.providerReceiptId)||e.reservationAmountAtomic!==t.reservationAmountAtomic||e.currentOutstandingBeforeAtomic!=="0"||e.currentOutstandingAfterAtomic!==t.reservationAmountAtomic)&&L("economic_identity"),nt(e.pendingVoucherCountBefore,"pending_voucher_count_before"),nt(e.pendingVoucherCountAfter,"pending_voucher_count_after"),e.contract==="dexter-native-tab-open-receipt/v1"?e.callerOperationId!==t.idempotencyKey&&L("idempotency_key"):(e.rootOperationId!==t.idempotencyKey||!Number.isSafeInteger(e.generation)||Number(e.generation)<2||!e.predecessorCallerOperationId||!e.predecessorLifecycleOperationId||!e.predecessorReleaseDigest||!e.stableReservationId||!e.economicEffectDigest)&&L("successor_identity")}var br=require("@dexterai/vault/session");var vn="https://x402.dexter.cash",An=6;function G(t,e=An){if(!/^\d+(\.\d+)?$/.test(t))throw new Error(`amount must be a non-negative decimal string, got "${t}"`);let[n,r=""]=t.split(".");if(r.length>e)throw new Error(`amount "${t}" has more than ${e} decimals`);let i=r.padEnd(e,"0"),o=`${n}${i}`.replace(/^0+(?=\d)/,"");return o===""?"0":o}function de(t,e=An){if(!/^\d+$/.test(t))throw new Error(`atomic must be a non-negative integer string, got "${t}"`);let n=t.padStart(e+1,"0"),r=n.slice(0,-e).replace(/^0+(?=\d)/,"")||"0",i=n.slice(-e).replace(/0+$/,"");return i?`${r}.${i}`:r}var Q=require("@solana/web3.js"),it=require("@noble/hashes/utils"),we=require("@dexterai/vault/credit"),me=require("@dexterai/vault/constants"),bn=require("@dexterai/vault/instructions"),wn=require("@dexterai/vault/reader"),Se=require("@dexterai/vault/session");var wr=Uint8Array.from([56,67,4,209,238,143,0,129]),Sr=74,_r=188,Cr=new Q.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),xr=(()=>{let t=Buffer.alloc(32);return t.write("OTS_SESSION_REGISTER_V2","ascii"),t})(),Ie=class extends Error{constructor(n,r){super(`native_tab_v2_solana_reservation_invalid:${n}`+(r?`:${r}`:""));this.code=n;this.name="SolanaFinalVoucherV2ReservationError"}code};function m(t,e){throw new Ie(t,e)}function F(t,e){try{return new Q.PublicKey(t)}catch{return m(e)}}function rt(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}async function Rr(t){let n=(await t.connection.getSignatureStatuses([t.signature],{searchTransactionHistory:!0})).value[0]??null;if(!n)return null;n.confirmationStatus!=="confirmed"&&n.confirmationStatus!=="finalized"&&m("transaction_commitment"),n.err!==null&&m("transaction_failed");let r=await t.connection.getTransaction(t.signature,{commitment:t.commitment,maxSupportedTransactionVersion:0});if(!r)return null;r.meta||m("transaction_meta_missing"),r.slot!==n.slot&&m("transaction_status_slot");let i=r.transaction.message,o=i.version===0?i.getAccountKeys({accountKeysFromLookups:r.meta.loadedAddresses??null}):i.getAccountKeys(),s=(c,l)=>{let p=o.get(c);return p||m(l),p};return{slot:r.slot,confirmationStatus:n.confirmationStatus,err:r.meta.err,signatures:[...r.transaction.signatures],accountKeys:Array.from({length:o.length},(c,l)=>({address:s(l,"transaction_account_key").toBase58(),signer:i.isAccountSigner(l),writable:i.isAccountWritable(l)})),instructions:i.compiledInstructions.map(c=>({programId:s(c.programIdIndex,"transaction_program_id").toBase58(),accounts:c.accountKeyIndexes.map(l=>s(l,"transaction_instruction_account").toBase58()),data:Uint8Array.from(c.data)}))}}function Er(t,e,n,r){r.length!==Sr&&m("binding_length"),rt(r.subarray(0,8),wr)||m("binding_discriminator");let i=r.readUInt8(8),o=r.readUInt8(9);return(0,me.isSwigVaultBindingIdentityVersion)(i)||m("binding_version"),o!==e&&m("binding_bump"),{address:t.toBase58(),owner:n.toBase58(),version:i,bump:o,swig:new Q.PublicKey(r.subarray(10,42)).toBase58(),vault:new Q.PublicKey(r.subarray(42,74)).toBase58()}}async function Pr(t){let e=F(t.input.programId,"program_id"),n=F(t.input.buyerSwigAddress,"buyer_swig"),r=F(t.input.vaultPda,"vault_pda"),i=F(t.input.seller,"seller"),[o,s]=(0,we.deriveSwigVaultBindingPda)(n,e),[c]=(0,Se.deriveSessionPda)(r,i,e),l=await t.connection.getMultipleAccountsInfoAndContext([o,r,c],{commitment:t.commitment,minContextSlot:t.minimumSlot}),[p,y,v]=l.value;p||m("binding_missing"),y||m("vault_missing"),v||m("session_missing");let h,f;try{h=(0,wn.decodeVaultFull)(Buffer.from(y.data)),f=(0,Se.decodeSessionAccount)(c,v.data)}catch(S){return m("post_state_decode",S instanceof Error?S.message:String(S))}let g=f.session;return{contextSlot:l.context.slot,binding:Er(o,s,p.owner,Buffer.from(p.data)),vault:{owner:y.owner.toBase58(),exists:h.exists,version:h.version,swigAddress:h.swigAddress,dexterAuthority:h.dexterAuthority,pendingVoucherCount:h.pendingVoucherCount},session:{owner:v.owner.toBase58(),version:f.version,bump:f.bump,vault:f.vault,sessionPublicKey:(0,it.bytesToHex)(g.sessionPubkey),maxAmount:g.maxAmount,expiresAt:g.expiresAt,seller:g.allowedCounterparty,nonce:g.nonce,spent:g.spent,currentOutstanding:g.currentOutstanding,maxRevolvingCapacity:g.maxRevolvingCapacity,crystallizedCumulative:g.crystallizedCumulative}}}function Vr(t){let e=Buffer.from(t.voucher.sessionRegistration);return e.length!==_r&&m("registration_length"),rt(e.subarray(0,32),xr)||m("registration_domain"),{programId:new Q.PublicKey(e.subarray(32,64)).toBase58(),vaultPda:new Q.PublicKey(e.subarray(64,96)).toBase58(),sessionPublicKey:(0,it.bytesToHex)(e.subarray(96,128)),maxAmount:e.readBigUInt64LE(128),expiresAt:e.readBigInt64LE(136),seller:new Q.PublicKey(e.subarray(144,176)).toBase58(),nonce:e.readUInt32LE(176),maxRevolvingCapacity:e.readBigUInt64LE(180)}}function be(t,e,n){let r=t.accountKeys.filter(i=>i.address===e);return r.length!==1&&m(`${n}_account_key`),r[0]}function Tr(t,e,n){(!Number.isSafeInteger(n.slot)||n.slot<=0)&&m("transaction_slot"),n.slot!==e.confirmationSlot&&m("transaction_confirmation_slot"),n.err!==null&&m("transaction_failed"),n.signatures[0]!==e.transaction&&m("transaction_signature"),n.instructions.length!==2&&m("transaction_instruction_count");let r=F(t.programId,"program_id"),i=F(t.buyerSwigAddress,"buyer_swig"),o=F(t.vaultPda,"vault_pda"),s=F(t.seller,"seller"),c=F(t.sessionPda,"session_pda"),[l]=(0,Se.deriveSessionPda)(o,s,r),p=(0,we.deriveSwigVaultBindingPda)(i,r)[0],y=(0,bn.deriveSwigWalletAddress)(i),v=(0,we.deriveGraphConfigPda)(r)[0];c.equals(l)||m("session_pda_derivation");let h=Buffer.from(me.DISCRIMINATORS.settle_voucher),f=n.instructions.filter(a=>{if(a.programId!==t.programId)return!1;let x=a.data;return x.length>=h.length&&rt(x.subarray(0,h.length),h)});f.length!==1&&m("settle_voucher_instruction_count");let g=f[0];n.instructions[0]!==g&&m("settle_voucher_instruction_order");let S=Buffer.from(g.data);S.length!==49&&m("settle_voucher_instruction_length"),S.readBigUInt64LE(8).toString()!==t.reservationAmountAtomic&&m("settle_voucher_amount"),S.readUInt8(16)!==1&&m("settle_voucher_increment"),new Q.PublicKey(S.subarray(17,49)).equals(s)||m("settle_voucher_seller"),g.accounts.length<8&&m("settle_voucher_accounts"),[o.toBase58(),null,c.toBase58(),null,i.toBase58(),y.toBase58(),p.toBase58(),v.toBase58()].forEach((a,x)=>{a!==null&&g.accounts[x]!==a&&m(`settle_voucher_account_${x}`)});let I=g.accounts[1];I||m("dexter_authority");let j=be(n,g.accounts[0],"vault"),te=be(n,I,"dexter_authority"),oe=be(n,g.accounts[2],"session");(!j.writable||j.signer)&&m("vault_privileges"),te.signer||m("dexter_authority_signature"),(!oe.writable||oe.signer)&&m("session_privileges");for(let a=3;a<Math.min(g.accounts.length,8);a+=1)be(n,g.accounts[a],`account_${a}`).signer&&m(`settle_voucher_account_${a}_signer`);for(let a=8;a<g.accounts.length;a+=1){let x=be(n,g.accounts[a],`sibling_${a-8}`);(!x.writable||x.signer)&&m("settle_voucher_sibling_privileges")}let q=n.instructions[1];q.programId!==Cr.toBase58()&&m("reservation_memo_program"),(q.accounts.length!==1||q.accounts[0]!==I)&&m("reservation_memo_authority"),be(n,I,"reservation_memo_authority").signer||m("reservation_memo_authority_signature");let d=new TextEncoder().encode(yn(t));return rt(q.data,d)||m("reservation_memo_digest"),I}function Ir(t,e,n,r){let i=F(t.programId,"program_id"),o=F(t.buyerSwigAddress,"buyer_swig"),s=F(t.vaultPda,"vault_pda"),c=F(t.seller,"seller"),[l,p]=(0,we.deriveSwigVaultBindingPda)(o,i),[y,v]=(0,Se.deriveSessionPda)(s,c,i);(!Number.isSafeInteger(r.contextSlot)||r.contextSlot<e)&&m("post_state_slot"),(r.binding.address!==l.toBase58()||r.binding.owner!==t.programId||r.binding.bump!==p||!(0,me.isSwigVaultBindingIdentityVersion)(r.binding.version)||r.binding.swig!==t.buyerSwigAddress||r.binding.vault!==t.vaultPda)&&m("binding_identity"),(r.vault.owner!==t.programId||!r.vault.exists||r.vault.version!==7||r.vault.swigAddress!==t.buyerSwigAddress||r.vault.dexterAuthority!==n)&&m("vault_post_state"),(t.sessionPda!==y.toBase58()||r.session.owner!==t.programId||r.session.version!==1||r.session.bump!==v||r.session.vault!==t.vaultPda||r.session.sessionPublicKey!==(0,it.bytesToHex)(t.voucher.sessionPublicKey)||r.session.seller!==t.seller||r.session.nonce!==t.sessionNonce||r.session.currentOutstanding.toString()!==t.reservationAmountAtomic)&&m("session_post_state");let h=Vr(t);(h.programId!==t.programId||h.vaultPda!==t.vaultPda||h.sessionPublicKey!==r.session.sessionPublicKey||h.seller!==t.seller||h.nonce!==t.sessionNonce||h.maxAmount!==r.session.maxAmount||h.expiresAt!==BigInt(r.session.expiresAt)||h.maxRevolvingCapacity!==r.session.maxRevolvingCapacity)&&m("registration_post_state");let f=r.session.spent>r.session.crystallizedCumulative?r.session.spent:r.session.crystallizedCumulative;return f.toString()!==t.previousCumulativeAtomic&&m("session_frontier"),{commitment:"confirmed",confirmationSlot:e,postStateSlot:r.contextSlot,sessionAccountVersion:r.session.version,wireVersion:2,frontierAtomic:f.toString(),spentAtomic:r.session.spent.toString(),currentOutstandingAtomic:r.session.currentOutstanding.toString(),crystallizedCumulativeAtomic:r.session.crystallizedCumulative.toString()}}async function Sn(t,e,n,r={}){try{$t(e,n)}catch(c){return m("provider_receipt",c instanceof Error?c.message:String(c))}e.network!=="solana:mainnet"&&m("network"),e.programId!==me.DEXTER_VAULT_PROGRAM_ID.toBase58()&&m("program_id");let i=await(r.readTransaction??Rr)({connection:t,signature:n.transaction,commitment:"confirmed"});i||m("transaction_missing"),i.confirmationStatus!=="confirmed"&&i.confirmationStatus!=="finalized"&&m("transaction_commitment");let o=Tr(e,n,i),s=await(r.readPostState??Pr)({connection:t,input:e,minimumSlot:i.slot,commitment:"confirmed"});return{...Ir(e,i.slot,o,s),commitment:i.confirmationStatus}}var Rn=require("@dexterai/vault/session");var ot=require("@noble/hashes/utils"),Nr=15e3,Lr=["claim_already_exists","non_monotonic_cumulative"],Or="below_lock_cadence";function st(t){return typeof t=="string"&&t.includes(Or)}function kr(t){return`${t.slice(0,16)}\u2026`}function _n(t,e,n,r){let i=kr(t);if(r.crystallized){console.info(`[tab/seller] crystallize OK channel=${i} cumulative=${e} seq=${n}${r.claimPda?` claimPda=${r.claimPda}`:""} \u2014 LockVoucher landed`);return}if(r.error){if(st(r.error)){console.warn(`[tab/seller] crystallize refused below the facilitator's cadence gate channel=${i} cumulative=${e} seq=${n}: ${r.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(Lr.some(o=>r.error.includes(o))){console.warn(`[tab/seller] crystallize duplicate channel=${i} cumulative=${e} seq=${n}: ${r.error} \u2014 voucher already secured on-chain (benign, no action)`);return}console.error(`[tab/seller] crystallize FAILED channel=${i} cumulative=${e} seq=${n}: ${r.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 Mt(t,e,n,r,i=fetch){let o=t.lastVoucher;if(!o)return{crystallized:!1};if(o.payload.channelId!==e){let c={crystallized:!1,error:"channel_id_mismatch"};return _n(e,o.payload.cumulativeAmount,o.payload.sequenceNumber,c),c}let s=c=>(_n(e,o.payload.cumulativeAmount,o.payload.sequenceNumber,c),c);try{let c=`${n.replace(/\/$/,"")}/tab/lock`,l={channelId:o.payload.channelId,cumulativeAmount:o.payload.cumulativeAmount,sequenceNumber:o.payload.sequenceNumber,sessionPublicKey:(0,ot.bytesToHex)(o.sessionPublicKey),sessionSignature:(0,ot.bytesToHex)(o.sessionSignature),sessionRegistration:(0,ot.bytesToHex)(o.sessionRegistration),network:r},p=await i(c,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(Nr)}),y=await p.text();if(!p.ok)return s({crystallized:!1,error:`tab lock ${p.status}: ${y.slice(0,200)}`});let v;try{let h=JSON.parse(y);h&&typeof h.claimPda=="string"&&(v=h.claimPda)}catch{}return s({crystallized:!0,claimPda:v})}catch(c){return s({crystallized:!1,error:String(c?.message??c)})}}async function Cn(t,e,n,r,i,o={}){let s=BigInt(t.deliveredCumulativeAtomic),c=BigInt(t.lastCrystallizedCumulativeAtomic??"0"),l=BigInt(i.thresholdAtomic);if(s-c<l)return{crystallized:!1};let p=t.lastVoucher?.payload.cumulativeAmount,y=t.gateRefusedCumulativeAtomic;if(p!==void 0&&y!==void 0&&BigInt(p)<=BigInt(y))return{crystallized:!1};let v=await Mt(t,e,n,r,o.fetchImpl);return v.crystallized&&p!==void 0?(t.lastCrystallizedCumulativeAtomic=p,t.gateRefusedCumulativeAtomic=void 0):st(v.error)&&p!==void 0&&(t.gateRefusedCumulativeAtomic=p),v}var ie="x-tab-voucher",lt=class extends Error{constructor(){super("response terminated before tab admission completed"),this.name="ResponseTerminatedError"}};function Br(t){if(t!==void 0)return t;if(process.env.NODE_ENV==="test"||process.env.NODE_ENV==="development")return"development";throw new Error("tab seller ledgerSafetyMode must be explicit outside NODE_ENV=test/development; choose production-single-instance or production-multi-instance for deployment")}function Ur(t,e){if(!["development","production-single-instance","production-multi-instance"].includes(e))throw new Error(`invalid tab seller ledgerSafetyMode: ${String(e)}`);let n=t.capabilities;if(!n||n.conditionalWrites!==!0)throw new Error("tab seller ledger must declare conditional owner-token/fence writes");if(e!=="development"&&!n.restartSafe)throw new Error(`tab seller ${e} requires restart-safe durable ledger state; ${n.adapter} is not restart-safe`);if(e!=="development"&&!n.canonicalChannelIds)throw new Error(`tab seller ${e} requires the legacy channel-id alias migration or an empty-store proof; ${n.adapter} has no canonical channel-id cutover acknowledgement`);if(e==="production-multi-instance"&&!n.multiInstanceSafe)throw new Error(`tab seller production-multi-instance requires cross-process atomic fencing; ${n.adapter} is single-instance only`)}var Dt=class{map=new Map;get(e){return this.map.get(e)}set(e,n){this.map.set(e,n)}deleteIfSame(e,n){this.map.get(e)===n&&this.map.delete(e)}update(e,n){let r=this.map.get(e);r&&(r.lastCumulativeAtomic=n)}delete(e){this.map.delete(e)}},Ft=class{constructor(e,n,r,i,o,s){this.recordDeliveredImpl=o;this.chargeImpl=s;this.channelId=e,this.network=n,this.cumulativeAtomic=r,this.deliveredBaselineAtomic=i}recordDeliveredImpl;chargeImpl;channelId;network;sessionPublicKey=null;cumulativeAtomic;deliveredBaselineAtomic;cumulative(){return de(this.cumulativeAtomic.toString())}deliveredCumulative(){return de(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 Kr(t){if(typeof t!="string"||t.length===0)throw new w("signature_invalid",`missing ${ie} header`);let e;try{e=Buffer.from(t,"base64").toString("utf8")}catch{throw new w("signature_invalid","malformed base64")}let n;try{n=JSON.parse(e)}catch{throw new w("signature_invalid","malformed JSON")}if(!n||typeof n!="object"||!n.payload||!n.sessionPublicKey)throw new w("signature_invalid","missing required fields");return{voucher:{payload:n.payload,sessionPublicKey:ct(n.sessionPublicKey),sessionRegistration:ct(n.sessionRegistration),sessionSignature:ct(n.sessionSignature)},reservationReceipt:n.reservationReceipt}}function ct(t){if(typeof t!="string"||t.length%2!==0)throw new w("signature_invalid",`bad hex: ${typeof t}`);let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.substr(n*2,2),16);return e}function $r(t){if(!/^[0-9a-f]{64}$/.test(t))throw new w("signature_invalid",`channelId must be canonical lowercase 64-char hex, got "${t}"`);return ct(t)}function ut(t){let e=t.ledger??new ve,n=Br(t.ledgerSafetyMode);Ur(e,n);let r=Z(t.leaseTtlMs??3e5),i=new Dt,o=typeof t.sellerPubkey=="string"?new xn.PublicKey(t.sellerPubkey):t.sellerPubkey,s=t.maxPerVoucherAtomic?BigInt(t.maxPerVoucherAtomic):BigInt(G(t.perUnit))*100n,c=t.facilitatorUrl??vn,l={thresholdAtomic:t.lockCadence?.thresholdAtomic??G("0.10"),onClose:t.lockCadence?.onClose??!0};return async(p,y,v)=>{let h=null,f=null,g=null,S=null,P=null,I=!1,j=async()=>{if(P)throw P},te=async()=>{if(!f||f.releaseStarted)return;let _=f;_.releaseStarted=!0,g&&(clearInterval(g),g=null),S&&await S.catch(()=>{});try{await e.releaseLease(_.channelId,f?.lease??_.lease)}catch(d){throw _.releaseStarted=!1,d}},oe=()=>{I||(I=!0,setImmediate(()=>{te().catch(_=>{console.error("[tab/seller] failed to release channel lease on response termination:",_)})}))},q=()=>{if(I)throw new lt};y.on("close",oe),y.on("finish",oe);try{let _=Kr(p.headers[ie]),d=_.voucher,a=d.payload.channelId,x=$r(a),A=i.get(a),O=null,$,xt=!1;if(A){if(!pe(A.registrationBytes,d.sessionRegistration))throw new T("voucher registration does not match the channel's verified registration")}else{xt=!0;let u=Ve(d.sessionRegistration);re(u.nonce)===1&&($=await Qe(t.connection,u),O=$?.frontierAtomic??null);let C=await e.get(a);A={registration:u,registrationBytes:d.sessionRegistration.slice(),lastCumulativeAtomic:C?.lastVoucher?.payload.cumulativeAmount??"0"}}let z=re(A.registration.nonce),Ht=re(d.payload.sequenceNumber);if(Ht!==z)throw new w("wire_version_mismatch",`voucher is V${Ht}, active registration is V${z}`);let Ce;if(z===2){if(_.reservationReceipt===void 0)throw new w("reservation_proof_missing","Native Tab V2 requires the verified reservation receipt in the voucher envelope");if(_.reservationReceipt===null||typeof _.reservationReceipt!="object"||Array.isArray(_.reservationReceipt))throw new w("reservation_proof_invalid","reservationReceipt must be an object");Ce=_.reservationReceipt}et(d,x);let k=BigInt(d.payload.cumulativeAmount),X=BigInt(A.lastCumulativeAtomic),xe=null,J=null,Rt=null;if(z===2){if(!Ce)throw new w("reservation_proof_missing","Native Tab V2 reservation proof was not carried through admission");if(J=at(Ce.reservationAmountAtomic,"receipt.reservationAmountAtomic"),J<=0n||J>k)throw new w("reservation_mismatch","reservation amount does not fit the voucher cumulative");let u=k-J,[C]=(0,Rn.deriveSessionPda)(A.registration.vaultPda,A.registration.allowedCounterparty,A.registration.programId),R=Kt(d);try{let U=await Sn(t.connection,{network:t.network,programId:A.registration.programId.toBase58(),buyerSwigAddress:Ce.buyerSwigAddress,vaultPda:A.registration.vaultPda.toBase58(),sessionPda:C.toBase58(),seller:A.registration.allowedCounterparty.toBase58(),channelId:a,sessionNonce:A.registration.nonce,reservationAmountAtomic:J.toString(),previousCumulativeAtomic:u.toString(),...R,voucher:d},Ce);$=U,O=U.frontierAtomic}catch(U){throw U instanceof Ie?new w("reservation_proof_invalid",U.message):U}if($?.wireVersion!==2)throw new w("wire_version_mismatch",`active SessionAccount is V${$?.wireVersion??"unknown"}, voucher is V2`);if($.sessionAccountVersion!==1||O===null||$.currentOutstandingAtomic===void 0)throw new w("reservation_mismatch","authoritative V2 SessionAccount reservation evidence is incomplete");let b=at(O,"frontierAtomic");if(b>X&&(X=b),k<=X)throw new w("voucher_already_covered",`cumulative ${k} is not above covered frontier ${X}`);xe=k-X;let B=at($.currentOutstandingAtomic,"currentOutstandingAtomic");if(Rt=B,B!==xe)throw new w("reservation_mismatch",`currentOutstanding ${B} does not equal voucher delta ${xe}`);if(J!==xe)throw new w("reservation_mismatch",`receipt reservation ${J} does not equal voucher delta ${xe}`)}let zn=z===1&&k===X;Te({registration:A.registration,voucher:d,expectedCounterparty:o,previousCumulativeAtomic:zn?void 0:X.toString()});let se=k-X;if(se>s)throw new N("cumulative_exceeds_cap",`single voucher increment ${se} exceeds maxPerVoucherAtomic ${s}`);if(xt){let u=i.get(a);if(u){if(!pe(u.registrationBytes,A.registrationBytes))throw new T("voucher registration lost the channel admission race to a different verified registration");if(BigInt(u.lastCumulativeAtomic)>BigInt(A.lastCumulativeAtomic))throw new N("non_monotonic","channel admission advanced while reservation proof was in flight");A=u}}q();let Re=await e.tryAcquireLease(a,r);if(!Re)throw new w("channel_busy","another stream is live on this channel; tabs serve one stream at a time");f={channelId:a,lease:Re,releaseStarted:!1},q();let Wt=Math.max(1,Math.floor(r/3)),Gt=async()=>{if(P)throw P;if(!f||f.releaseStarted)throw new M(a);return S||(S=(async()=>{let u=await e.renewLease(a,f.lease,r);f&&!f.releaseStarted&&(f.lease=u)})().catch(u=>{let C=u instanceof Error?u:new Error(String(u));throw P=C,console.error(`[tab/seller] channel lease renewal FAILED channel=${a.slice(0,16)}\u2026; stream terminated before further delivery:`,C),typeof y.destroy=="function"&&y.destroy(C),C}).finally(()=>{S=null}),S)};j=async()=>{if(P)throw P;if(!f||f.releaseStarted)throw new M(a);f.lease.heldUntilUnixMs-Date.now()<=Wt&&await Gt()},g=setInterval(()=>{Gt().catch(()=>{})},Wt),g.unref?.();let Ee=await e.get(a);if(q(),Ee?.lastVoucher&&!pe(Ee.lastVoucher.sessionRegistration,d.sessionRegistration))throw new T("durable channel registration changed while reservation proof was in flight");let jt=BigInt(Ee?.lastVoucher?.payload.cumulativeAmount??"0"),H=BigInt(A.lastCumulativeAtomic);if(jt>H&&(H=jt),z===2&&O!==null){let u=at(O,"frontierAtomic");u>H&&(H=u)}let Xt=z===1&&k===H;if(k<H||z===2&&k===H)throw new w(z===2?"voucher_already_covered":"non_monotonic",`cumulative ${k} is not above post-lease covered frontier ${H}`);if(Xt){let u=Ee?.lastVoucher;if(!u||BigInt(u.payload.cumulativeAmount)!==k||d.payload.sequenceNumber<=u.payload.sequenceNumber)throw new w("non_monotonic","same-cumulative V1 reconnect requires a strictly newer sequence than the durable voucher")}if(Te({registration:A.registration,voucher:d,expectedCounterparty:o,previousCumulativeAtomic:Xt?void 0:H.toString()}),se=k-H,se>s)throw new N("cumulative_exceeds_cap",`post-lease voucher increment ${se} exceeds maxPerVoucherAtomic ${s}`);if(z===2&&(J===null||Rt===null||J!==se||Rt!==se))throw new w("reservation_mismatch","durable channel frontier advanced while reservation proof was in flight");if(X=H,xt){let u=i.get(a);if(u){if(!pe(u.registrationBytes,A.registrationBytes))throw await te(),new T("voucher registration lost the channel lease race to a different verified registration");A=u}else i.set(a,A),h={channelId:a,entry:A}}let Et=async u=>{try{return await e.update(a,Re,u)}catch(C){if(!(C instanceof M))throw C;let R=await e.tryAcquireLease(a,Math.min(r,15e3));if(!R)throw C;try{return await e.update(a,R,u)}finally{await e.releaseLease(a,R)}}},Hn=async u=>{let C=u.lastCrystallizedCumulativeAtomic??"0",R=u.gateRefusedCumulativeAtomic;await Cn(u,a,c,t.network,l),(u.lastCrystallizedCumulativeAtomic!==C||u.gateRefusedCumulativeAtomic!==R)&&await Et(b=>{if(!b)throw new Error("channel ledger entry missing during crystallize persist");let B=BigInt(b.lastCrystallizedCumulativeAtomic??"0")>=BigInt(u.lastCrystallizedCumulativeAtomic??"0")?b.lastCrystallizedCumulativeAtomic??"0":u.lastCrystallizedCumulativeAtomic??"0",he=[b.gateRefusedCumulativeAtomic,u.gateRefusedCumulativeAtomic].filter(fe=>fe!==void 0).reduce((fe,nn)=>fe===void 0||BigInt(nn)>BigInt(fe)?nn:fe,void 0);return{...b,lastCrystallizedCumulativeAtomic:B,gateRefusedCumulativeAtomic:he!==void 0&&BigInt(he)>BigInt(B)?he:void 0}}).catch(b=>{console.error(`[tab/seller] crystallize watermark persist FAILED channel=${a.slice(0,16)}\u2026 (expect a benign duplicate/below-cadence warn on the next request):`,b)})},Jt=Promise.resolve(),Yt=u=>{let C=Jt.then(u,u);return Jt=C.catch(()=>{}),C},Zt=!1,Qt=()=>{!l.onClose||Zt||(Zt=!0,Yt(async()=>{let u=await e.get(a);if(!u||!u.lastVoucher)return;let C=u.lastVoucher.payload.cumulativeAmount;if(u.gateRefusedCumulativeAtomic!==void 0&&BigInt(C)<=BigInt(u.gateRefusedCumulativeAtomic))return;let R=await Mt(u,a,c,t.network);R.crystallized?await Et(b=>{if(!b)throw new Error("channel ledger entry missing during close crystallize");let B=BigInt(b.lastCrystallizedCumulativeAtomic??"0")>=BigInt(C)?b.lastCrystallizedCumulativeAtomic??"0":C;return{...b,lastCrystallizedCumulativeAtomic:B,gateRefusedCumulativeAtomic:b.gateRefusedCumulativeAtomic!==void 0&&BigInt(b.gateRefusedCumulativeAtomic)>BigInt(B)?b.gateRefusedCumulativeAtomic:void 0}}):st(R.error)&&await Et(b=>{if(!b)throw new Error("channel ledger entry missing during close refusal persist");let B=BigInt(b.lastCrystallizedCumulativeAtomic??"0"),U=b.gateRefusedCumulativeAtomic!==void 0&&BigInt(b.gateRefusedCumulativeAtomic)>=BigInt(C)?b.gateRefusedCumulativeAtomic:C;return{...b,gateRefusedCumulativeAtomic:BigInt(U)>B?U:void 0}})}).catch(u=>{console.error(`[tab/seller] close-path crystallize CRASHED channel=${a.slice(0,16)}\u2026 (final voucher NOT locked; exposure unsecured until the next request retries):`,u)}))};y.on("close",Qt),y.on("finish",Qt);let Fe=Ee,en=BigInt(Fe?.deliveredCumulativeAtomic??"0"),Wn=!Fe?.lastVoucher&&en===0n,Pt=O===null?null:BigInt(O),ge=Pt!==null&&Pt>en&&(z===2||Wn)?Pt.toString():null;ge!==null&&console.info(`[tab/seller] channel ${a.slice(0,16)}\u2026 resumed: seeding delivered baseline from chain frontier ${ge} (session already settled/locked up to it \u2014 that span is not deliverable budget)`);let Gn=ge!==null?BigInt(ge):Fe?BigInt(Fe.deliveredCumulativeAtomic):0n;await e.update(a,Re,u=>({...u??{},lastVoucher:d,deliveredCumulativeAtomic:ge??(u?u.deliveredCumulativeAtomic:"0"),lastCrystallizedCumulativeAtomic:ge??u?.lastCrystallizedCumulativeAtomic??"0"})),h=null,q(),i.update(a,d.payload.cumulativeAmount);let tn=new Ft(a,t.network,k,Gn,async u=>{await j();let C=null;C=await e.update(a,Re,R=>{if(!R?.lastVoucher||!Mr(R.lastVoucher,d))throw new T("durable voucher identity changed before delivery accounting");let b=BigInt(R.deliveredCumulativeAtomic),B=BigInt(u),U=B>0n?b+B:b,he=BigInt(R.lastVoucher.payload.cumulativeAmount);if(U>he)throw new N("cumulative_exceeds_cap",`durable delivered cumulative ${U} exceeds signed cumulative ${he}`);return{...R,lastVoucher:R.lastVoucher,deliveredCumulativeAtomic:U.toString(),lastCrystallizedCumulativeAtomic:R.lastCrystallizedCumulativeAtomic??"0"}}),C&&Yt(async()=>{let R=await e.get(a);R&&await Hn(R)}).catch(R=>{console.error(`[tab/seller] crystallize cadence CRASHED channel=${a.slice(0,16)}\u2026 (threshold lock not attempted; retries at the next delivery):`,R)})},async u=>{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.")});tn.setSessionPublicKey(d.sessionPublicKey),p.tab=tn,v()}catch(_){if(f&&!f.releaseStarted&&await te().catch(d=>{console.error("[tab/seller] failed to release channel lease after request error:",d)}),h&&i.deleteIfSame(h.channelId,h.entry),_ instanceof lt)return;if(_ instanceof w||_ instanceof W||_ instanceof K||_ instanceof T||_ instanceof N){y.status(402).json({error:"invalid_voucher",reason:_.reason??"unknown",detail:_.message});return}v(_)}}}function pe(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r+=1)n|=t[r]^e[r];return n===0}function Mr(t,e){return t.payload.channelId===e.payload.channelId&&t.payload.cumulativeAmount===e.payload.cumulativeAmount&&t.payload.sequenceNumber===e.payload.sequenceNumber&&pe(t.sessionPublicKey,e.sessionPublicKey)&&pe(t.sessionRegistration,e.sessionRegistration)&&pe(t.sessionSignature,e.sessionSignature)}function at(t,e){if(!/^(0|[1-9][0-9]*)$/.test(t))throw new w("reservation_mismatch",`authoritative ${e} is not a canonical atomic amount`);return BigInt(t)}function En(t){if(!t.tab)throw new Error("req.tab is missing \u2014 did tabMiddleware run on this route?");return t.tab}function Pn(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 n=e.tab,r=BigInt(G(n.cumulative())),i=BigInt(G(n.deliveredCumulative())),o=r-i;o<0n&&(o=0n);let s=e.perUnit?BigInt(G(e.perUnit)):null,c=0n,l=!1,p=0,y=Promise.resolve();t.prependListener("close",()=>{l||(l=!0)});function v(g=1){if(l)return Promise.reject(new Error("meter ended"));if(s===null)return Promise.reject(new Error("charge() needs options.perUnit"));if(!Number.isSafeInteger(g)||g<=0)return Promise.reject(new Error("charge() units must be a positive safe integer"));let S=s*BigInt(g);p+=1;let P=y.then(async()=>{if(l)throw new Error("meter ended");let I=c+S;if(I>o)throw l=!0,new N("cumulative_exceeds_cap",`chunk would push delivered to ${de((i+I).toString())} beyond signed cumulative ${de(r.toString())} (per-request budget ${de(o.toString())})`);try{await n.recordDelivered(S.toString()),c=I}catch(j){throw l=!0,j}});return y=P.catch(()=>{}),P.finally(()=>{p-=1})}function h(g){if(l)throw new Error("meter ended");if(p>0)throw new Error("charge still pending; await meter.charge() before send()");let P=(typeof g=="string"?g:Buffer.from(g).toString("utf8")).replace(/\\/g,"\\\\").replace(/\n/g,"\\n");t.write(`data: ${P}
23
23
 
24
24
  `)}async function f(){l||(l=!0,t.write(`event: end
25
25
  data: {"chargedAtomic":"${c}"}
26
26
 
27
- `),t.end())}return{charge:v,send:h,end:f}}var Se=require("fs"),pt=require("path");function Fr(t){return{payload:t.payload,sessionPublicKey:qt(t.sessionPublicKey),sessionRegistration:qt(t.sessionRegistration),sessionSignature:qt(t.sessionSignature)}}function qr(t){return{payload:t.payload,sessionPublicKey:zt(t.sessionPublicKey),sessionRegistration:zt(t.sessionRegistration),sessionSignature:zt(t.sessionSignature)}}function qt(t){let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}function zt(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 n=0;n<e.length;n++)e[n]=parseInt(t.substr(n*2,2),16);return e}var dt=class{map=new Map;async get(e){return this.map.get(e)??null}async set(e,n){this.map.set(e,n)}async delete(e){this.map.delete(e)}},mt=class{constructor(e){this.dir=e}dir;pathFor(e){if(!/^[a-z0-9_-]+$/i.test(e))throw new Error(`unsafe channelId for filesystem: ${e}`);return(0,pt.join)(this.dir,`${e}.json`)}async get(e){try{let n=await Se.promises.readFile(this.pathFor(e),"utf8");return qr(JSON.parse(n))}catch(n){if(n?.code==="ENOENT")return null;throw n}}async set(e,n){let r=this.pathFor(e);await Se.promises.mkdir((0,pt.dirname)(r),{recursive:!0});let i=`${r}.tmp`;await Se.promises.writeFile(i,JSON.stringify(Fr(n))),await Se.promises.rename(i,r)}async delete(e){try{await Se.promises.unlink(this.pathFor(e))}catch(n){if(n?.code!=="ENOENT")throw n}}};var Dn=require("@solana/web3.js");var ee="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Tn="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",In="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";var Ie="eip155:8453",gt="eip155:84532",ht="eip155:42161",ft="eip155:137",yt="eip155:10",vt="eip155:43114",At="eip155:56",Ne="eip155:480",Le="eip155:143",Oe="eip155:4663",ke="eip155:1187947933",Be="eip155:324705682",bt="eip155:1";var wt="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";var Nn="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",zr="0x55d398326f99059fF775485246999027B3197955",Ln="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",Hr="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",On={[At]:Ln,[Ie]:Nn,[gt]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[ht]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[ft]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[yt]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[vt]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[Ne]:"0x79A02482A880bCE3F13e09Da970dC34db4CD24d1",[Le]:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",[Oe]:Hr,[ke]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[Be]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[bt]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},kn={[zr]:{symbol:"USDT",decimals:18},[Ln]:{symbol:"USDC",decimals:18}};var Hi={[Ne]:{name:"USDC",version:"2"},[Le]:{name:"USDC",version:"2"},[Oe]:{name:"Global Dollar",version:"1"},[ke]:{name:"Bridged USDC (SKALE Bridge)",version:"2"},[Be]:{name:"Bridged USDC (SKALE Bridge)",version:"2"}};var Wi={[At]:56,[Ie]:8453,[gt]:84532,[ht]:42161,[ft]:137,[yt]:10,[vt]:43114,[Ne]:480,[Le]:143,[Oe]:4663,[ke]:1187947933,[Be]:324705682,[bt]:1},Gi={[ee]:"https://api.dexter.cash/api/solana/rpc",[Tn]:"https://api.devnet.solana.com",[In]:"https://api.testnet.solana.com"},Wr={[At]:"https://api.dexter.cash/api/evm/bsc/rpc",[Ie]:"https://api.dexter.cash/api/base/rpc",[gt]:"https://sepolia.base.org",[ht]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[ft]:"https://api.dexter.cash/api/evm/polygon/rpc",[yt]:"https://api.dexter.cash/api/evm/optimism/rpc",[vt]:"https://api.dexter.cash/api/evm/avalanche/rpc",[Ne]:"https://worldchain-mainnet.g.alchemy.com/public",[Le]:"https://rpc.monad.xyz",[Oe]:"https://rpc.mainnet.chain.robinhood.com",[ke]:"https://skale-base.skalenodes.com/v1/base",[Be]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[bt]:"https://eth.llamarpc.com"},Ue="https://x402.dexter.cash";var Bn="dexter-tab-hosted-pay-before-delivery/v1",Un="pay_before_delivery_seller_2xx",Kn="x-tab-voucher",$n="base64(188-byte sessionRegisterMessage)";function St(t){return t.startsWith("solana:")||t==="solana"}function Gr(t){if(typeof Buffer<"u")return Buffer.from(t,"utf-8").toString("base64");let e=new TextEncoder().encode(t),n="";for(let r=0;r<e.length;r++)n+=String.fromCharCode(e[r]);return btoa(n)}function jr(t){if(typeof Buffer<"u")return Buffer.from(t,"base64").toString("utf-8");let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return new TextDecoder().decode(n)}function _t(t){return Gr(JSON.stringify(t))}function Ke(t){return JSON.parse(jr(t))}function Xr(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 $e=class extends Error{status;body;constructor(e,n){super(`HTTP ${e}`),this.status=e,this.body=n}},Ct=class{facilitatorUrl;cachedSupported=null;cacheTime=0;CACHE_TTL_MS=6e4;timeoutMs;maxRetries;retryBaseMs;constructor(e=Ue,n){this.facilitatorUrl=e.replace(/\/$/,""),this.timeoutMs=n?.timeoutMs??1e4,this.maxRetries=n?.maxRetries??3,this.retryBaseMs=n?.retryBaseMs??500}async fetchWithTimeout(e,n){let r=new AbortController,i=setTimeout(()=>r.abort(),this.timeoutMs);try{return await fetch(e,{...n,signal:r.signal})}finally{clearTimeout(i)}}async fetchWithRetry(e,n){let r;for(let i=0;i<this.maxRetries;i++)try{let o=await this.fetchWithTimeout(e,n);if(!o.ok&&o.status>=500)throw new $e(o.status,await o.text());return o}catch(o){if(r=o,i<this.maxRetries-1&&Xr(o)){let s=this.retryBaseMs*Math.pow(2,i);await new Promise(c=>setTimeout(c,s));continue}throw o}throw r}async getSupported(){let e=Date.now();if(this.cachedSupported&&e-this.cacheTime<this.CACHE_TTL_MS)return this.cachedSupported;let n=await this.fetchWithTimeout(`${this.facilitatorUrl}/supported`);if(!n.ok)throw new Error(`Facilitator /supported returned ${n.status}`);return this.cachedSupported=await n.json(),this.cacheTime=e,this.cachedSupported}async getFeePayer(e){let r=(await this.getSupported()).kinds.find(i=>i.x402Version===2&&(i.scheme==="exact"||i.scheme==="exact-approval")&&i.network===e);if(!r)throw new Error(`Facilitator does not support network "${e}" with a recognized scheme`);return r.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,n){try{let r=Ke(e),i=await this.fetchWithRetry(`${this.facilitatorUrl}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x402Version:2,paymentPayload:r,paymentRequirements:n})});return i.ok?await i.json():{isValid:!1,invalidReason:`facilitator_error_${i.status}`}}catch(r){return{isValid:!1,invalidReason:r instanceof $e?`facilitator_error_${r.status}`:r instanceof Error&&r.name==="AbortError"?"facilitator_timeout":r instanceof Error?r.message:"unexpected_verify_error"}}}async settlePayment(e,n){try{let r=Ke(e),i=await this.fetchWithRetry(`${this.facilitatorUrl}/settle`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x402Version:2,paymentPayload:r,paymentRequirements:n})});return i.ok?{...await i.json(),network:n.network}:{success:!1,network:n.network,errorReason:`facilitator_error_${i.status}`}}catch(r){let i=r instanceof $e?`facilitator_error_${r.status}`:r instanceof Error&&r.name==="AbortError"?"facilitator_timeout":r instanceof Error?r.message:"unexpected_settle_error";return{success:!1,network:n.network,errorReason:i}}}};function Jr(t){if(St(t))return{address:wt,decimals:6};let e=On[t];if(e){let n=kn[e]?.decimals??6;return{address:e,decimals:n}}return{address:wt,decimals:6}}function Mn(t){try{let e=Ke(t);return e?.accepted?.amount??e?.accepted?.maxAmountRequired}catch{return}}function Me(t){let{payTo:e,facilitatorUrl:n=Ue,network:r=ee,defaultTimeoutSeconds:i=60}=t,o=t.asset??Jr(r),s=t.scheme??"exact";if(s==="tab"&&!St(r))throw new Error(`scheme 'tab' is SVM-only; got network "${r}"`);let c=new Ct(n),l=null,p=new Map,y=3e4,v=Date.now();function h(d){let a=(d.maxTimeoutSeconds||i)*1e3;if(p.set(d.payTo,{accept:d,expiresAt:Date.now()+a}),Date.now()-v>y){let x=Date.now();for(let[A,O]of p)O.expiresAt<x&&p.delete(A);v=x}}function f(d){let a=p.get(d);if(a){if(a.expiresAt<Date.now()){p.delete(d);return}return a.accept}}async function g(d){return typeof e=="string"?e:e(d||{})}async function S(){if(l||(l=await c.getNetworkExtra(r)),St(r)&&!l?.feePayer)throw new Error(`Facilitator does not provide feePayer for network "${r}"`);return{...l?.feePayer?{feePayer:l.feePayer}:{},decimals:l?.decimals??o.decimals,name:l?.name,version:l?.version,...s==="batch-settlement"&&l?.receiverAuthorizer?{receiverAuthorizer:l.receiverAuthorizer}:{},...s==="tab"?{voucherHeader:Kn,registrationEncoding:$n,termsVersion:Bn,acceptanceRule:Un}:{}}}async function P(d,a){let{amountAtomic:x,timeoutSeconds:A=i}=a,O=await S(),$={scheme:s,network:r,amount:x,maxAmountRequired:x,asset:o.address,payTo:d,maxTimeoutSeconds:A,extra:O};return h($),$}async function I(d){let a=await g({amountAtomic:d.amountAtomic,resourceUrl:d.resourceUrl});return P(a,d)}async function j(d){let{resourceUrl:a,description:x,mimeType:A="application/json"}=d,O={url:a,description:x,mimeType:A},$=await I(d);return{x402Version:2,resource:O,accepts:[$],error:"Payment required"}}function te(d){return _t(d)}function oe(d){return{status:402,headers:{"PAYMENT-REQUIRED":te(d)},body:{}}}async function q(d,a){if(!a){let x=await g({paymentHeader:d});a=f(x),a||(a=await P(x,{amountAtomic:Mn(d)??"0",resourceUrl:""}))}return c.verifyPayment(d,a)}async function _(d,a){if(!a){let x=await g({paymentHeader:d});a=f(x),a||(a=await P(x,{amountAtomic:Mn(d)??"0",resourceUrl:""}))}return c.settlePayment(d,a)}return{buildRequirements:j,encodeRequirements:te,create402Response:oe,verifyPayment:q,settlePayment:_,getPaymentAccept:I,network:r,assetDecimals:o.decimals,facilitator:c}}var Yr={"solana:mainnet":ee};function Fn(t){let e=Yr[t.network];if(!e)throw new Error(`tabChallengeMiddleware: unsupported network "${t.network}"`);let n=typeof t.sellerPubkey=="string"?t.sellerPubkey:t.sellerPubkey.toBase58();new Dn.PublicKey(n);let r=Me({payTo:n,network:e,scheme:"tab",facilitatorUrl:t.facilitatorUrl}),i=G(t.perUnit);return async(o,s,c)=>{if(o.headers[ie])return c();try{let l=`${o.protocol}://${o.get("host")}${o.originalUrl}`,p=await r.buildRequirements({amountAtomic:i,resourceUrl:l,description:t.description}),y=r.create402Response(p);s.set(y.headers).status(y.status).json(y.body)}catch(l){let p=l?.message??String(l);s.status(503).set({"Retry-After":"5"}).json({error:"challenge_unavailable",detail:p})}}}var qn=require("@solana/web3.js");var Zr={"solana:mainnet":ee};function zn(t){let e=Zr[t.network];if(!e)throw new Error(`tabOrExactMiddleware: unsupported network "${t.network}"`);let n=typeof t.sellerPubkey=="string"?t.sellerPubkey:t.sellerPubkey.toBase58();new qn.PublicKey(n);let r=Me({payTo:n,network:e,scheme:"tab",facilitatorUrl:t.facilitatorUrl}),i=Me({payTo:n,network:e,scheme:"exact",facilitatorUrl:t.facilitatorUrl}),o=G(t.perUnit),s=ut({connection:t.connection,sellerPubkey:n,network:t.network,perUnit:t.perUnit,settle:"on-close",facilitatorUrl:t.facilitatorUrl,ledger:t.ledger,ledgerSafetyMode:t.ledgerSafetyMode,leaseTtlMs:t.leaseTtlMs,lockCadence:t.lockCadence});return async(c,l,p)=>{if(c.headers[ie])return s(c,l,p);let y=`${c.protocol}://${c.get("host")}${c.originalUrl}`,v=c.headers["payment-signature"];if(v){let h;try{h=await i.getPaymentAccept({amountAtomic:o,resourceUrl:y,description:t.description})}catch(f){let g=f?.message??String(f);l.status(503).set({"Retry-After":"5"}).json({error:"challenge_unavailable",detail:g});return}try{let f=await i.verifyPayment(v,h);if(!f.isValid){l.status(402).json({error:"Payment verification failed",reason:f.invalidReason});return}let g=await i.settlePayment(v,h);if(!g.success){l.status(402).json({error:"Payment settlement failed",reason:g.errorReason});return}return c.x402={transaction:g.transaction,payer:f.payer??"",network:g.network||e},l.setHeader("PAYMENT-RESPONSE",_t({success:!0,transaction:g.transaction,network:g.network||e,payer:f.payer??""})),p()}catch{l.status(500).json({error:"Payment processing error"});return}}try{let h={amountAtomic:o,resourceUrl:y,description:t.description},[f,g]=await Promise.all([r.buildRequirements(h),i.buildRequirements(h)]),S={...f,accepts:[...f.accepts,...g.accepts]};l.set({"PAYMENT-REQUIRED":r.encodeRequirements(S)}).status(402).json({error:"Payment required",accepts:S.accepts,resource:S.resource})}catch(h){let f=h?.message??String(h);l.status(503).set({"Retry-After":"5"}).json({error:"challenge_unavailable",detail:f})}}}0&&(module.exports={ChannelLeaseLostError,FileChannelLedger,FileVoucherStore,InMemoryChannelLedger,InMemoryVoucherStore,InvalidRegistrationError,InvalidVoucherError,InvalidVoucherSignatureError,OnChainVerificationError,RedisChannelLedger,RedisKeyspaceMigrationRequiredError,ScopeViolationError,TAB_VOUCHER_HEADER,deserializeChannelLedgerEntry,enforceScope,openSse,parseRegistration,requireTab,serializeChannelLedgerEntry,tabChallengeMiddleware,tabMiddleware,tabOrExactMiddleware,verifyRegistrationOnChain,verifyVoucherSignature});
27
+ `),t.end())}return{charge:v,send:h,end:f}}var _e=require("fs"),pt=require("path");function Dr(t){return{payload:t.payload,sessionPublicKey:qt(t.sessionPublicKey),sessionRegistration:qt(t.sessionRegistration),sessionSignature:qt(t.sessionSignature)}}function Fr(t){return{payload:t.payload,sessionPublicKey:zt(t.sessionPublicKey),sessionRegistration:zt(t.sessionRegistration),sessionSignature:zt(t.sessionSignature)}}function qt(t){let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}function zt(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 n=0;n<e.length;n++)e[n]=parseInt(t.substr(n*2,2),16);return e}var dt=class{map=new Map;async get(e){return this.map.get(e)??null}async set(e,n){this.map.set(e,n)}async delete(e){this.map.delete(e)}},mt=class{constructor(e){this.dir=e}dir;pathFor(e){if(!/^[a-z0-9_-]+$/i.test(e))throw new Error(`unsafe channelId for filesystem: ${e}`);return(0,pt.join)(this.dir,`${e}.json`)}async get(e){try{let n=await _e.promises.readFile(this.pathFor(e),"utf8");return Fr(JSON.parse(n))}catch(n){if(n?.code==="ENOENT")return null;throw n}}async set(e,n){let r=this.pathFor(e);await _e.promises.mkdir((0,pt.dirname)(r),{recursive:!0});let i=`${r}.tmp`;await _e.promises.writeFile(i,JSON.stringify(Dr(n))),await _e.promises.rename(i,r)}async delete(e){try{await _e.promises.unlink(this.pathFor(e))}catch(n){if(n?.code!=="ENOENT")throw n}}};var Mn=require("@solana/web3.js");var ee="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Vn="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Tn="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";var Ne="eip155:8453",gt="eip155:84532",ht="eip155:42161",ft="eip155:137",yt="eip155:10",vt="eip155:43114",At="eip155:56",Le="eip155:480",Oe="eip155:143",ke="eip155:4663",Be="eip155:1187947933",Ue="eip155:324705682",bt="eip155:1";var wt="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";var In="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",qr="0x55d398326f99059fF775485246999027B3197955",Nn="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",zr="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",Ln={[At]:Nn,[Ne]:In,[gt]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[ht]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[ft]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[yt]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[vt]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[Le]:"0x79A02482A880bCE3F13e09Da970dC34db4CD24d1",[Oe]:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",[ke]:zr,[Be]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[Ue]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[bt]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},On={[qr]:{symbol:"USDT",decimals:18},[Nn]:{symbol:"USDC",decimals:18}};var zi={[Le]:{name:"USDC",version:"2"},[Oe]:{name:"USDC",version:"2"},[ke]:{name:"Global Dollar",version:"1"},[Be]:{name:"Bridged USDC (SKALE Bridge)",version:"2"},[Ue]:{name:"Bridged USDC (SKALE Bridge)",version:"2"}};var Hi={[At]:56,[Ne]:8453,[gt]:84532,[ht]:42161,[ft]:137,[yt]:10,[vt]:43114,[Le]:480,[Oe]:143,[ke]:4663,[Be]:1187947933,[Ue]:324705682,[bt]:1},Wi={[ee]:"https://api.dexter.cash/api/solana/rpc",[Vn]:"https://api.devnet.solana.com",[Tn]:"https://api.testnet.solana.com"},Hr={[At]:"https://api.dexter.cash/api/evm/bsc/rpc",[Ne]:"https://api.dexter.cash/api/base/rpc",[gt]:"https://sepolia.base.org",[ht]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[ft]:"https://api.dexter.cash/api/evm/polygon/rpc",[yt]:"https://api.dexter.cash/api/evm/optimism/rpc",[vt]:"https://api.dexter.cash/api/evm/avalanche/rpc",[Le]:"https://worldchain-mainnet.g.alchemy.com/public",[Oe]:"https://rpc.monad.xyz",[ke]:"https://rpc.mainnet.chain.robinhood.com",[Be]:"https://skale-base.skalenodes.com/v1/base",[Ue]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[bt]:"https://eth.llamarpc.com"},Ke="https://x402.dexter.cash";var kn="dexter-tab-hosted-pay-before-delivery/v1",Bn="pay_before_delivery_seller_2xx",Un="x-tab-voucher",Kn="base64(188-byte sessionRegisterMessage)";function St(t){return t.startsWith("solana:")||t==="solana"}function Wr(t){if(typeof Buffer<"u")return Buffer.from(t,"utf-8").toString("base64");let e=new TextEncoder().encode(t),n="";for(let r=0;r<e.length;r++)n+=String.fromCharCode(e[r]);return btoa(n)}function Gr(t){if(typeof Buffer<"u")return Buffer.from(t,"base64").toString("utf-8");let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return new TextDecoder().decode(n)}function _t(t){return Wr(JSON.stringify(t))}function $e(t){return JSON.parse(Gr(t))}function jr(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 Me=class extends Error{status;body;constructor(e,n){super(`HTTP ${e}`),this.status=e,this.body=n}},Ct=class{facilitatorUrl;cachedSupported=null;cacheTime=0;CACHE_TTL_MS=6e4;timeoutMs;maxRetries;retryBaseMs;constructor(e=Ke,n){this.facilitatorUrl=e.replace(/\/$/,""),this.timeoutMs=n?.timeoutMs??1e4,this.maxRetries=n?.maxRetries??3,this.retryBaseMs=n?.retryBaseMs??500}async fetchWithTimeout(e,n){let r=new AbortController,i=setTimeout(()=>r.abort(),this.timeoutMs);try{return await fetch(e,{...n,signal:r.signal})}finally{clearTimeout(i)}}async fetchWithRetry(e,n){let r;for(let i=0;i<this.maxRetries;i++)try{let o=await this.fetchWithTimeout(e,n);if(!o.ok&&o.status>=500)throw new Me(o.status,await o.text());return o}catch(o){if(r=o,i<this.maxRetries-1&&jr(o)){let s=this.retryBaseMs*Math.pow(2,i);await new Promise(c=>setTimeout(c,s));continue}throw o}throw r}async getSupported(){let e=Date.now();if(this.cachedSupported&&e-this.cacheTime<this.CACHE_TTL_MS)return this.cachedSupported;let n=await this.fetchWithTimeout(`${this.facilitatorUrl}/supported`);if(!n.ok)throw new Error(`Facilitator /supported returned ${n.status}`);return this.cachedSupported=await n.json(),this.cacheTime=e,this.cachedSupported}async getFeePayer(e){let r=(await this.getSupported()).kinds.find(i=>i.x402Version===2&&(i.scheme==="exact"||i.scheme==="exact-approval")&&i.network===e);if(!r)throw new Error(`Facilitator does not support network "${e}" with a recognized scheme`);return r.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,n){try{let r=$e(e),i=await this.fetchWithRetry(`${this.facilitatorUrl}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x402Version:2,paymentPayload:r,paymentRequirements:n})});return i.ok?await i.json():{isValid:!1,invalidReason:`facilitator_error_${i.status}`}}catch(r){return{isValid:!1,invalidReason:r instanceof Me?`facilitator_error_${r.status}`:r instanceof Error&&r.name==="AbortError"?"facilitator_timeout":r instanceof Error?r.message:"unexpected_verify_error"}}}async settlePayment(e,n){try{let r=$e(e),i=await this.fetchWithRetry(`${this.facilitatorUrl}/settle`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x402Version:2,paymentPayload:r,paymentRequirements:n})});return i.ok?{...await i.json(),network:n.network}:{success:!1,network:n.network,errorReason:`facilitator_error_${i.status}`}}catch(r){let i=r instanceof Me?`facilitator_error_${r.status}`:r instanceof Error&&r.name==="AbortError"?"facilitator_timeout":r instanceof Error?r.message:"unexpected_settle_error";return{success:!1,network:n.network,errorReason:i}}}};function Xr(t){if(St(t))return{address:wt,decimals:6};let e=Ln[t];if(e){let n=On[e]?.decimals??6;return{address:e,decimals:n}}return{address:wt,decimals:6}}function $n(t){try{let e=$e(t);return e?.accepted?.amount??e?.accepted?.maxAmountRequired}catch{return}}function De(t){let{payTo:e,facilitatorUrl:n=Ke,network:r=ee,defaultTimeoutSeconds:i=60}=t,o=t.asset??Xr(r),s=t.scheme??"exact";if(s==="tab"&&!St(r))throw new Error(`scheme 'tab' is SVM-only; got network "${r}"`);let c=new Ct(n),l=null,p=new Map,y=3e4,v=Date.now();function h(d){let a=(d.maxTimeoutSeconds||i)*1e3;if(p.set(d.payTo,{accept:d,expiresAt:Date.now()+a}),Date.now()-v>y){let x=Date.now();for(let[A,O]of p)O.expiresAt<x&&p.delete(A);v=x}}function f(d){let a=p.get(d);if(a){if(a.expiresAt<Date.now()){p.delete(d);return}return a.accept}}async function g(d){return typeof e=="string"?e:e(d||{})}async function S(){if(l||(l=await c.getNetworkExtra(r)),St(r)&&!l?.feePayer)throw new Error(`Facilitator does not provide feePayer for network "${r}"`);return{...l?.feePayer?{feePayer:l.feePayer}:{},decimals:l?.decimals??o.decimals,name:l?.name,version:l?.version,...s==="batch-settlement"&&l?.receiverAuthorizer?{receiverAuthorizer:l.receiverAuthorizer}:{},...s==="tab"?{voucherHeader:Un,registrationEncoding:Kn,termsVersion:kn,acceptanceRule:Bn}:{}}}async function P(d,a){let{amountAtomic:x,timeoutSeconds:A=i}=a,O=await S(),$={scheme:s,network:r,amount:x,maxAmountRequired:x,asset:o.address,payTo:d,maxTimeoutSeconds:A,extra:O};return h($),$}async function I(d){let a=await g({amountAtomic:d.amountAtomic,resourceUrl:d.resourceUrl});return P(a,d)}async function j(d){let{resourceUrl:a,description:x,mimeType:A="application/json"}=d,O={url:a,description:x,mimeType:A},$=await I(d);return{x402Version:2,resource:O,accepts:[$],error:"Payment required"}}function te(d){return _t(d)}function oe(d){return{status:402,headers:{"PAYMENT-REQUIRED":te(d)},body:{}}}async function q(d,a){if(!a){let x=await g({paymentHeader:d});a=f(x),a||(a=await P(x,{amountAtomic:$n(d)??"0",resourceUrl:""}))}return c.verifyPayment(d,a)}async function _(d,a){if(!a){let x=await g({paymentHeader:d});a=f(x),a||(a=await P(x,{amountAtomic:$n(d)??"0",resourceUrl:""}))}return c.settlePayment(d,a)}return{buildRequirements:j,encodeRequirements:te,create402Response:oe,verifyPayment:q,settlePayment:_,getPaymentAccept:I,network:r,assetDecimals:o.decimals,facilitator:c}}var Jr={"solana:mainnet":ee};function Dn(t){let e=Jr[t.network];if(!e)throw new Error(`tabChallengeMiddleware: unsupported network "${t.network}"`);let n=typeof t.sellerPubkey=="string"?t.sellerPubkey:t.sellerPubkey.toBase58();new Mn.PublicKey(n);let r=De({payTo:n,network:e,scheme:"tab",facilitatorUrl:t.facilitatorUrl}),i=G(t.perUnit);return async(o,s,c)=>{if(o.headers[ie])return c();try{let l=`${o.protocol}://${o.get("host")}${o.originalUrl}`,p=await r.buildRequirements({amountAtomic:i,resourceUrl:l,description:t.description}),y=r.create402Response(p);s.set(y.headers).status(y.status).json(y.body)}catch(l){let p=l?.message??String(l);s.status(503).set({"Retry-After":"5"}).json({error:"challenge_unavailable",detail:p})}}}var Fn=require("@solana/web3.js");var Yr={"solana:mainnet":ee};function qn(t){let e=Yr[t.network];if(!e)throw new Error(`tabOrExactMiddleware: unsupported network "${t.network}"`);let n=typeof t.sellerPubkey=="string"?t.sellerPubkey:t.sellerPubkey.toBase58();new Fn.PublicKey(n);let r=De({payTo:n,network:e,scheme:"tab",facilitatorUrl:t.facilitatorUrl}),i=De({payTo:n,network:e,scheme:"exact",facilitatorUrl:t.facilitatorUrl}),o=G(t.perUnit),s=ut({connection:t.connection,sellerPubkey:n,network:t.network,perUnit:t.perUnit,settle:"on-close",facilitatorUrl:t.facilitatorUrl,ledger:t.ledger,ledgerSafetyMode:t.ledgerSafetyMode,leaseTtlMs:t.leaseTtlMs,lockCadence:t.lockCadence});return async(c,l,p)=>{if(c.headers[ie])return s(c,l,p);let y=`${c.protocol}://${c.get("host")}${c.originalUrl}`,v=c.headers["payment-signature"];if(v){let h;try{h=await i.getPaymentAccept({amountAtomic:o,resourceUrl:y,description:t.description})}catch(f){let g=f?.message??String(f);l.status(503).set({"Retry-After":"5"}).json({error:"challenge_unavailable",detail:g});return}try{let f=await i.verifyPayment(v,h);if(!f.isValid){l.status(402).json({error:"Payment verification failed",reason:f.invalidReason});return}let g=await i.settlePayment(v,h);if(!g.success){l.status(402).json({error:"Payment settlement failed",reason:g.errorReason});return}return c.x402={transaction:g.transaction,payer:f.payer??"",network:g.network||e},l.setHeader("PAYMENT-RESPONSE",_t({success:!0,transaction:g.transaction,network:g.network||e,payer:f.payer??""})),p()}catch{l.status(500).json({error:"Payment processing error"});return}}try{let h={amountAtomic:o,resourceUrl:y,description:t.description},[f,g]=await Promise.all([r.buildRequirements(h),i.buildRequirements(h)]),S={...f,accepts:[...f.accepts,...g.accepts]};l.set({"PAYMENT-REQUIRED":r.encodeRequirements(S)}).status(402).json({error:"Payment required",accepts:S.accepts,resource:S.resource})}catch(h){let f=h?.message??String(h);l.status(503).set({"Retry-After":"5"}).json({error:"challenge_unavailable",detail:f})}}}0&&(module.exports={ChannelLeaseLostError,FileChannelLedger,FileVoucherStore,InMemoryChannelLedger,InMemoryVoucherStore,InvalidRegistrationError,InvalidVoucherError,InvalidVoucherSignatureError,OnChainVerificationError,RedisChannelLedger,RedisKeyspaceMigrationRequiredError,ScopeViolationError,TAB_VOUCHER_HEADER,deserializeChannelLedgerEntry,enforceScope,openSse,parseRegistration,requireTab,serializeChannelLedgerEntry,tabChallengeMiddleware,tabMiddleware,tabOrExactMiddleware,verifyRegistrationOnChain,verifyVoucherSignature});