@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
@@ -19,7 +19,7 @@ return redis.call("del", KEYS[1])
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
- `,Bn='return redis.call("get", KEYS[1])',ke=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 Le(t){return`${t.ownerToken}:${t.fence}`}function Oe(t){return t===1||t==="1"}var pt=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&&!Xt(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:Xt(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(Bn,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 ke(e)}async get(e){this.assertChannelId(e),await this.assertClusterCutover(e);let n=await this.primaryGet(this.ledgerKey(e));return n===null?null:mt(JSON.parse(n))}async writeIfOwned(e,n,r){let i=dt(n),o=await this.client.eval(Nn,2,this.leaseKey(e),this.ledgerKey(e),Le(r),JSON.stringify(i));if(!Oe(o))throw new D(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(Ln,2,this.leaseKey(e),this.ledgerKey(e),Le(n));if(!Oe(r))throw new D(e)})}async tryAcquireLease(e,n){return this.assertChannelId(e),E(e,async()=>{await this.assertClusterCutover(e);let r=Tn(),i=J(n),o=await this.client.eval(In,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(On,1,this.leaseKey(e),Le(n));return Oe(r)})}async renewLease(e,n,r){return this.assertChannelId(e),E(e,async()=>{let i=J(r),o=await this.client.eval(kn,1,this.leaseKey(e),Le(n),i);if(!Oe(o))throw new D(e);return{...n,heldUntilUnixMs:Date.now()+i}})}};import{PublicKey as hr}from"@solana/web3.js";import Kn from"tweetnacl";import{sha256 as yi}from"@noble/hashes/sha256";import{p256 as Ai}from"@noble/curves/p256";import{PublicKey as ht}from"@solana/web3.js";import{sessionRegisterMessage as Un,sessionReplaceV1Message as Zr,sessionRevokeMessage as Qr,sessionVoucherV2Nonce as ei,sessionVoucherV2AuthorizationNonce as ti,finalVoucherV2Sequence as ni,voucherV2SequenceOrdinal as ri,voucherPayloadMessage as gt,buildVoucherMessage as ii}from"@dexterai/vault/messages";import{buildRegisterSessionKeyInstruction as ai,buildRevokeSessionKeyInstruction as ci,deriveSwigWalletAddress as li}from"@dexterai/vault/instructions";import{buildSecp256r1VerifyInstruction as di}from"@dexterai/vault/precompile";import{DEXTER_VAULT_PROGRAM_ID as Be,SECP256R1_PROGRAM_ID as pi,INSTRUCTIONS_SYSVAR_ID as gi}from"@dexterai/vault/constants";import{decodeSessionAccount as $n,deriveSessionPda as Yt,isSessionLive as Mn}from"@dexterai/vault/session";import{contextBoundVoucherV2Message as Dn,sessionVoucherV2AuthorizationNonce as Fn,voucherV2SequenceOrdinal as qn}from"@dexterai/vault/messages";var ft="OTS_SESSION_REGISTER_V2";function te(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 Ue(t){if(t.length!==188)throw new W("wrong_length",`expected 188, got ${t.length}`);let e=new TextDecoder().decode(t.slice(0,ft.length));if(e!==ft)throw new W("wrong_domain",`got "${e}"`);for(let v=ft.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 ht(t.slice(32,64)),i=new ht(t.slice(64,96)),o=t.slice(96,128),s=n.getBigUint64(128,!0),c=n.getBigInt64(136,!0),l=new ht(t.slice(144,176)),p=n.getUint32(176,!0),y=n.getBigUint64(180,!0);if(!r.equals(Be))throw new W("wrong_program",`${r.toBase58()} is not ${Be.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 $=class extends Error{constructor(n,r){super(`On-chain verification failed: ${n}${r?` (${r})`:""}`);this.reason=n;this.name="OnChainVerificationError"}reason};async function yt(t,e){let[n]=Yt(e.vaultPda,e.allowedCounterparty,e.programId),r=await t.getAccountInfo(n,"finalized");if(!r)throw new $("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 $("wrong_program",`SessionAccount owner ${r.owner.toBase58()} != ${e.programId.toBase58()}`);let i;try{i=$n(n,r.data)}catch(h){throw new $("registration_state_mismatch",`finalized SessionAccount decode failed: ${h instanceof Error?h.message:String(h)}`)}if(i.version===0)throw new $("session_not_active","finalized SessionAccount is cleared");if(!Mn(i))throw new $("session_not_active","SessionAccount PDA is present but expired");if(!Zt(i.session.sessionPubkey,e.sessionPubkey))throw new $("session_pubkey_mismatch",`on-chain ${Jt(i.session.sessionPubkey)} != registration ${Jt(e.sessionPubkey)}`);let o=te(e.nonce),s=te(i.session.nonce);if(s!==o)throw new $("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 $("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 I=class extends Error{constructor(e){super(`Invalid voucher signature${e?`: ${e}`:""}`),this.name="InvalidVoucherSignatureError"}};function vt(t,e){if(e.length!==32)throw new I(`channelIdBytes must be 32 bytes, got ${e.length}`);if(t.sessionPublicKey.length!==32)throw new I(`sessionPublicKey must be 32 bytes, got ${t.sessionPublicKey.length}`);if(t.sessionSignature.length!==64)throw new I(`sessionSignature must be 64 bytes, got ${t.sessionSignature.length}`);let n=Ue(t.sessionRegistration);if(!Zt(n.sessionPubkey,t.sessionPublicKey))throw new I("registration session key does not match voucher session key");let r=n.nonce>=2147483648,i=te(n.nonce),o=te(t.payload.sequenceNumber);if(i!==o)throw new I(`voucher wire V${o} does not match registration wire V${i}`);let s;if(r){Fn(n.nonce),qn(t.payload.sequenceNumber);let[l]=Yt(n.vaultPda,n.allowedCounterparty,n.programId);s=Dn({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=gt({channelId:e,cumulativeAmount:BigInt(t.payload.cumulativeAmount),sequenceNumber:t.payload.sequenceNumber});if(!Kn.sign.detached.verify(s,t.sessionSignature,t.sessionPublicKey))throw new I("ed25519 verify rejected")}var L=class extends Error{constructor(n,r){super(`Scope violation: ${n}${r?` (${r})`:""}`);this.reason=n;this.name="ScopeViolationError"}reason};function Ke(t){let e=BigInt(t.voucher.payload.cumulativeAmount);if(e>t.registration.maxAmount)throw new L("cumulative_exceeds_cap",`${e} > ${t.registration.maxAmount}`);let n=BigInt(Math.floor(Date.now()/1e3));if(n>=t.registration.expiresAt)throw new L("session_expired",`now=${n} >= expiresAt=${t.registration.expiresAt}`);if(!t.registration.allowedCounterparty.equals(t.expectedCounterparty))throw new L("wrong_counterparty",`${t.registration.allowedCounterparty.toBase58()} != ${t.expectedCounterparty.toBase58()}`);if(t.previousCumulativeAtomic!==void 0){let r=BigInt(t.previousCumulativeAtomic);if(e<=r)throw new L("non_monotonic",`cumulative=${e} not > previous=${r}`)}}function Zt(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 Jt(t){let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}import{PublicKey as Qi}from"@solana/web3.js";import{bytesToHex as to}from"@noble/hashes/utils";import Vi from"tweetnacl";import{PublicKey as Ii}from"@solana/web3.js";import{contextBoundVoucherV2Message as Li,finalVoucherV2Sequence as Oi,sessionRegisterMessage as ki,sessionVoucherV2AuthorizationNonce as Bi}from"@dexterai/vault/messages";import{deriveSessionPda as Ki}from"@dexterai/vault/session";import{sha256 as Fi}from"@noble/hashes/sha256";var Mi=(1n<<64n)-1n;import{sha256 as nn}from"@noble/hashes/sha256";import{bytesToHex as pe}from"@noble/hashes/utils";var Qt=/^[0-9a-f]{64}$/,en=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/,zn=/^[1-9A-HJ-NP-Za-km-z]{32,100}$/,tn="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",rn="dexter-native-tab-v2-reservation/v1",Hn=`${rn}:`;function At(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(At);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,At(n)]));throw new Error("canonical_value_unsupported")}function on(t){return JSON.stringify(At(t))}function bt(t){if(t==="solana:mainnet"||t===tn)return tn;throw new Error("native_tab_v2_reservation_network_unsupported")}function wt(t){return pe(nn(new TextEncoder().encode(on({channelId:t.payload.channelId,cumulativeAmount:t.payload.cumulativeAmount,sequenceNumber:t.payload.sequenceNumber,sessionPublicKey:pe(t.sessionPublicKey),sessionSignature:pe(t.sessionSignature),sessionRegistration:pe(t.sessionRegistration)}))))}function St(t){let e=wt(t);return{voucherDigest:e,idempotencyKey:`native-tab-v2:${e}`}}function Wn(t){return pe(nn(new TextEncoder().encode(on({contract:rn,network:bt(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 Gn(t){let e=wt(t.voucher);return Wn({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 sn(t){return`${Hn}${Gn(t)}`}function N(t){throw new Error(`native_tab_v2_reservation_receipt_invalid:${t}`)}function $e(t,e){(!Number.isSafeInteger(t)||t<0)&&N(e)}function _t(t,e){(!e||typeof e!="object")&&N("missing");let n=wt(t.voucher);(!Qt.test(t.voucherDigest)||t.voucherDigest!==n)&&N("input_voucher_digest"),t.idempotencyKey!==`native-tab-v2:${n}`&&N("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)&&N("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)&&N("input_voucher_identity"),e.contract!=="dexter-native-tab-open-receipt/v1"&&e.contract!=="dexter-native-tab-open-receipt/v2"&&N("contract"),Qt.test(e.operationId)||N("operation_id"),en.test(e.callerOperationId)||N("caller_operation_id"),zn.test(e.transaction)||N("transaction"),e.commitment!=="confirmed"&&e.commitment!=="finalized"&&N("commitment"),$e(e.confirmationSlot,"confirmation_slot"),$e(e.postStateSlot,"post_state_slot"),(e.confirmationSlot===0||e.postStateSlot<e.confirmationSlot)&&N("post_state_slot");let s,c;try{s=bt(t.network),c=bt(e.network)}catch{return N("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!==pe(t.voucher.sessionPublicKey)||e.voucherDigest!==n||e.cumulativeAmountAtomic!==t.voucher.payload.cumulativeAmount||e.sequenceNumber!==t.voucher.payload.sequenceNumber||!en.test(e.providerReceiptId)||e.reservationAmountAtomic!==t.reservationAmountAtomic||e.currentOutstandingBeforeAtomic!=="0"||e.currentOutstandingAfterAtomic!==t.reservationAmountAtomic)&&N("economic_identity"),$e(e.pendingVoucherCountBefore,"pending_voucher_count_before"),$e(e.pendingVoucherCountAfter,"pending_voucher_count_after"),e.contract==="dexter-native-tab-open-receipt/v1"?e.callerOperationId!==t.idempotencyKey&&N("idempotency_key"):(e.rootOperationId!==t.idempotencyKey||!Number.isSafeInteger(e.generation)||Number(e.generation)<2||!e.predecessorCallerOperationId||!e.predecessorLifecycleOperationId||!e.predecessorReleaseDigest||!e.stableReservationId||!e.economicEffectDigest)&&N("successor_identity")}import{deriveSessionPda as so}from"@dexterai/vault/session";var an="https://x402.dexter.cash",cn=6;function H(t,e=cn){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 se(t,e=cn){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}import{PublicKey as ne}from"@solana/web3.js";import{bytesToHex as Ct}from"@noble/hashes/utils";import{deriveGraphConfigPda as jn,deriveSwigVaultBindingPda as xt}from"@dexterai/vault/credit";import{DEXTER_VAULT_PROGRAM_ID as Xn,DISCRIMINATORS as Jn}from"@dexterai/vault/constants";import{deriveSwigWalletAddress as Yn}from"@dexterai/vault/instructions";import{decodeVaultFull as Zn}from"@dexterai/vault/reader";import{decodeSessionAccount as Qn,deriveSessionPda as Rt}from"@dexterai/vault/session";var er=Uint8Array.from([56,67,4,209,238,143,0,129]),tr=74,ln=new Set([1,2]),nr=188,rr=new ne("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),ir=(()=>{let t=Buffer.alloc(32);return t.write("OTS_SESSION_REGISTER_V2","ascii"),t})(),be=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 be(t,e)}function M(t,e){try{return new ne(t)}catch{return m(e)}}function Me(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}async function or(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 sr(t,e,n,r){r.length!==tr&&m("binding_length"),Me(r.subarray(0,8),er)||m("binding_discriminator");let i=r.readUInt8(8),o=r.readUInt8(9);return ln.has(i)||m("binding_version"),o!==e&&m("binding_bump"),{address:t.toBase58(),owner:n.toBase58(),version:i,bump:o,swig:new ne(r.subarray(10,42)).toBase58(),vault:new ne(r.subarray(42,74)).toBase58()}}async function ar(t){let e=M(t.input.programId,"program_id"),n=M(t.input.buyerSwigAddress,"buyer_swig"),r=M(t.input.vaultPda,"vault_pda"),i=M(t.input.seller,"seller"),[o,s]=xt(n,e),[c]=Rt(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=Zn(Buffer.from(y.data)),f=Qn(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:sr(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:Ct(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 cr(t){let e=Buffer.from(t.voucher.sessionRegistration);return e.length!==nr&&m("registration_length"),Me(e.subarray(0,32),ir)||m("registration_domain"),{programId:new ne(e.subarray(32,64)).toBase58(),vaultPda:new ne(e.subarray(64,96)).toBase58(),sessionPublicKey:Ct(e.subarray(96,128)),maxAmount:e.readBigUInt64LE(128),expiresAt:e.readBigInt64LE(136),seller:new ne(e.subarray(144,176)).toBase58(),nonce:e.readUInt32LE(176),maxRevolvingCapacity:e.readBigUInt64LE(180)}}function ge(t,e,n){let r=t.accountKeys.filter(i=>i.address===e);return r.length!==1&&m(`${n}_account_key`),r[0]}function lr(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=M(t.programId,"program_id"),i=M(t.buyerSwigAddress,"buyer_swig"),o=M(t.vaultPda,"vault_pda"),s=M(t.seller,"seller"),c=M(t.sessionPda,"session_pda"),[l]=Rt(o,s,r),p=xt(i,r)[0],y=Yn(i),v=jn(r)[0];c.equals(l)||m("session_pda_derivation");let h=Buffer.from(Jn.settle_voucher),f=n.instructions.filter(a=>{if(a.programId!==t.programId)return!1;let x=a.data;return x.length>=h.length&&Me(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 ne(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 T=g.accounts[1];T||m("dexter_authority");let G=ge(n,g.accounts[0],"vault"),Z=ge(n,T,"dexter_authority"),re=ge(n,g.accounts[2],"session");(!G.writable||G.signer)&&m("vault_privileges"),Z.signer||m("dexter_authority_signature"),(!re.writable||re.signer)&&m("session_privileges");for(let a=3;a<Math.min(g.accounts.length,8);a+=1)ge(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=ge(n,g.accounts[a],`sibling_${a-8}`);(!x.writable||x.signer)&&m("settle_voucher_sibling_privileges")}let F=n.instructions[1];F.programId!==rr.toBase58()&&m("reservation_memo_program"),(F.accounts.length!==1||F.accounts[0]!==T)&&m("reservation_memo_authority"),ge(n,T,"reservation_memo_authority").signer||m("reservation_memo_authority_signature");let d=new TextEncoder().encode(sn(t));return Me(F.data,d)||m("reservation_memo_digest"),T}function ur(t,e,n,r){let i=M(t.programId,"program_id"),o=M(t.buyerSwigAddress,"buyer_swig"),s=M(t.vaultPda,"vault_pda"),c=M(t.seller,"seller"),[l,p]=xt(o,i),[y,v]=Rt(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||!ln.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!==Ct(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=cr(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 un(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!==Xn.toBase58()&&m("program_id");let i=await(r.readTransaction??or)({connection:t,signature:n.transaction,commitment:"confirmed"});i||m("transaction_missing"),i.confirmationStatus!=="confirmed"&&i.confirmationStatus!=="finalized"&&m("transaction_commitment");let o=lr(e,n,i),s=await(r.readPostState??ar)({connection:t,input:e,minimumSlot:i.slot,commitment:"confirmed"});return{...ur(e,i.slot,o,s),commitment:i.confirmationStatus}}import{deriveSessionPda as fr}from"@dexterai/vault/session";import{bytesToHex as Et}from"@noble/hashes/utils";var dr=15e3,mr=["claim_already_exists","non_monotonic_cumulative"],pr="below_lock_cadence";function De(t){return typeof t=="string"&&t.includes(pr)}function gr(t){return`${t.slice(0,16)}\u2026`}function dn(t,e,n,r){let i=gr(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(De(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(mr.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 Pt(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 dn(e,o.payload.cumulativeAmount,o.payload.sequenceNumber,c),c}let s=c=>(dn(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:Et(o.sessionPublicKey),sessionSignature:Et(o.sessionSignature),sessionRegistration:Et(o.sessionRegistration),network:r},p=await i(c,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(dr)}),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 mn(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 Pt(t,e,n,r,o.fetchImpl);return v.crystallized&&p!==void 0?(t.lastCrystallizedCumulativeAtomic=p,t.gateRefusedCumulativeAtomic=void 0):De(v.error)&&p!==void 0&&(t.gateRefusedCumulativeAtomic=p),v}var ce="x-tab-voucher",ze=class extends Error{constructor(){super("response terminated before tab admission completed"),this.name="ResponseTerminatedError"}};function yr(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 vr(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 Vt=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)}},Tt=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 se(this.cumulativeAtomic.toString())}deliveredCumulative(){return se(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 Ar(t){if(typeof t!="string"||t.length===0)throw new w("signature_invalid",`missing ${ce} 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:qe(n.sessionPublicKey),sessionRegistration:qe(n.sessionRegistration),sessionSignature:qe(n.sessionSignature)},reservationReceipt:n.reservationReceipt}}function qe(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 br(t){if(!/^[0-9a-f]{64}$/.test(t))throw new w("signature_invalid",`channelId must be canonical lowercase 64-char hex, got "${t}"`);return qe(t)}function It(t){let e=t.ledger??new Ae,n=yr(t.ledgerSafetyMode);vr(e,n);let r=J(t.leaseTtlMs??3e5),i=new Vt,o=typeof t.sellerPubkey=="string"?new hr(t.sellerPubkey):t.sellerPubkey,s=t.maxPerVoucherAtomic?BigInt(t.maxPerVoucherAtomic):BigInt(H(t.perUnit))*100n,c=t.facilitatorUrl??an,l={thresholdAtomic:t.lockCadence?.thresholdAtomic??H("0.10"),onClose:t.lockCadence?.onClose??!0};return async(p,y,v)=>{let h=null,f=null,g=null,S=null,P=null,T=!1,G=async()=>{if(P)throw P},Z=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}},re=()=>{T||(T=!0,setImmediate(()=>{Z().catch(_=>{console.error("[tab/seller] failed to release channel lease on response termination:",_)})}))},F=()=>{if(T)throw new ze};y.on("close",re),y.on("finish",re);try{let _=Ar(p.headers[ce]),d=_.voucher,a=d.payload.channelId,x=br(a),A=i.get(a),O=null,K,nt=!1;if(A){if(!ae(A.registrationBytes,d.sessionRegistration))throw new I("voucher registration does not match the channel's verified registration")}else{nt=!0;let u=Ue(d.sessionRegistration);te(u.nonce)===1&&(K=await yt(t.connection,u),O=K?.frontierAtomic??null);let C=await e.get(a);A={registration:u,registrationBytes:d.sessionRegistration.slice(),lastCumulativeAtomic:C?.lastVoucher?.payload.cumulativeAmount??"0"}}let q=te(A.registration.nonce),Bt=te(d.payload.sequenceNumber);if(Bt!==q)throw new w("wire_version_mismatch",`voucher is V${Bt}, active registration is V${q}`);let he;if(q===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");he=_.reservationReceipt}vt(d,x);let k=BigInt(d.payload.cumulativeAmount),j=BigInt(A.lastCumulativeAtomic),fe=null,X=null,rt=null;if(q===2){if(!he)throw new w("reservation_proof_missing","Native Tab V2 reservation proof was not carried through admission");if(X=Fe(he.reservationAmountAtomic,"receipt.reservationAmountAtomic"),X<=0n||X>k)throw new w("reservation_mismatch","reservation amount does not fit the voucher cumulative");let u=k-X,[C]=fr(A.registration.vaultPda,A.registration.allowedCounterparty,A.registration.programId),R=St(d);try{let U=await un(t.connection,{network:t.network,programId:A.registration.programId.toBase58(),buyerSwigAddress:he.buyerSwigAddress,vaultPda:A.registration.vaultPda.toBase58(),sessionPda:C.toBase58(),seller:A.registration.allowedCounterparty.toBase58(),channelId:a,sessionNonce:A.registration.nonce,reservationAmountAtomic:X.toString(),previousCumulativeAtomic:u.toString(),...R,voucher:d},he);K=U,O=U.frontierAtomic}catch(U){throw U instanceof be?new w("reservation_proof_invalid",U.message):U}if(K?.wireVersion!==2)throw new w("wire_version_mismatch",`active SessionAccount is V${K?.wireVersion??"unknown"}, voucher is V2`);if(K.sessionAccountVersion!==1||O===null||K.currentOutstandingAtomic===void 0)throw new w("reservation_mismatch","authoritative V2 SessionAccount reservation evidence is incomplete");let b=Fe(O,"frontierAtomic");if(b>j&&(j=b),k<=j)throw new w("voucher_already_covered",`cumulative ${k} is not above covered frontier ${j}`);fe=k-j;let B=Fe(K.currentOutstandingAtomic,"currentOutstandingAtomic");if(rt=B,B!==fe)throw new w("reservation_mismatch",`currentOutstanding ${B} does not equal voucher delta ${fe}`);if(X!==fe)throw new w("reservation_mismatch",`receipt reservation ${X} does not equal voucher delta ${fe}`)}let Cn=q===1&&k===j;Ke({registration:A.registration,voucher:d,expectedCounterparty:o,previousCumulativeAtomic:Cn?void 0:j.toString()});let ie=k-j;if(ie>s)throw new L("cumulative_exceeds_cap",`single voucher increment ${ie} exceeds maxPerVoucherAtomic ${s}`);if(nt){let u=i.get(a);if(u){if(!ae(u.registrationBytes,A.registrationBytes))throw new I("voucher registration lost the channel admission race to a different verified registration");if(BigInt(u.lastCumulativeAtomic)>BigInt(A.lastCumulativeAtomic))throw new L("non_monotonic","channel admission advanced while reservation proof was in flight");A=u}}F();let ye=await e.tryAcquireLease(a,r);if(!ye)throw new w("channel_busy","another stream is live on this channel; tabs serve one stream at a time");f={channelId:a,lease:ye,releaseStarted:!1},F();let Ut=Math.max(1,Math.floor(r/3)),Kt=async()=>{if(P)throw P;if(!f||f.releaseStarted)throw new D(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)};G=async()=>{if(P)throw P;if(!f||f.releaseStarted)throw new D(a);f.lease.heldUntilUnixMs-Date.now()<=Ut&&await Kt()},g=setInterval(()=>{Kt().catch(()=>{})},Ut),g.unref?.();let ve=await e.get(a);if(F(),ve?.lastVoucher&&!ae(ve.lastVoucher.sessionRegistration,d.sessionRegistration))throw new I("durable channel registration changed while reservation proof was in flight");let $t=BigInt(ve?.lastVoucher?.payload.cumulativeAmount??"0"),z=BigInt(A.lastCumulativeAtomic);if($t>z&&(z=$t),q===2&&O!==null){let u=Fe(O,"frontierAtomic");u>z&&(z=u)}let Mt=q===1&&k===z;if(k<z||q===2&&k===z)throw new w(q===2?"voucher_already_covered":"non_monotonic",`cumulative ${k} is not above post-lease covered frontier ${z}`);if(Mt){let u=ve?.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(Ke({registration:A.registration,voucher:d,expectedCounterparty:o,previousCumulativeAtomic:Mt?void 0:z.toString()}),ie=k-z,ie>s)throw new L("cumulative_exceeds_cap",`post-lease voucher increment ${ie} exceeds maxPerVoucherAtomic ${s}`);if(q===2&&(X===null||rt===null||X!==ie||rt!==ie))throw new w("reservation_mismatch","durable channel frontier advanced while reservation proof was in flight");if(j=z,nt){let u=i.get(a);if(u){if(!ae(u.registrationBytes,A.registrationBytes))throw await Z(),new I("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 it=async u=>{try{return await e.update(a,ye,u)}catch(C){if(!(C instanceof D))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)}}},xn=async u=>{let C=u.lastCrystallizedCumulativeAtomic??"0",R=u.gateRefusedCumulativeAtomic;await mn(u,a,c,t.network,l),(u.lastCrystallizedCumulativeAtomic!==C||u.gateRefusedCumulativeAtomic!==R)&&await it(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",ue=[b.gateRefusedCumulativeAtomic,u.gateRefusedCumulativeAtomic].filter(de=>de!==void 0).reduce((de,Gt)=>de===void 0||BigInt(Gt)>BigInt(de)?Gt:de,void 0);return{...b,lastCrystallizedCumulativeAtomic:B,gateRefusedCumulativeAtomic:ue!==void 0&&BigInt(ue)>BigInt(B)?ue: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)})},Dt=Promise.resolve(),Ft=u=>{let C=Dt.then(u,u);return Dt=C.catch(()=>{}),C},qt=!1,zt=()=>{!l.onClose||qt||(qt=!0,Ft(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 Pt(u,a,c,t.network);R.crystallized?await it(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}}):De(R.error)&&await it(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",zt),y.on("finish",zt);let Ne=ve,Ht=BigInt(Ne?.deliveredCumulativeAtomic??"0"),Rn=!Ne?.lastVoucher&&Ht===0n,ot=O===null?null:BigInt(O),le=ot!==null&&ot>Ht&&(q===2||Rn)?ot.toString():null;le!==null&&console.info(`[tab/seller] channel ${a.slice(0,16)}\u2026 resumed: seeding delivered baseline from chain frontier ${le} (session already settled/locked up to it \u2014 that span is not deliverable budget)`);let En=le!==null?BigInt(le):Ne?BigInt(Ne.deliveredCumulativeAtomic):0n;await e.update(a,ye,u=>({...u??{},lastVoucher:d,deliveredCumulativeAtomic:le??(u?u.deliveredCumulativeAtomic:"0"),lastCrystallizedCumulativeAtomic:le??u?.lastCrystallizedCumulativeAtomic??"0"})),h=null,F(),i.update(a,d.payload.cumulativeAmount);let Wt=new Tt(a,t.network,k,En,async u=>{await G();let C=null;C=await e.update(a,ye,R=>{if(!R?.lastVoucher||!wr(R.lastVoucher,d))throw new I("durable voucher identity changed before delivery accounting");let b=BigInt(R.deliveredCumulativeAtomic),B=BigInt(u),U=B>0n?b+B:b,ue=BigInt(R.lastVoucher.payload.cumulativeAmount);if(U>ue)throw new L("cumulative_exceeds_cap",`durable delivered cumulative ${U} exceeds signed cumulative ${ue}`);return{...R,lastVoucher:R.lastVoucher,deliveredCumulativeAtomic:U.toString(),lastCrystallizedCumulativeAtomic:R.lastCrystallizedCumulativeAtomic??"0"}}),C&&Ft(async()=>{let R=await e.get(a);R&&await xn(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.")});Wt.setSessionPublicKey(d.sessionPublicKey),p.tab=Wt,v()}catch(_){if(f&&!f.releaseStarted&&await Z().catch(d=>{console.error("[tab/seller] failed to release channel lease after request error:",d)}),h&&i.deleteIfSame(h.channelId,h.entry),_ instanceof ze)return;if(_ instanceof w||_ instanceof W||_ instanceof $||_ instanceof I||_ instanceof L){y.status(402).json({error:"invalid_voucher",reason:_.reason??"unknown",detail:_.message});return}v(_)}}}function ae(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 wr(t,e){return t.payload.channelId===e.payload.channelId&&t.payload.cumulativeAmount===e.payload.cumulativeAmount&&t.payload.sequenceNumber===e.payload.sequenceNumber&&ae(t.sessionPublicKey,e.sessionPublicKey)&&ae(t.sessionRegistration,e.sessionRegistration)&&ae(t.sessionSignature,e.sessionSignature)}function Fe(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 Sr(t){if(!t.tab)throw new Error("req.tab is missing \u2014 did tabMiddleware run on this route?");return t.tab}function _r(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(H(n.cumulative())),i=BigInt(H(n.deliveredCumulative())),o=r-i;o<0n&&(o=0n);let s=e.perUnit?BigInt(H(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 T=c+S;if(T>o)throw l=!0,new L("cumulative_exceeds_cap",`chunk would push delivered to ${se((i+T).toString())} beyond signed cumulative ${se(r.toString())} (per-request budget ${se(o.toString())})`);try{await n.recordDelivered(S.toString()),c=T}catch(G){throw l=!0,G}});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
+ `,Bn='return redis.call("get", KEYS[1])',ke=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 Le(t){return`${t.ownerToken}:${t.fence}`}function Oe(t){return t===1||t==="1"}var pt=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&&!Xt(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:Xt(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(Bn,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 ke(e)}async get(e){this.assertChannelId(e),await this.assertClusterCutover(e);let n=await this.primaryGet(this.ledgerKey(e));return n===null?null:mt(JSON.parse(n))}async writeIfOwned(e,n,r){let i=dt(n),o=await this.client.eval(Nn,2,this.leaseKey(e),this.ledgerKey(e),Le(r),JSON.stringify(i));if(!Oe(o))throw new D(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(Ln,2,this.leaseKey(e),this.ledgerKey(e),Le(n));if(!Oe(r))throw new D(e)})}async tryAcquireLease(e,n){return this.assertChannelId(e),E(e,async()=>{await this.assertClusterCutover(e);let r=Tn(),i=J(n),o=await this.client.eval(In,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(On,1,this.leaseKey(e),Le(n));return Oe(r)})}async renewLease(e,n,r){return this.assertChannelId(e),E(e,async()=>{let i=J(r),o=await this.client.eval(kn,1,this.leaseKey(e),Le(n),i);if(!Oe(o))throw new D(e);return{...n,heldUntilUnixMs:Date.now()+i}})}};import{PublicKey as hr}from"@solana/web3.js";import Kn from"tweetnacl";import{sha256 as yi}from"@noble/hashes/sha256";import{p256 as Ai}from"@noble/curves/p256";import{PublicKey as ht}from"@solana/web3.js";import{sessionRegisterMessage as Un,sessionReplaceV1Message as Zr,sessionRevokeMessage as Qr,sessionVoucherV2Nonce as ei,sessionVoucherV2AuthorizationNonce as ti,finalVoucherV2Sequence as ni,voucherV2SequenceOrdinal as ri,voucherPayloadMessage as gt,buildVoucherMessage as ii}from"@dexterai/vault/messages";import{buildRegisterSessionKeyInstruction as ai,buildRevokeSessionKeyInstruction as ci,deriveSwigWalletAddress as li}from"@dexterai/vault/instructions";import{buildSecp256r1VerifyInstruction as di}from"@dexterai/vault/precompile";import{DEXTER_VAULT_PROGRAM_ID as Be,SECP256R1_PROGRAM_ID as pi,INSTRUCTIONS_SYSVAR_ID as gi}from"@dexterai/vault/constants";import{decodeSessionAccount as $n,deriveSessionPda as Yt,isSessionLive as Mn}from"@dexterai/vault/session";import{contextBoundVoucherV2Message as Dn,sessionVoucherV2AuthorizationNonce as Fn,voucherV2SequenceOrdinal as qn}from"@dexterai/vault/messages";var ft="OTS_SESSION_REGISTER_V2";function te(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 Ue(t){if(t.length!==188)throw new W("wrong_length",`expected 188, got ${t.length}`);let e=new TextDecoder().decode(t.slice(0,ft.length));if(e!==ft)throw new W("wrong_domain",`got "${e}"`);for(let v=ft.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 ht(t.slice(32,64)),i=new ht(t.slice(64,96)),o=t.slice(96,128),s=n.getBigUint64(128,!0),c=n.getBigInt64(136,!0),l=new ht(t.slice(144,176)),p=n.getUint32(176,!0),y=n.getBigUint64(180,!0);if(!r.equals(Be))throw new W("wrong_program",`${r.toBase58()} is not ${Be.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 $=class extends Error{constructor(n,r){super(`On-chain verification failed: ${n}${r?` (${r})`:""}`);this.reason=n;this.name="OnChainVerificationError"}reason};async function yt(t,e){let[n]=Yt(e.vaultPda,e.allowedCounterparty,e.programId),r=await t.getAccountInfo(n,"finalized");if(!r)throw new $("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 $("wrong_program",`SessionAccount owner ${r.owner.toBase58()} != ${e.programId.toBase58()}`);let i;try{i=$n(n,r.data)}catch(h){throw new $("registration_state_mismatch",`finalized SessionAccount decode failed: ${h instanceof Error?h.message:String(h)}`)}if(i.version===0)throw new $("session_not_active","finalized SessionAccount is cleared");if(!Mn(i))throw new $("session_not_active","SessionAccount PDA is present but expired");if(!Zt(i.session.sessionPubkey,e.sessionPubkey))throw new $("session_pubkey_mismatch",`on-chain ${Jt(i.session.sessionPubkey)} != registration ${Jt(e.sessionPubkey)}`);let o=te(e.nonce),s=te(i.session.nonce);if(s!==o)throw new $("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 $("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 I=class extends Error{constructor(e){super(`Invalid voucher signature${e?`: ${e}`:""}`),this.name="InvalidVoucherSignatureError"}};function vt(t,e){if(e.length!==32)throw new I(`channelIdBytes must be 32 bytes, got ${e.length}`);if(t.sessionPublicKey.length!==32)throw new I(`sessionPublicKey must be 32 bytes, got ${t.sessionPublicKey.length}`);if(t.sessionSignature.length!==64)throw new I(`sessionSignature must be 64 bytes, got ${t.sessionSignature.length}`);let n=Ue(t.sessionRegistration);if(!Zt(n.sessionPubkey,t.sessionPublicKey))throw new I("registration session key does not match voucher session key");let r=n.nonce>=2147483648,i=te(n.nonce),o=te(t.payload.sequenceNumber);if(i!==o)throw new I(`voucher wire V${o} does not match registration wire V${i}`);let s;if(r){Fn(n.nonce),qn(t.payload.sequenceNumber);let[l]=Yt(n.vaultPda,n.allowedCounterparty,n.programId);s=Dn({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=gt({channelId:e,cumulativeAmount:BigInt(t.payload.cumulativeAmount),sequenceNumber:t.payload.sequenceNumber});if(!Kn.sign.detached.verify(s,t.sessionSignature,t.sessionPublicKey))throw new I("ed25519 verify rejected")}var L=class extends Error{constructor(n,r){super(`Scope violation: ${n}${r?` (${r})`:""}`);this.reason=n;this.name="ScopeViolationError"}reason};function Ke(t){let e=BigInt(t.voucher.payload.cumulativeAmount);if(e>t.registration.maxAmount)throw new L("cumulative_exceeds_cap",`${e} > ${t.registration.maxAmount}`);let n=BigInt(Math.floor(Date.now()/1e3));if(n>=t.registration.expiresAt)throw new L("session_expired",`now=${n} >= expiresAt=${t.registration.expiresAt}`);if(!t.registration.allowedCounterparty.equals(t.expectedCounterparty))throw new L("wrong_counterparty",`${t.registration.allowedCounterparty.toBase58()} != ${t.expectedCounterparty.toBase58()}`);if(t.previousCumulativeAtomic!==void 0){let r=BigInt(t.previousCumulativeAtomic);if(e<=r)throw new L("non_monotonic",`cumulative=${e} not > previous=${r}`)}}function Zt(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 Jt(t){let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}import{PublicKey as Qi}from"@solana/web3.js";import{bytesToHex as to}from"@noble/hashes/utils";import Vi from"tweetnacl";import{PublicKey as Ii}from"@solana/web3.js";import{contextBoundVoucherV2Message as Li,finalVoucherV2Sequence as Oi,sessionRegisterMessage as ki,sessionVoucherV2AuthorizationNonce as Bi}from"@dexterai/vault/messages";import{deriveSessionPda as Ki}from"@dexterai/vault/session";import{sha256 as Fi}from"@noble/hashes/sha256";var Mi=(1n<<64n)-1n;import{sha256 as nn}from"@noble/hashes/sha256";import{bytesToHex as pe}from"@noble/hashes/utils";var Qt=/^[0-9a-f]{64}$/,en=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/,zn=/^[1-9A-HJ-NP-Za-km-z]{32,100}$/,tn="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",rn="dexter-native-tab-v2-reservation/v1",Hn=`${rn}:`;function At(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(At);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,At(n)]));throw new Error("canonical_value_unsupported")}function on(t){return JSON.stringify(At(t))}function bt(t){if(t==="solana:mainnet"||t===tn)return tn;throw new Error("native_tab_v2_reservation_network_unsupported")}function wt(t){return pe(nn(new TextEncoder().encode(on({channelId:t.payload.channelId,cumulativeAmount:t.payload.cumulativeAmount,sequenceNumber:t.payload.sequenceNumber,sessionPublicKey:pe(t.sessionPublicKey),sessionSignature:pe(t.sessionSignature),sessionRegistration:pe(t.sessionRegistration)}))))}function St(t){let e=wt(t);return{voucherDigest:e,idempotencyKey:`native-tab-v2:${e}`}}function Wn(t){return pe(nn(new TextEncoder().encode(on({contract:rn,network:bt(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 Gn(t){let e=wt(t.voucher);return Wn({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 sn(t){return`${Hn}${Gn(t)}`}function N(t){throw new Error(`native_tab_v2_reservation_receipt_invalid:${t}`)}function $e(t,e){(!Number.isSafeInteger(t)||t<0)&&N(e)}function _t(t,e){(!e||typeof e!="object")&&N("missing");let n=wt(t.voucher);(!Qt.test(t.voucherDigest)||t.voucherDigest!==n)&&N("input_voucher_digest"),t.idempotencyKey!==`native-tab-v2:${n}`&&N("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)&&N("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)&&N("input_voucher_identity"),e.contract!=="dexter-native-tab-open-receipt/v1"&&e.contract!=="dexter-native-tab-open-receipt/v2"&&N("contract"),Qt.test(e.operationId)||N("operation_id"),en.test(e.callerOperationId)||N("caller_operation_id"),zn.test(e.transaction)||N("transaction"),e.commitment!=="confirmed"&&e.commitment!=="finalized"&&N("commitment"),$e(e.confirmationSlot,"confirmation_slot"),$e(e.postStateSlot,"post_state_slot"),(e.confirmationSlot===0||e.postStateSlot<e.confirmationSlot)&&N("post_state_slot");let s,c;try{s=bt(t.network),c=bt(e.network)}catch{return N("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!==pe(t.voucher.sessionPublicKey)||e.voucherDigest!==n||e.cumulativeAmountAtomic!==t.voucher.payload.cumulativeAmount||e.sequenceNumber!==t.voucher.payload.sequenceNumber||!en.test(e.providerReceiptId)||e.reservationAmountAtomic!==t.reservationAmountAtomic||e.currentOutstandingBeforeAtomic!=="0"||e.currentOutstandingAfterAtomic!==t.reservationAmountAtomic)&&N("economic_identity"),$e(e.pendingVoucherCountBefore,"pending_voucher_count_before"),$e(e.pendingVoucherCountAfter,"pending_voucher_count_after"),e.contract==="dexter-native-tab-open-receipt/v1"?e.callerOperationId!==t.idempotencyKey&&N("idempotency_key"):(e.rootOperationId!==t.idempotencyKey||!Number.isSafeInteger(e.generation)||Number(e.generation)<2||!e.predecessorCallerOperationId||!e.predecessorLifecycleOperationId||!e.predecessorReleaseDigest||!e.stableReservationId||!e.economicEffectDigest)&&N("successor_identity")}import{deriveSessionPda as so}from"@dexterai/vault/session";var an="https://x402.dexter.cash",cn=6;function H(t,e=cn){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 se(t,e=cn){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}import{PublicKey as ne}from"@solana/web3.js";import{bytesToHex as Ct}from"@noble/hashes/utils";import{deriveGraphConfigPda as jn,deriveSwigVaultBindingPda as xt}from"@dexterai/vault/credit";import{DEXTER_VAULT_PROGRAM_ID as Xn,DISCRIMINATORS as Jn,isSwigVaultBindingIdentityVersion as ln}from"@dexterai/vault/constants";import{deriveSwigWalletAddress as Yn}from"@dexterai/vault/instructions";import{decodeVaultFull as Zn}from"@dexterai/vault/reader";import{decodeSessionAccount as Qn,deriveSessionPda as Rt}from"@dexterai/vault/session";var er=Uint8Array.from([56,67,4,209,238,143,0,129]),tr=74,nr=188,rr=new ne("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),ir=(()=>{let t=Buffer.alloc(32);return t.write("OTS_SESSION_REGISTER_V2","ascii"),t})(),be=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 be(t,e)}function M(t,e){try{return new ne(t)}catch{return m(e)}}function Me(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}async function or(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 sr(t,e,n,r){r.length!==tr&&m("binding_length"),Me(r.subarray(0,8),er)||m("binding_discriminator");let i=r.readUInt8(8),o=r.readUInt8(9);return ln(i)||m("binding_version"),o!==e&&m("binding_bump"),{address:t.toBase58(),owner:n.toBase58(),version:i,bump:o,swig:new ne(r.subarray(10,42)).toBase58(),vault:new ne(r.subarray(42,74)).toBase58()}}async function ar(t){let e=M(t.input.programId,"program_id"),n=M(t.input.buyerSwigAddress,"buyer_swig"),r=M(t.input.vaultPda,"vault_pda"),i=M(t.input.seller,"seller"),[o,s]=xt(n,e),[c]=Rt(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=Zn(Buffer.from(y.data)),f=Qn(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:sr(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:Ct(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 cr(t){let e=Buffer.from(t.voucher.sessionRegistration);return e.length!==nr&&m("registration_length"),Me(e.subarray(0,32),ir)||m("registration_domain"),{programId:new ne(e.subarray(32,64)).toBase58(),vaultPda:new ne(e.subarray(64,96)).toBase58(),sessionPublicKey:Ct(e.subarray(96,128)),maxAmount:e.readBigUInt64LE(128),expiresAt:e.readBigInt64LE(136),seller:new ne(e.subarray(144,176)).toBase58(),nonce:e.readUInt32LE(176),maxRevolvingCapacity:e.readBigUInt64LE(180)}}function ge(t,e,n){let r=t.accountKeys.filter(i=>i.address===e);return r.length!==1&&m(`${n}_account_key`),r[0]}function lr(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=M(t.programId,"program_id"),i=M(t.buyerSwigAddress,"buyer_swig"),o=M(t.vaultPda,"vault_pda"),s=M(t.seller,"seller"),c=M(t.sessionPda,"session_pda"),[l]=Rt(o,s,r),p=xt(i,r)[0],y=Yn(i),v=jn(r)[0];c.equals(l)||m("session_pda_derivation");let h=Buffer.from(Jn.settle_voucher),f=n.instructions.filter(a=>{if(a.programId!==t.programId)return!1;let x=a.data;return x.length>=h.length&&Me(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 ne(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 T=g.accounts[1];T||m("dexter_authority");let G=ge(n,g.accounts[0],"vault"),Z=ge(n,T,"dexter_authority"),re=ge(n,g.accounts[2],"session");(!G.writable||G.signer)&&m("vault_privileges"),Z.signer||m("dexter_authority_signature"),(!re.writable||re.signer)&&m("session_privileges");for(let a=3;a<Math.min(g.accounts.length,8);a+=1)ge(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=ge(n,g.accounts[a],`sibling_${a-8}`);(!x.writable||x.signer)&&m("settle_voucher_sibling_privileges")}let F=n.instructions[1];F.programId!==rr.toBase58()&&m("reservation_memo_program"),(F.accounts.length!==1||F.accounts[0]!==T)&&m("reservation_memo_authority"),ge(n,T,"reservation_memo_authority").signer||m("reservation_memo_authority_signature");let d=new TextEncoder().encode(sn(t));return Me(F.data,d)||m("reservation_memo_digest"),T}function ur(t,e,n,r){let i=M(t.programId,"program_id"),o=M(t.buyerSwigAddress,"buyer_swig"),s=M(t.vaultPda,"vault_pda"),c=M(t.seller,"seller"),[l,p]=xt(o,i),[y,v]=Rt(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||!ln(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!==Ct(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=cr(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 un(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!==Xn.toBase58()&&m("program_id");let i=await(r.readTransaction??or)({connection:t,signature:n.transaction,commitment:"confirmed"});i||m("transaction_missing"),i.confirmationStatus!=="confirmed"&&i.confirmationStatus!=="finalized"&&m("transaction_commitment");let o=lr(e,n,i),s=await(r.readPostState??ar)({connection:t,input:e,minimumSlot:i.slot,commitment:"confirmed"});return{...ur(e,i.slot,o,s),commitment:i.confirmationStatus}}import{deriveSessionPda as fr}from"@dexterai/vault/session";import{bytesToHex as Et}from"@noble/hashes/utils";var dr=15e3,mr=["claim_already_exists","non_monotonic_cumulative"],pr="below_lock_cadence";function De(t){return typeof t=="string"&&t.includes(pr)}function gr(t){return`${t.slice(0,16)}\u2026`}function dn(t,e,n,r){let i=gr(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(De(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(mr.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 Pt(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 dn(e,o.payload.cumulativeAmount,o.payload.sequenceNumber,c),c}let s=c=>(dn(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:Et(o.sessionPublicKey),sessionSignature:Et(o.sessionSignature),sessionRegistration:Et(o.sessionRegistration),network:r},p=await i(c,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(dr)}),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 mn(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 Pt(t,e,n,r,o.fetchImpl);return v.crystallized&&p!==void 0?(t.lastCrystallizedCumulativeAtomic=p,t.gateRefusedCumulativeAtomic=void 0):De(v.error)&&p!==void 0&&(t.gateRefusedCumulativeAtomic=p),v}var ce="x-tab-voucher",ze=class extends Error{constructor(){super("response terminated before tab admission completed"),this.name="ResponseTerminatedError"}};function yr(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 vr(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 Vt=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)}},Tt=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 se(this.cumulativeAtomic.toString())}deliveredCumulative(){return se(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 Ar(t){if(typeof t!="string"||t.length===0)throw new w("signature_invalid",`missing ${ce} 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:qe(n.sessionPublicKey),sessionRegistration:qe(n.sessionRegistration),sessionSignature:qe(n.sessionSignature)},reservationReceipt:n.reservationReceipt}}function qe(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 br(t){if(!/^[0-9a-f]{64}$/.test(t))throw new w("signature_invalid",`channelId must be canonical lowercase 64-char hex, got "${t}"`);return qe(t)}function It(t){let e=t.ledger??new Ae,n=yr(t.ledgerSafetyMode);vr(e,n);let r=J(t.leaseTtlMs??3e5),i=new Vt,o=typeof t.sellerPubkey=="string"?new hr(t.sellerPubkey):t.sellerPubkey,s=t.maxPerVoucherAtomic?BigInt(t.maxPerVoucherAtomic):BigInt(H(t.perUnit))*100n,c=t.facilitatorUrl??an,l={thresholdAtomic:t.lockCadence?.thresholdAtomic??H("0.10"),onClose:t.lockCadence?.onClose??!0};return async(p,y,v)=>{let h=null,f=null,g=null,S=null,P=null,T=!1,G=async()=>{if(P)throw P},Z=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}},re=()=>{T||(T=!0,setImmediate(()=>{Z().catch(_=>{console.error("[tab/seller] failed to release channel lease on response termination:",_)})}))},F=()=>{if(T)throw new ze};y.on("close",re),y.on("finish",re);try{let _=Ar(p.headers[ce]),d=_.voucher,a=d.payload.channelId,x=br(a),A=i.get(a),O=null,K,nt=!1;if(A){if(!ae(A.registrationBytes,d.sessionRegistration))throw new I("voucher registration does not match the channel's verified registration")}else{nt=!0;let u=Ue(d.sessionRegistration);te(u.nonce)===1&&(K=await yt(t.connection,u),O=K?.frontierAtomic??null);let C=await e.get(a);A={registration:u,registrationBytes:d.sessionRegistration.slice(),lastCumulativeAtomic:C?.lastVoucher?.payload.cumulativeAmount??"0"}}let q=te(A.registration.nonce),Bt=te(d.payload.sequenceNumber);if(Bt!==q)throw new w("wire_version_mismatch",`voucher is V${Bt}, active registration is V${q}`);let he;if(q===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");he=_.reservationReceipt}vt(d,x);let k=BigInt(d.payload.cumulativeAmount),j=BigInt(A.lastCumulativeAtomic),fe=null,X=null,rt=null;if(q===2){if(!he)throw new w("reservation_proof_missing","Native Tab V2 reservation proof was not carried through admission");if(X=Fe(he.reservationAmountAtomic,"receipt.reservationAmountAtomic"),X<=0n||X>k)throw new w("reservation_mismatch","reservation amount does not fit the voucher cumulative");let u=k-X,[C]=fr(A.registration.vaultPda,A.registration.allowedCounterparty,A.registration.programId),R=St(d);try{let U=await un(t.connection,{network:t.network,programId:A.registration.programId.toBase58(),buyerSwigAddress:he.buyerSwigAddress,vaultPda:A.registration.vaultPda.toBase58(),sessionPda:C.toBase58(),seller:A.registration.allowedCounterparty.toBase58(),channelId:a,sessionNonce:A.registration.nonce,reservationAmountAtomic:X.toString(),previousCumulativeAtomic:u.toString(),...R,voucher:d},he);K=U,O=U.frontierAtomic}catch(U){throw U instanceof be?new w("reservation_proof_invalid",U.message):U}if(K?.wireVersion!==2)throw new w("wire_version_mismatch",`active SessionAccount is V${K?.wireVersion??"unknown"}, voucher is V2`);if(K.sessionAccountVersion!==1||O===null||K.currentOutstandingAtomic===void 0)throw new w("reservation_mismatch","authoritative V2 SessionAccount reservation evidence is incomplete");let b=Fe(O,"frontierAtomic");if(b>j&&(j=b),k<=j)throw new w("voucher_already_covered",`cumulative ${k} is not above covered frontier ${j}`);fe=k-j;let B=Fe(K.currentOutstandingAtomic,"currentOutstandingAtomic");if(rt=B,B!==fe)throw new w("reservation_mismatch",`currentOutstanding ${B} does not equal voucher delta ${fe}`);if(X!==fe)throw new w("reservation_mismatch",`receipt reservation ${X} does not equal voucher delta ${fe}`)}let Cn=q===1&&k===j;Ke({registration:A.registration,voucher:d,expectedCounterparty:o,previousCumulativeAtomic:Cn?void 0:j.toString()});let ie=k-j;if(ie>s)throw new L("cumulative_exceeds_cap",`single voucher increment ${ie} exceeds maxPerVoucherAtomic ${s}`);if(nt){let u=i.get(a);if(u){if(!ae(u.registrationBytes,A.registrationBytes))throw new I("voucher registration lost the channel admission race to a different verified registration");if(BigInt(u.lastCumulativeAtomic)>BigInt(A.lastCumulativeAtomic))throw new L("non_monotonic","channel admission advanced while reservation proof was in flight");A=u}}F();let ye=await e.tryAcquireLease(a,r);if(!ye)throw new w("channel_busy","another stream is live on this channel; tabs serve one stream at a time");f={channelId:a,lease:ye,releaseStarted:!1},F();let Ut=Math.max(1,Math.floor(r/3)),Kt=async()=>{if(P)throw P;if(!f||f.releaseStarted)throw new D(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)};G=async()=>{if(P)throw P;if(!f||f.releaseStarted)throw new D(a);f.lease.heldUntilUnixMs-Date.now()<=Ut&&await Kt()},g=setInterval(()=>{Kt().catch(()=>{})},Ut),g.unref?.();let ve=await e.get(a);if(F(),ve?.lastVoucher&&!ae(ve.lastVoucher.sessionRegistration,d.sessionRegistration))throw new I("durable channel registration changed while reservation proof was in flight");let $t=BigInt(ve?.lastVoucher?.payload.cumulativeAmount??"0"),z=BigInt(A.lastCumulativeAtomic);if($t>z&&(z=$t),q===2&&O!==null){let u=Fe(O,"frontierAtomic");u>z&&(z=u)}let Mt=q===1&&k===z;if(k<z||q===2&&k===z)throw new w(q===2?"voucher_already_covered":"non_monotonic",`cumulative ${k} is not above post-lease covered frontier ${z}`);if(Mt){let u=ve?.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(Ke({registration:A.registration,voucher:d,expectedCounterparty:o,previousCumulativeAtomic:Mt?void 0:z.toString()}),ie=k-z,ie>s)throw new L("cumulative_exceeds_cap",`post-lease voucher increment ${ie} exceeds maxPerVoucherAtomic ${s}`);if(q===2&&(X===null||rt===null||X!==ie||rt!==ie))throw new w("reservation_mismatch","durable channel frontier advanced while reservation proof was in flight");if(j=z,nt){let u=i.get(a);if(u){if(!ae(u.registrationBytes,A.registrationBytes))throw await Z(),new I("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 it=async u=>{try{return await e.update(a,ye,u)}catch(C){if(!(C instanceof D))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)}}},xn=async u=>{let C=u.lastCrystallizedCumulativeAtomic??"0",R=u.gateRefusedCumulativeAtomic;await mn(u,a,c,t.network,l),(u.lastCrystallizedCumulativeAtomic!==C||u.gateRefusedCumulativeAtomic!==R)&&await it(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",ue=[b.gateRefusedCumulativeAtomic,u.gateRefusedCumulativeAtomic].filter(de=>de!==void 0).reduce((de,Gt)=>de===void 0||BigInt(Gt)>BigInt(de)?Gt:de,void 0);return{...b,lastCrystallizedCumulativeAtomic:B,gateRefusedCumulativeAtomic:ue!==void 0&&BigInt(ue)>BigInt(B)?ue: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)})},Dt=Promise.resolve(),Ft=u=>{let C=Dt.then(u,u);return Dt=C.catch(()=>{}),C},qt=!1,zt=()=>{!l.onClose||qt||(qt=!0,Ft(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 Pt(u,a,c,t.network);R.crystallized?await it(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}}):De(R.error)&&await it(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",zt),y.on("finish",zt);let Ne=ve,Ht=BigInt(Ne?.deliveredCumulativeAtomic??"0"),Rn=!Ne?.lastVoucher&&Ht===0n,ot=O===null?null:BigInt(O),le=ot!==null&&ot>Ht&&(q===2||Rn)?ot.toString():null;le!==null&&console.info(`[tab/seller] channel ${a.slice(0,16)}\u2026 resumed: seeding delivered baseline from chain frontier ${le} (session already settled/locked up to it \u2014 that span is not deliverable budget)`);let En=le!==null?BigInt(le):Ne?BigInt(Ne.deliveredCumulativeAtomic):0n;await e.update(a,ye,u=>({...u??{},lastVoucher:d,deliveredCumulativeAtomic:le??(u?u.deliveredCumulativeAtomic:"0"),lastCrystallizedCumulativeAtomic:le??u?.lastCrystallizedCumulativeAtomic??"0"})),h=null,F(),i.update(a,d.payload.cumulativeAmount);let Wt=new Tt(a,t.network,k,En,async u=>{await G();let C=null;C=await e.update(a,ye,R=>{if(!R?.lastVoucher||!wr(R.lastVoucher,d))throw new I("durable voucher identity changed before delivery accounting");let b=BigInt(R.deliveredCumulativeAtomic),B=BigInt(u),U=B>0n?b+B:b,ue=BigInt(R.lastVoucher.payload.cumulativeAmount);if(U>ue)throw new L("cumulative_exceeds_cap",`durable delivered cumulative ${U} exceeds signed cumulative ${ue}`);return{...R,lastVoucher:R.lastVoucher,deliveredCumulativeAtomic:U.toString(),lastCrystallizedCumulativeAtomic:R.lastCrystallizedCumulativeAtomic??"0"}}),C&&Ft(async()=>{let R=await e.get(a);R&&await xn(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.")});Wt.setSessionPublicKey(d.sessionPublicKey),p.tab=Wt,v()}catch(_){if(f&&!f.releaseStarted&&await Z().catch(d=>{console.error("[tab/seller] failed to release channel lease after request error:",d)}),h&&i.deleteIfSame(h.channelId,h.entry),_ instanceof ze)return;if(_ instanceof w||_ instanceof W||_ instanceof $||_ instanceof I||_ instanceof L){y.status(402).json({error:"invalid_voucher",reason:_.reason??"unknown",detail:_.message});return}v(_)}}}function ae(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 wr(t,e){return t.payload.channelId===e.payload.channelId&&t.payload.cumulativeAmount===e.payload.cumulativeAmount&&t.payload.sequenceNumber===e.payload.sequenceNumber&&ae(t.sessionPublicKey,e.sessionPublicKey)&&ae(t.sessionRegistration,e.sessionRegistration)&&ae(t.sessionSignature,e.sessionSignature)}function Fe(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 Sr(t){if(!t.tab)throw new Error("req.tab is missing \u2014 did tabMiddleware run on this route?");return t.tab}function _r(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(H(n.cumulative())),i=BigInt(H(n.deliveredCumulative())),o=r-i;o<0n&&(o=0n);let s=e.perUnit?BigInt(H(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 T=c+S;if(T>o)throw l=!0,new L("cumulative_exceeds_cap",`chunk would push delivered to ${se((i+T).toString())} beyond signed cumulative ${se(r.toString())} (per-request budget ${se(o.toString())})`);try{await n.recordDelivered(S.toString()),c=T}catch(G){throw l=!0,G}});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}"}
@@ -1,4 +1,4 @@
1
- import { W as WalletSet } from './types-BvQpNtFw.js';
1
+ import { W as WalletSet } from './types-C08JT9MG.js';
2
2
  import { T as Tab } from './types-D0IFR4Ro.js';
3
3
 
4
4
  /**
@@ -1,238 +1,4 @@
1
- /**
2
- * x402 v2 SDK — Shared Types
3
- *
4
- * Chain-agnostic types for x402 v2 payments.
5
- * Works with Solana, Base, and any future x402-compatible networks.
6
- */
7
-
8
- /**
9
- * Context passed to a PayToProvider function.
10
- * Contains request-scoped information for dynamic address resolution.
11
- */
12
- interface PayToContext {
13
- /** The PAYMENT-SIGNATURE header value (present on retry/verify, undefined on initial 402) */
14
- paymentHeader?: string;
15
- /** Amount in atomic units (e.g., '10000' for 0.01 USDC) */
16
- amountAtomic?: string;
17
- /** The resource URL being accessed */
18
- resourceUrl?: string;
19
- }
20
- /**
21
- * Optional defaults a PayToProvider can advertise for auto-configuration.
22
- * Attached as `_x402Defaults` on the provider function.
23
- */
24
- interface PayToProviderDefaults {
25
- /** Default CAIP-2 network (e.g., 'eip155:8453' for Base) */
26
- network?: string;
27
- /** Default facilitator URL */
28
- facilitatorUrl?: string;
29
- }
30
- /**
31
- * A function that dynamically resolves a payment address.
32
- * Used for providers like Stripe that generate per-request deposit addresses.
33
- *
34
- * @example
35
- * ```typescript
36
- * import { stripePayTo } from '@dexterai/x402/server';
37
- *
38
- * const provider = stripePayTo(process.env.STRIPE_SECRET_KEY);
39
- * const address = await provider({ amountAtomic: '10000' });
40
- * ```
41
- */
42
- type PayToProvider = ((context: PayToContext) => Promise<string>) & {
43
- /** Auto-configuration defaults (set by provider factories like stripePayTo) */
44
- _x402Defaults?: PayToProviderDefaults;
45
- };
46
- /**
47
- * Resource info included in payment requirements
48
- */
49
- interface ResourceInfo {
50
- /** Resource URL */
51
- url: string;
52
- /** Human-readable description */
53
- description?: string;
54
- /** MIME type of the resource */
55
- mimeType?: string;
56
- }
57
- /**
58
- * Extra fields in payment requirements
59
- * Chain-specific fields may vary
60
- */
61
- interface AcceptsExtra {
62
- /** Facilitator address that pays tx fees (required for Solana) */
63
- feePayer?: string;
64
- /** Token decimals (optional - defaults to 6 for USDC) */
65
- decimals?: number;
66
- /** EIP-712: Token name (EVM only) */
67
- name?: string;
68
- /** EIP-712: Token version (EVM only) */
69
- version?: string;
70
- /**
71
- * batch-settlement: on-chain authorizer that the escrow channel pays into.
72
- * Provided by the facilitator's batch-settlement kind. EVM only.
73
- */
74
- receiverAuthorizer?: string;
75
- /** Tab seller-wire header advertised by the default hosted scheme. */
76
- voucherHeader?: string;
77
- /** Tab registration encoding carried inside each seller voucher. */
78
- registrationEncoding?: string;
79
- /** Immutable commercial-terms version for this Tab offer. */
80
- termsVersion?: string;
81
- /** Event that makes usage accepted under the advertised terms version. */
82
- acceptanceRule?: string;
83
- /** Additional chain-specific fields */
84
- [key: string]: unknown;
85
- }
86
- /**
87
- * A single payment option in the accepts array
88
- */
89
- interface PaymentAccept {
90
- /** x402 version (1 or 2, defaults to 2 if not specified) */
91
- x402Version?: 1 | 2;
92
- /**
93
- * Payment scheme: 'exact' for EIP-3009 chains, 'exact-approval' for
94
- * approval-based chains like BSC, 'batch-settlement' for the EVM
95
- * escrow-channel batching scheme (discrete API purchases, gas-amortized),
96
- * 'tab' (SVM only) for streaming session-key vouchers against an
97
- * on-chain vault.
98
- */
99
- scheme: 'exact' | 'exact-approval' | 'batch-settlement' | 'tab';
100
- /** CAIP-2 network identifier (v1: 'solana', v2: 'solana:5eykt...') */
101
- network: string;
102
- /** Payment amount in atomic units (x402 v2 spec field) */
103
- amount: string;
104
- /** @deprecated v1 field — use `amount` instead. Kept for backwards compatibility with v1 data. */
105
- maxAmountRequired?: string;
106
- /** Token address */
107
- asset: string;
108
- /** Seller's address to receive payment */
109
- payTo: string;
110
- /** Maximum seconds until payment expires */
111
- maxTimeoutSeconds: number;
112
- /** Chain-specific extra data */
113
- extra?: AcceptsExtra;
114
- }
115
- /**
116
- * Full PaymentRequired structure (sent in PAYMENT-REQUIRED header)
117
- */
118
- interface PaymentRequired {
119
- /** x402 version (always 2) */
120
- x402Version: 2;
121
- /** Resource being accessed */
122
- resource: ResourceInfo;
123
- /** Available payment options */
124
- accepts: PaymentAccept[];
125
- /** Optional error message */
126
- error?: string;
127
- /** Protocol extensions */
128
- extensions?: Record<string, unknown>;
129
- }
130
- /**
131
- * Response from /verify endpoint
132
- */
133
- interface VerifyResponse {
134
- /** Whether the payment is valid */
135
- isValid: boolean;
136
- /** Reason for invalidity (if invalid) */
137
- invalidReason?: string;
138
- /** Payer address */
139
- payer?: string;
140
- }
141
- /**
142
- * Response from /settle endpoint
143
- */
144
- interface SettleResponse {
145
- /** Whether settlement succeeded */
146
- success: boolean;
147
- /** Transaction signature/hash */
148
- transaction?: string;
149
- /** Network the payment was made on */
150
- network: string;
151
- /** Error reason (if failed) */
152
- errorReason?: string;
153
- /** Error code (if failed) */
154
- errorCode?: string;
155
- /** Payer address */
156
- payer?: string;
157
- /** Protocol extensions returned by the facilitator (e.g., sponsored-access recommendations) */
158
- extensions?: Record<string, unknown>;
159
- }
160
- /**
161
- * A single access pass tier offered by a seller
162
- */
163
- interface AccessPassTier {
164
- /** Tier ID (e.g., '1h', '24h') */
165
- id: string;
166
- /** Human-readable label (e.g., '1 hour') */
167
- label: string;
168
- /** Duration in seconds */
169
- seconds: number;
170
- /** Price in USD (e.g., '0.50') */
171
- price: string;
172
- /** Price in atomic units (e.g., '500000') */
173
- priceAtomic: string;
174
- }
175
- /**
176
- * Access pass info returned in X-ACCESS-PASS-TIERS header
177
- */
178
- interface AccessPassInfo {
179
- /** Available tiers (if tier-based pricing) */
180
- tiers?: AccessPassTier[];
181
- /** Rate per hour in USD (if custom duration pricing) */
182
- ratePerHour?: string;
183
- /** Pass issuer identifier */
184
- issuer?: string;
185
- }
186
- /**
187
- * JWT claims inside an access pass token
188
- */
189
- interface AccessPassClaims {
190
- /** Subject — always 'x402-access-pass' */
191
- sub: string;
192
- /** Tier ID or 'custom' */
193
- tier: string;
194
- /** Duration in seconds */
195
- duration: number;
196
- /** Issued at (unix seconds) */
197
- iat: number;
198
- /** Expires at (unix seconds) */
199
- exp: number;
200
- /** Payer wallet address */
201
- payer: string;
202
- /** Network used for payment */
203
- network: string;
204
- /** Issuer identifier */
205
- iss: string;
206
- }
207
- /**
208
- * Client-side access pass configuration
209
- */
210
- interface AccessPassClientConfig {
211
- /** Enable access pass mode (default: true when this config is present) */
212
- enabled?: boolean;
213
- /** Preferred tier ID (e.g., '1h') — pick this tier if available */
214
- preferTier?: string;
215
- /** Preferred custom duration in seconds (e.g., 3600) */
216
- preferDuration?: number;
217
- /** Maximum amount willing to spend in USD (e.g., '2.00') */
218
- maxSpend?: string;
219
- /** Auto-renew expired passes (default: true) */
220
- autoRenew?: boolean;
221
- }
222
- /**
223
- * SDK error codes
224
- */
225
- type X402ErrorCode = 'missing_payment_required_header' | 'invalid_payment_required' | 'unsupported_network' | 'no_matching_payment_option' | 'missing_fee_payer' | 'missing_decimals' | 'missing_amount' | 'amount_exceeds_max' | 'insufficient_balance' | 'wallet_missing_sign_transaction' | 'wallet_not_connected' | 'wallet_disconnected' | 'user_rejected_signature' | 'transaction_build_failed' | 'payment_rejected' | 'rpc_timeout' | 'facilitator_timeout' | 'invalid_payment_signature' | 'facilitator_verify_failed' | 'facilitator_settle_failed' | 'facilitator_request_failed' | 'no_matching_requirement' | 'access_pass_expired' | 'access_pass_invalid' | 'access_pass_tier_not_found' | 'access_pass_exceeds_max_spend';
226
- /**
227
- * Custom error class for x402 operations
228
- */
229
- declare class X402Error extends Error {
230
- /** Error code for programmatic handling */
231
- code: X402ErrorCode;
232
- /** Additional error details */
233
- details?: unknown;
234
- constructor(code: X402ErrorCode, message: string, details?: unknown);
235
- }
1
+ import { P as PaymentAccept } from './types-DolSK-3d.js';
236
2
 
237
3
  /**
238
4
  * EVM Chain Adapter
@@ -645,4 +411,4 @@ interface BalanceInfo {
645
411
  asset: string;
646
412
  }
647
413
 
648
- export { type AdapterConfig as A, type BalanceInfo as B, type ChainAdapter as C, EvmAdapter as E, type GenericWallet as G, type PaymentAccept as P, SolanaAdapter as S, type VerifyResponse as V, type WalletSet as W, X402Error as X, type EvmWallet as a, type SignedTransaction as b, type SolanaWallet as c, createEvmAdapter as d, createSolanaAdapter as e, isSolanaWallet as f, type SettlementProbe as g, type AccessPassClientConfig as h, isEvmWallet as i, type AccessPassInfo as j, type AccessPassTier as k, type SettleResponse as l, type PaymentRequired as m, type PayToProvider as n, type AccessPassClaims as o, type PayToContext as p, type PayToProviderDefaults as q };
414
+ export { type AdapterConfig as A, type BalanceInfo as B, type ChainAdapter as C, EvmAdapter as E, type GenericWallet as G, SolanaAdapter as S, type WalletSet as W, type EvmWallet as a, type SignedTransaction as b, type SolanaWallet as c, createEvmAdapter as d, createSolanaAdapter as e, isSolanaWallet as f, type SettlementProbe as g, isEvmWallet as i };
@@ -1,6 +1,6 @@
1
1
  import { RequestHandler } from 'express';
2
2
  import { ChannelStorage } from '@x402/evm/batch-settlement/server';
3
- import { b as CloseReceipt } from './types-DwVhPqOZ.js';
3
+ import { b as CloseReceipt } from './types-DjDjuUc6.js';
4
4
 
5
5
  /**
6
6
  * Result of closing one channel from the seller side. Either a settlement