@dexterai/x402 5.4.2 → 6.0.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -4
- package/REFERENCE.md +79 -8
- package/dist/adapters/index.d.cts +3 -3
- package/dist/adapters/index.d.ts +3 -3
- package/dist/batch-settlement/index.d.cts +3 -3
- package/dist/batch-settlement/index.d.ts +3 -3
- package/dist/batch-settlement/seller/index.d.cts +4 -4
- package/dist/batch-settlement/seller/index.d.ts +4 -4
- package/dist/client/index.cjs +1 -1
- package/dist/client/index.d.cts +6 -6
- package/dist/client/index.d.ts +6 -6
- package/dist/client/index.js +1 -1
- package/dist/{constants-Icc4CXNG.d.cts → constants-BLvApMMl.d.cts} +1 -1
- package/dist/{constants-Icc4CXNG.d.ts → constants-BLvApMMl.d.ts} +1 -1
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.cts +4 -4
- package/dist/react/index.d.ts +4 -4
- package/dist/react/index.js +1 -1
- package/dist/server/index.cjs +1 -1
- package/dist/server/index.d.cts +5 -5
- package/dist/server/index.d.ts +5 -5
- package/dist/server/index.js +1 -1
- package/dist/{sessions-BG2OYLBi.d.cts → sessions-rPdO1CgK.d.cts} +35 -3
- package/dist/{sessions-BG2OYLBi.d.ts → sessions-rPdO1CgK.d.ts} +35 -3
- package/dist/tab/adapters/solana/index.cjs +1 -1
- package/dist/tab/adapters/solana/index.d.cts +178 -26
- package/dist/tab/adapters/solana/index.d.ts +178 -26
- package/dist/tab/adapters/solana/index.js +1 -1
- package/dist/tab/index.cjs +5 -5
- package/dist/tab/index.d.cts +117 -16
- package/dist/tab/index.d.ts +117 -16
- package/dist/tab/index.js +4 -4
- package/dist/tab/seller/index.cjs +3 -3
- package/dist/tab/seller/index.d.cts +4 -4
- package/dist/tab/seller/index.d.ts +4 -4
- package/dist/tab/seller/index.js +3 -3
- package/dist/{types-CSuISjXA.d.cts → types-45M9fb5M.d.cts} +109 -6
- package/dist/{types-CSuISjXA.d.ts → types-45M9fb5M.d.ts} +109 -6
- package/dist/{types-BdS_uvNs.d.cts → types-BbvuPNXl.d.cts} +2 -2
- package/dist/{types-Co5YYhVB.d.ts → types-BhXu7cgi.d.ts} +3 -3
- package/dist/{types-xQu1U4xk.d.cts → types-BvQpNtFw.d.cts} +9 -1
- package/dist/{types-xQu1U4xk.d.ts → types-BvQpNtFw.d.ts} +9 -1
- package/dist/{types-CZHPdVkg.d.cts → types-C6z04Mxr.d.cts} +3 -3
- package/dist/{types-DY8xKheW.d.ts → types-CkcNYx1Q.d.ts} +2 -2
- package/dist/{types-_wdHzVG-.d.ts → types-DwVhPqOZ.d.ts} +2 -2
- package/dist/{types-WMqs5xII.d.cts → types-JpkrtFbZ.d.cts} +2 -2
- package/dist/utils/index.d.cts +1 -1
- package/dist/utils/index.d.ts +1 -1
- package/dist/{x402-client-BQKDeNxq.d.cts → x402-client-B8zdDeat.d.cts} +2 -2
- package/dist/{x402-client-BQKDeNxq.d.ts → x402-client-B8zdDeat.d.ts} +2 -2
- package/package.json +7 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var me=Object.create;var M=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var ye=Object.getOwnPropertyNames;var ge=Object.getPrototypeOf,he=Object.prototype.hasOwnProperty;var Ae=(e,t)=>{for(var n in t)M(e,n,{get:t[n],enumerable:!0})},Y=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ye(t))!he.call(e,i)&&i!==n&&M(e,i,{get:()=>t[i],enumerable:!(s=de(t,i))||s.enumerable});return e};var q=(e,t,n)=>(n=e!=null?me(ge(e)):{},Y(t||!e||!e.__esModule?M(n,"default",{value:e,enumerable:!0}):n,e)),fe=e=>Y(M({},"__esModule",{value:!0}),e);var Ie={};Ae(Ie,{LiveSessionExistsError:()=>R,TX_SIZE_LIMIT_BYTES:()=>$,buildAdapterRegisterInstruction:()=>pe,collectAltAddresses:()=>F,compileComposeV0:()=>J,createSelfPayingComposeSend:()=>N,createSolanaVaultAdapter:()=>Te,deriveChannelId:()=>te,passkeySignerFromP256Keypair:()=>ce});module.exports=fe(Ie);var v=require("@solana/web3.js");var R=class extends Error{constructor(n){super(`a LIVE session already exists for counterparty ${n.allowedCounterparty} (session ${n.sessionPubkeyHex.slice(0,16)}\u2026, expires ${n.expiresAtUnix}; on-chain spent=${n.spentAtomic}, crystallized=${n.crystallizedCumulativeAtomic}, frontier=${n.frontierAtomic}). Replacing it voids any signed-but-unsettled vouchers beyond the frontier. Settle the old tab first (tab.close() or POST its last voucher to /tab/settle), or pass onLiveSession: 'replace' to atomically revoke-then-register over it.`);this.details=n;this.name="LiveSessionExistsError"}};var O=require("@dexterai/vault/instructions"),V=require("@dexterai/vault/precompile"),I=require("@dexterai/vault/constants");var P=require("@dexterai/vault/messages");var z=q(require("tweetnacl"),1);var ee=require("@noble/hashes/sha256");function G(){let e=z.default.sign.keyPair();return{publicKey:e.publicKey,privateKey:e.secretKey}}function Z(e,t,n){return{publicKey:e.publicKey,privateKey:e.privateKey,scope:t,registration:n}}function Q(e,t,n){if(n.length!==32)throw new Error(`channelIdBytes must be 32 bytes, got ${n.length}`);let s=BigInt(t.cumulativeAmount),i=BigInt(e.scope.maxAmountAtomic);if(s>i)throw new Error(`voucher cumulative ${s} exceeds session cap ${i}`);let m=Math.floor(Date.now()/1e3);if(m>=e.scope.expiresAtUnix)throw new Error(`session expired at ${e.scope.expiresAtUnix}, now ${m}`);let r=(0,P.voucherPayloadMessage)({channelId:n,cumulativeAmount:s,sequenceNumber:t.sequenceNumber}),a=z.default.sign.detached(r,e.privateKey);return{payload:t,sessionPublicKey:e.publicKey,sessionRegistration:e.registration,sessionSignature:a}}function E(e){if(!/^\d+$/.test(e))throw new Error(`atomic amount must be a non-negative integer string, got "${e}"`);return BigInt(e)}function te(e){let t=new Uint8Array(8);new DataView(t.buffer).setBigUint64(0,e.nonce,!0);let n=new TextEncoder().encode(e.sellerUrl),s=ee.sha256.create();return s.update(e.vaultPda.toBytes()),s.update(n),s.update(t),s.digest()}var g=require("@dexterai/vault/session"),W=require("@noble/hashes/sha256"),ue=require("@noble/hashes/utils");var f=require("@solana/web3.js"),$=1232,Se=40,ne=20,se=4,be=20,_=1e4,we=1e6,B=4,L="[tab/solana/compose]";function F(e,t){let n=new Set,s=[],i=t.toBase58();for(let m of e)for(let r of m.keys){if(r.isSigner)continue;let a=r.pubkey.toBase58();a===i||n.has(a)||(n.add(a),s.push(r.pubkey))}return s}function J(e,t,n,s){let i=new f.TransactionMessage({payerKey:t,recentBlockhash:n,instructions:e}).compileToV0Message([s]);return new f.VersionedTransaction(i)}async function ie(e){try{let t=(await e.getRecentPrioritizationFees()).map(s=>s.prioritizationFee).filter(s=>s>0).sort((s,i)=>s-i);if(t.length===0)return _;let n=t[Math.floor(.75*(t.length-1))]??_;return Math.max(_,Math.min(n,we))}catch{return _}}function Pe(e){let t=e,n=String(t?.message??e??""),s=Array.isArray(t?.logs)?t.logs.join(" "):"";return/already in use/i.test(n)||/already in use/i.test(s)}function oe(e){let t=e;return(Array.isArray(t?.logs)?t.logs:[]).length===0&&/block height exceeded|has expired|blockhash not found/i.test(String(t?.message??e))}var H=e=>new Promise(t=>setTimeout(t,e));function N(e,t,n={}){let s=n.commitment??"confirmed",i=n.altWarmupPollMs??400,m=n.altReadbackPollMs??400,r=n.altCollisionPollMs??500,a=null,l=null;async function d(p,u){let c=await ie(e),b=[f.ComputeBudgetProgram.setComputeUnitPrice({microLamports:c}),...p],S;for(let y=0;y<B;y+=1){let{blockhash:A,lastValidBlockHeight:C}=await e.getLatestBlockhash(s),w=new f.Transaction().add(...b);w.feePayer=t.publicKey,w.recentBlockhash=A,w.sign(t);try{let o=await e.sendRawTransaction(w.serialize(),{skipPreflight:!1,maxRetries:5}),k=await e.confirmTransaction({signature:o,blockhash:A,lastValidBlockHeight:C},s);if(k.value.err)throw new Error(`${u} tx failed on-chain: ${JSON.stringify(k.value.err)}`);return o}catch(o){if(oe(o)&&y<B-1){console.warn(`${L} ${u} tx expired before landing (attempt ${y+1}) \u2014 rebroadcasting with a fresh blockhash`),S=o;continue}throw o}}throw S??new Error(`${u} tx did not land after rebroadcast attempts`)}async function K(p){for(let u=0;u<be;u+=1){let c=await e.getSlot("finalized");if(c>p)return c;await H(r)}throw new Error(`ALT collision retry: finalized slot never advanced past ${p}`)}async function h(p){for(let u=0;u<Se;u+=1){if(await e.getSlot(s)>p)return;await H(i)}throw new Error(`ALT warmup timed out: preflight (${s}) slot never passed lastExtendedSlot ${p}`)}async function x(p){if(a)return a;let u=F(p,t.publicKey),c=null,b=null,S=-1;for(let A=0;A<se;A+=1){let C=S<0?await e.getSlot("finalized"):await K(S),[w,o]=f.AddressLookupTableProgram.createLookupTable({authority:t.publicKey,payer:t.publicKey,recentSlot:C}),k=f.AddressLookupTableProgram.extendLookupTable({payer:t.publicKey,authority:t.publicKey,lookupTable:o,addresses:u});try{b=await d([w,k],"ALT create/extend"),c=o;break}catch(j){if(Pe(j)&&A<se-1){S=C,console.warn(`${L} ALT address collision at slot ${C} (attempt ${A+1}) \u2014 retrying create with a fresh finalized slot`);continue}throw j}}if(!c||!b)throw new Error("ALT create exhausted retries after repeated address collisions");let y=await e.getAddressLookupTable(c);for(let A=0;A<ne&&!y.value;A+=1)await H(m),y=await e.getAddressLookupTable(c);if(!y.value)throw new Error(`ALT ${c.toBase58()} not visible after ${ne} read polls (${b})`);return await h(y.value.state.lastExtendedSlot),a=y.value,l=c,console.info(`${L} ephemeral compose ALT ready: ${c.toBase58()} (${u.length} addresses, createTx ${b})`),a}async function T(p){let u=await ie(e),c=[f.ComputeBudgetProgram.setComputeUnitPrice({microLamports:u}),...p],b=await x(c),S;for(let y=0;y<B;y+=1){let{blockhash:A,lastValidBlockHeight:C}=await e.getLatestBlockhash(s),w;try{let o=J(c,t.publicKey,A,b);o.sign([t]),w=o.serialize()}catch(o){throw/overrun|too large/i.test(String(o?.message??o))?new Error(`composed revoke-then-register v0 tx exceeds the ${$}B wire cap \u2014 too many sibling PDAs outside the lookup table`):o}if(w.length>$)throw new Error(`composed revoke-then-register v0 tx ${w.length}B exceeds the ${$}B wire cap \u2014 too many sibling PDAs outside the lookup table`);try{let o=await e.sendRawTransaction(w,{skipPreflight:!1,maxRetries:5}),k=await e.confirmTransaction({signature:o,blockhash:A,lastValidBlockHeight:C},s);if(k.value.err)throw new Error(`composed tx failed on-chain: ${JSON.stringify(k.value.err)}`);return o}catch(o){if(oe(o)&&y<B-1){console.warn(`${L} compose tx expired before landing (attempt ${y+1}, priorityFee ${u}) \u2014 rebroadcasting with a fresh blockhash`),S=o;continue}let k=Array.isArray(o?.logs)?o.logs:[];throw k.length?new Error(`${o?.message??o} | ${k.join(" | ")}`):o}}throw S instanceof Error?S:new Error("compose tx did not land after rebroadcast attempts")}async function U(){if(l)try{let p=f.AddressLookupTableProgram.deactivateLookupTable({lookupTable:l,authority:t.publicKey}),u=await d([p],"ALT deactivate");console.info(`${L} ephemeral compose ALT deactivated: ${l.toBase58()} (${u}) \u2014 rent reclaimable via close_lookup_table after the deactivation cooldown`)}catch(p){console.warn(`${L} ALT deactivate failed for ${l?.toBase58()} \u2014 rent parks until a later cleanup retries (the compose already landed): ${String(p?.message??p)}`)}}return{send:T,getAltAddress:()=>l,deactivateAlt:U}}var re=require("@noble/curves/p256"),D=require("@noble/hashes/sha256"),ae="dexter.cash";function ve(e){return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function xe(e,t=`https://${ae}`){let s={type:"webauthn.get",challenge:ve(e),origin:t,crossOrigin:!1};return new TextEncoder().encode(JSON.stringify(s))}function ke(e=1){let t=(0,D.sha256)(new TextEncoder().encode(ae)),n=new Uint8Array(37);return n.set(t,0),n[32]=5,new DataView(n.buffer).setUint32(33,e,!1),n}function Ke(e,t){let n=xe(t),s=ke(1),i=new Uint8Array(s.length+32);i.set(s,0),i.set((0,D.sha256)(n),s.length);let m=(0,D.sha256)(i);return{signature:re.p256.sign(m,e.privateKey,{lowS:!0}).toCompactRawBytes(),clientDataJSON:n,authenticatorData:s}}function ce(e){return{credentialId:new Uint8Array(0),publicKey:e.publicKey,signOperation:async t=>Ke(e,(0,D.sha256)(t))}}function pe(e){return(0,O.buildRegisterSessionKeyInstruction)({vaultPda:e.vaultPda,sessionPubkey:e.sessionPubkey,maxAmount:e.maxAmount,maxRevolvingCapacity:e.maxRevolvingCapacity,expiresAt:e.expiresAt,allowedCounterparty:e.allowedCounterparty,nonce:e.nonce,swigAddress:e.swigAddress,vaultUsdcAta:e.vaultUsdcAta,clientDataJSON:e.clientDataJSON,authenticatorData:e.authenticatorData,payer:e.payer,siblingSessionPdas:e.siblingSessionPdas})}var X=class{network="solana:mainnet";swigAddress;vaultPda;connection;vaultPdaKey;passkey;feePayer;confirmOptions;seams;constructor(t){this.connection=t.connection,this.swigAddress=typeof t.swigAddress=="string"?t.swigAddress:t.swigAddress.toBase58(),this.vaultPdaKey=typeof t.vaultPda=="string"?new v.PublicKey(t.vaultPda):t.vaultPda,this.vaultPda=this.vaultPdaKey.toBase58(),this.passkey=t.passkeySigner,this.feePayer=t.feePayer,this.confirmOptions=t.confirmOptions??{commitment:"confirmed"},this.seams=t.seams??{}}async authorizeSession(t,n){let s=new v.PublicKey(t.allowedCounterparty),i=E(t.revolvingCapacityAtomic??t.maxAmountAtomic),r=await(this.seams.fetchSession??g.fetchSessionAccount)(this.connection,this.vaultPdaKey,s),a=r!==null&&(0,g.isSessionLive)(r);if(a&&(n?.onLiveSession??"error")!=="replace"){let T=r.session.spent,U=r.session.crystallizedCumulative;throw new R({allowedCounterparty:t.allowedCounterparty,sessionPubkeyHex:(0,ue.bytesToHex)(r.session.sessionPubkey),expiresAtUnix:r.session.expiresAt,spentAtomic:T.toString(),crystallizedCumulativeAtomic:U.toString(),currentOutstandingAtomic:r.session.currentOutstanding.toString(),frontierAtomic:(T>U?T:U).toString()})}let l=G(),d=Ue(),K=(0,P.sessionRegisterMessage)({programId:I.DEXTER_VAULT_PROGRAM_ID,vaultPda:this.vaultPdaKey,sessionPubkey:l.publicKey,maxAmount:E(t.maxAmountAtomic),maxRevolvingCapacity:i,expiresAt:BigInt(t.expiresAtUnix),allowedCounterparty:s,nonce:d}),h=await this.passkey.signOperation(K);return a?await this.sendAtomicReplace(r,t,s,l.publicKey,d,i,h):await this.sendBareRegister(t,s,l.publicKey,d,i,h),await(this.seams.waitForSession??g.waitForSession)(this.connection,this.vaultPdaKey,s,{expectedSessionPubkey:l.publicKey,timeoutMs:2e4}),Z(l,t,K)}async sendBareRegister(t,n,s,i,m,r){let{signature:a,clientDataJSON:l,authenticatorData:d}=r,K=le(d,(0,W.sha256)(l)),h=(0,V.buildSecp256r1VerifyInstruction)(this.passkey.publicKey,a,K),x=this.seams.fetchSessions??g.fetchVaultSessionAccounts,T=(0,g.sessionPdasOf)(await x(this.connection,this.vaultPdaKey)),p=await(this.seams.resolveUsdcAta??g.resolveVaultUsdcAta)(this.connection,new v.PublicKey(this.swigAddress)),u=pe({vaultPda:this.vaultPdaKey,swigAddress:new v.PublicKey(this.swigAddress),sessionPubkey:s,maxAmount:E(t.maxAmountAtomic),maxRevolvingCapacity:m,expiresAt:BigInt(t.expiresAtUnix),allowedCounterparty:n,nonce:i,clientDataJSON:l,authenticatorData:d,payer:this.feePayer.publicKey,siblingSessionPdas:T,vaultUsdcAta:p}),c=new v.Transaction().add(h,u);c.feePayer=this.feePayer.publicKey;let{blockhash:b}=await this.connection.getLatestBlockhash(this.confirmOptions.commitment);c.recentBlockhash=b,c.sign(this.feePayer);let S=await this.connection.sendRawTransaction(c.serialize(),{skipPreflight:!1,preflightCommitment:this.confirmOptions.preflightCommitment??this.confirmOptions.commitment});await this.connection.confirmTransaction({signature:S,blockhash:b,lastValidBlockHeight:(await this.connection.getLatestBlockhash(this.confirmOptions.commitment)).lastValidBlockHeight},this.confirmOptions.commitment)}async sendAtomicReplace(t,n,s,i,m,r,a){let l=(0,P.sessionRevokeMessage)({programId:I.DEXTER_VAULT_PROGRAM_ID,vaultPda:this.vaultPdaKey,sessionPubkey:t.session.sessionPubkey}),d=await this.passkey.signOperation(l),h=await(this.seams.resolveUsdcAta??g.resolveVaultUsdcAta)(this.connection,new v.PublicKey(this.swigAddress)),x=this.seams.composeSend?{send:this.seams.composeSend,deactivateAlt:async()=>{}}:N(this.connection,this.feePayer,{commitment:this.confirmOptions.commitment});try{await(0,g.composeRevokeThenRegister)({connection:this.connection,vaultPda:this.vaultPdaKey,allowedCounterparty:s,registerArgs:{sessionPubkey:i,maxAmount:E(n.maxAmountAtomic),maxRevolvingCapacity:r,expiresAt:BigInt(n.expiresAtUnix),nonce:m,swigAddress:new v.PublicKey(this.swigAddress),vaultUsdcAta:h,payer:this.feePayer.publicKey},registerCeremony:{clientDataJSON:a.clientDataJSON,authenticatorData:a.authenticatorData,signature:a.signature},revokeCeremony:{clientDataJSON:d.clientDataJSON,authenticatorData:d.authenticatorData,signature:d.signature},credentialPublicKey:this.passkey.publicKey,send:x.send,fetchSession:this.seams.fetchSession,fetchSessions:this.seams.fetchSessions})}finally{x.deactivateAlt()}}async signWithSession(t,n){let s=await Ce(n.channelId);return Q(t,n,s)}async signOpenTab(t,n){return t.registration}async signCloseTab(t,n,s){let i=(0,P.sessionRevokeMessage)({programId:I.DEXTER_VAULT_PROGRAM_ID,vaultPda:this.vaultPdaKey,sessionPubkey:t.publicKey}),{signature:m,clientDataJSON:r,authenticatorData:a}=await this.passkey.signOperation(i),l=le(a,(0,W.sha256)(r)),d=(0,V.buildSecp256r1VerifyInstruction)(this.passkey.publicKey,m,l),K=(0,O.buildRevokeSessionKeyInstruction)({vaultPda:this.vaultPdaKey,allowedCounterparty:new v.PublicKey(t.scope.allowedCounterparty),clientDataJSON:r,authenticatorData:a}),h=new v.Transaction().add(d,K);h.feePayer=this.feePayer.publicKey;let{blockhash:x,lastValidBlockHeight:T}=await this.connection.getLatestBlockhash(this.confirmOptions.commitment);h.recentBlockhash=x,h.sign(this.feePayer);let U=await this.connection.sendRawTransaction(h.serialize(),{skipPreflight:!1,preflightCommitment:this.confirmOptions.preflightCommitment??this.confirmOptions.commitment});return await this.connection.confirmTransaction({signature:U,blockhash:x,lastValidBlockHeight:T},this.confirmOptions.commitment),i}};function Te(e){return new X(e)}function le(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function Ue(){return Math.floor(Math.random()*4294967295)>>>0}async function Ce(e){if(/^[0-9a-f]{64}$/i.test(e))return Oe(e);let{sha256:t}=await import("@noble/hashes/sha256");return t(new TextEncoder().encode(e))}function Oe(e){let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.substr(n*2,2),16);return t}0&&(module.exports={LiveSessionExistsError,TX_SIZE_LIMIT_BYTES,buildAdapterRegisterInstruction,collectAltAddresses,compileComposeV0,createSelfPayingComposeSend,createSolanaVaultAdapter,deriveChannelId,passkeySignerFromP256Keypair});
|
|
1
|
+
"use strict";var ut=Object.create;var ee=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var mt=Object.getOwnPropertyNames;var gt=Object.getPrototypeOf,pt=Object.prototype.hasOwnProperty;var yt=(e,t)=>{for(var n in t)ee(e,n,{get:t[n],enumerable:!0})},Ve=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of mt(t))!pt.call(e,i)&&i!==n&&ee(e,i,{get:()=>t[i],enumerable:!(o=dt(t,i))||o.enumerable});return e};var te=(e,t,n)=>(n=e!=null?ut(gt(e)):{},Ve(t||!e||!e.__esModule?ee(n,"default",{value:e,enumerable:!0}):n,e)),ht=e=>Ve(ee({},"__esModule",{value:!0}),e);var Xt={};yt(Xt,{LiveSessionExistsError:()=>z,SOLANA_FINAL_VOUCHER_V2_MEMO_PROGRAM_ID:()=>tt,SOLANA_FINAL_VOUCHER_V2_PROGRAM_ID:()=>et,SolanaFinalVoucherV2ReservationError:()=>Y,TX_SIZE_LIMIT_BYTES:()=>j,buildAdapterRegisterInstruction:()=>lt,collectAltAddresses:()=>be,compileComposeV0:()=>we,createSelfPayingComposeSend:()=>ae,createSolanaFinalVoucherV2ReservationVerifier:()=>Qe,createSolanaVaultAdapter:()=>Gt,deriveChannelId:()=>Ue,passkeySignerFromP256Keypair:()=>st,verifySolanaFinalVoucherV2Reservation:()=>Q});module.exports=ht(Xt);var k=require("@solana/web3.js"),at=te(require("bs58"),1);var z=class extends Error{constructor(n){super(`a LIVE session already exists for counterparty ${n.allowedCounterparty} (session ${n.sessionPubkeyHex.slice(0,16)}\u2026, expires ${n.expiresAtUnix}; on-chain spent=${n.spentAtomic}, crystallized=${n.crystallizedCumulativeAtomic}, frontier=${n.frontierAtomic}). Replacing it voids any signed-but-unsettled vouchers beyond the frontier. Settle the old tab first (tab.close() or POST its last voucher to /tab/settle), or pass onLiveSession: 'replace' to atomically revoke-then-register over it.`);this.details=n;this.name="LiveSessionExistsError"}details};var N=require("@dexterai/vault/instructions"),ne=require("@dexterai/vault/precompile"),C=require("@dexterai/vault/constants");var x=require("@dexterai/vault/messages");var X=te(require("tweetnacl"),1),W=require("@solana/web3.js"),U=require("@dexterai/vault/messages"),ke=require("@dexterai/vault/session");var Be=require("@noble/hashes/sha256");function Ke(){let e=X.default.sign.keyPair();return{publicKey:e.publicKey,privateKey:e.secretKey}}function Te(e,t,n){return{publicKey:e.publicKey,privateKey:e.privateKey,scope:t,registration:n}}function Ee(e,t,n){if(n.length!==32)throw new Error(`channelIdBytes must be 32 bytes, got ${n.length}`);if(e.registration.length===188&&new DataView(e.registration.buffer,e.registration.byteOffset,e.registration.byteLength).getUint32(176,!0)>=2147483648)throw new Error("context-bound V2 sessions require signContextBoundFinalVoucherV2 and a durable reservation");let o=BigInt(t.cumulativeAmount),i=BigInt(e.scope.maxAmountAtomic);if(o>i)throw new Error(`voucher cumulative ${o} exceeds session cap ${i}`);let r=Math.floor(Date.now()/1e3);if(r>=e.scope.expiresAtUnix)throw new Error(`session expired at ${e.scope.expiresAtUnix}, now ${r}`);let s=(0,x.voucherPayloadMessage)({channelId:n,cumulativeAmount:o,sequenceNumber:t.sequenceNumber}),a=X.default.sign.detached(s,e.privateKey);return{payload:t,sessionPublicKey:e.publicKey,sessionRegistration:e.registration,sessionSignature:a}}var ft=/^[0-9a-f]{64}$/,vt=(1n<<64n)-1n;function pe(e){return Buffer.from(e).toString("hex")}function At(e){return Uint8Array.from(Buffer.from(e,"hex"))}function ye(e,t){if(e.length!==t.length)return!1;let n=0;for(let o=0;o<e.length;o+=1)n|=(e[o]??0)^(t[o]??0);return n===0}function Oe(e){if(!ft.test(e.channelId)||e.sessionPublicKey.length!==32||e.sessionPrivateKey.length!==64||e.sessionRegistration.length!==188||!/^[1-9][0-9]*$/.test(e.cumulativeAmountAtomic))throw new Error("native_tab_v2_signing_input_invalid");let t=BigInt(e.cumulativeAmountAtomic);if(t>vt)throw new Error("native_tab_v2_cumulative_amount_invalid");let n=new W.PublicKey(e.programId),o=new W.PublicKey(e.vaultPda),i=new W.PublicKey(e.sessionPda),r=new W.PublicKey(e.seller),[s]=(0,ke.deriveSessionPda)(o,r,n);if(!i.equals(s))throw new Error("native_tab_v2_session_pda_mismatch");let a=e.sessionRegistration,u=new DataView(a.buffer,a.byteOffset,a.byteLength),d=u.getBigUint64(128,!0),m=u.getBigInt64(136,!0),v=u.getBigUint64(180,!0),g=e.nowUnixSeconds??Math.floor(Date.now()/1e3);if(!Number.isSafeInteger(g)||g<0)throw new Error("native_tab_v2_signing_time_invalid");if(!ye(a,(0,U.sessionRegisterMessage)({programId:n,vaultPda:o,sessionPubkey:e.sessionPublicKey,maxAmount:d,expiresAt:m,allowedCounterparty:r,nonce:e.sessionNonce,maxRevolvingCapacity:v})))throw new Error("native_tab_v2_registration_identity_mismatch");if(d===0n||v===0n||v>d||m<=BigInt(g)||m>0x7fffffffffffffffn-604800n||t>d)throw new Error("native_tab_v2_registration_semantics_invalid");(0,U.sessionVoucherV2AuthorizationNonce)(e.sessionNonce);let y=X.default.sign.keyPair.fromSeed(e.sessionPrivateKey.subarray(0,32)),h=!1;try{h=ye(y.publicKey,e.sessionPublicKey)&&ye(e.sessionPrivateKey.subarray(32,64),e.sessionPublicKey)}finally{y.secretKey.fill(0)}if(!h)throw new Error("native_tab_v2_session_key_mismatch");let f=(0,U.finalVoucherV2Sequence)(e.sequenceOrdinal),p=(0,U.contextBoundVoucherV2Message)({programId:n,vaultPda:o,sessionPda:i,seller:r,sessionNonce:e.sessionNonce,channelId:At(e.channelId),cumulativeAmount:t,sequenceNumber:f}),R=X.default.sign.detached(p,e.sessionPrivateKey);return{channelId:e.channelId,cumulativeAmount:e.cumulativeAmountAtomic,sequenceNumber:f,sessionPublicKey:pe(e.sessionPublicKey),sessionSignature:pe(R),sessionRegistration:pe(a)}}function $(e){if(!/^\d+$/.test(e))throw new Error(`atomic amount must be a non-negative integer string, got "${e}"`);return BigInt(e)}function Ue(e){let t=new Uint8Array(8);new DataView(t.buffer).setBigUint64(0,e.nonce,!0);let n=new TextEncoder().encode(e.sellerUrl),o=Be.sha256.create();return o.update(e.vaultPda.toBytes()),o.update(n),o.update(t),o.digest()}var w=require("@dexterai/vault/session"),ct=require("@dexterai/vault/reader"),ge=require("@dexterai/vault");var bt=te(require("tweetnacl"),1),wt=require("@noble/hashes/sha256"),St=require("@noble/curves/p256"),oe=require("@solana/web3.js");var fe=require("@dexterai/vault/session"),ve=require("@dexterai/vault/messages"),he="OTS_SESSION_REGISTER_V2",F=class extends Error{constructor(n,o){super(`Invalid registration: ${n}${o?` (${o})`:""}`);this.reason=n;this.name="InvalidRegistrationError"}reason};function ie(e){if(e.length!==188)throw new F("wrong_length",`expected 188, got ${e.length}`);let t=new TextDecoder().decode(e.slice(0,he.length));if(t!==he)throw new F("wrong_domain",`got "${t}"`);for(let v=he.length;v<32;v++)if(e[v]!==0)throw new F("wrong_domain",`non-NUL padding at byte ${v}`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),o=new oe.PublicKey(e.slice(32,64)),i=new oe.PublicKey(e.slice(64,96)),r=e.slice(96,128),s=n.getBigUint64(128,!0),a=n.getBigInt64(136,!0),u=new oe.PublicKey(e.slice(144,176)),d=n.getUint32(176,!0),m=n.getBigUint64(180,!0);if(!o.equals(C.DEXTER_VAULT_PROGRAM_ID))throw new F("wrong_program",`${o.toBase58()} is not ${C.DEXTER_VAULT_PROGRAM_ID.toBase58()}`);if(s===0n)throw new F("cap_zero");return{programId:o,vaultPda:i,sessionPubkey:new Uint8Array(r),maxAmount:s,expiresAt:a,allowedCounterparty:u,nonce:d,maxRevolvingCapacity:m}}var Re=require("@noble/hashes/sha256"),me=require("@noble/hashes/utils");var K=require("@solana/web3.js"),j=1232,Pt=40,Ne=20,$e=4,xt=20,se=1e4,_t=1e6,re=4,M="[tab/solana/compose]";function be(e,t){let n=new Set,o=[],i=t.toBase58();for(let r of e)for(let s of r.keys){if(s.isSigner)continue;let a=s.pubkey.toBase58();a===i||n.has(a)||(n.add(a),o.push(s.pubkey))}return o}function we(e,t,n,o){let i=new K.TransactionMessage({payerKey:t,recentBlockhash:n,instructions:e}).compileToV0Message([o]);return new K.VersionedTransaction(i)}async function Fe(e){try{let t=(await e.getRecentPrioritizationFees()).map(o=>o.prioritizationFee).filter(o=>o>0).sort((o,i)=>o-i);if(t.length===0)return se;let n=t[Math.floor(.75*(t.length-1))]??se;return Math.max(se,Math.min(n,_t))}catch{return se}}function Rt(e){let t=e,n=String(t?.message??e??""),o=Array.isArray(t?.logs)?t.logs.join(" "):"";return/already in use/i.test(n)||/already in use/i.test(o)}function Le(e){let t=e;return(Array.isArray(t?.logs)?t.logs:[]).length===0&&/block height exceeded|has expired|blockhash not found/i.test(String(t?.message??e))}var Ae=e=>new Promise(t=>setTimeout(t,e));function ae(e,t,n={}){let o=n.commitment??"confirmed",i=n.altWarmupPollMs??400,r=n.altReadbackPollMs??400,s=n.altCollisionPollMs??500,a=null,u=null;async function d(h,f){let p=await Fe(e),R=[K.ComputeBudgetProgram.setComputeUnitPrice({microLamports:p}),...h],S;for(let P=0;P<re;P+=1){let{blockhash:b,lastValidBlockHeight:O}=await e.getLatestBlockhash(o),I=new K.Transaction().add(...R);I.feePayer=t.publicKey,I.recentBlockhash=b,I.sign(t);try{let c=await e.sendRawTransaction(I.serialize(),{skipPreflight:!1,maxRetries:5}),A=await e.confirmTransaction({signature:c,blockhash:b,lastValidBlockHeight:O},o);if(A.value.err)throw new Error(`${f} tx failed on-chain: ${JSON.stringify(A.value.err)}`);return c}catch(c){if(Le(c)&&P<re-1){console.warn(`${M} ${f} tx expired before landing (attempt ${P+1}) \u2014 rebroadcasting with a fresh blockhash`),S=c;continue}throw c}}throw S??new Error(`${f} tx did not land after rebroadcast attempts`)}async function m(h){for(let f=0;f<xt;f+=1){let p=await e.getSlot("finalized");if(p>h)return p;await Ae(s)}throw new Error(`ALT collision retry: finalized slot never advanced past ${h}`)}async function v(h){for(let f=0;f<Pt;f+=1){if(await e.getSlot(o)>h)return;await Ae(i)}throw new Error(`ALT warmup timed out: preflight (${o}) slot never passed lastExtendedSlot ${h}`)}async function g(h){if(a)return a;let f=be(h,t.publicKey),p=null,R=null,S=-1;for(let b=0;b<$e;b+=1){let O=S<0?await e.getSlot("finalized"):await m(S),[I,c]=K.AddressLookupTableProgram.createLookupTable({authority:t.publicKey,payer:t.publicKey,recentSlot:O}),A=K.AddressLookupTableProgram.extendLookupTable({payer:t.publicKey,authority:t.publicKey,lookupTable:c,addresses:f});try{R=await d([I,A],"ALT create/extend"),p=c;break}catch(D){if(Rt(D)&&b<$e-1){S=O,console.warn(`${M} ALT address collision at slot ${O} (attempt ${b+1}) \u2014 retrying create with a fresh finalized slot`);continue}throw D}}if(!p||!R)throw new Error("ALT create exhausted retries after repeated address collisions");let P=await e.getAddressLookupTable(p);for(let b=0;b<Ne&&!P.value;b+=1)await Ae(r),P=await e.getAddressLookupTable(p);if(!P.value)throw new Error(`ALT ${p.toBase58()} not visible after ${Ne} read polls (${R})`);return await v(P.value.state.lastExtendedSlot),a=P.value,u=p,console.info(`${M} ephemeral compose ALT ready: ${p.toBase58()} (${f.length} addresses, createTx ${R})`),a}async function _(h){let f=await Fe(e),p=[K.ComputeBudgetProgram.setComputeUnitPrice({microLamports:f}),...h],R=await g(p),S;for(let P=0;P<re;P+=1){let{blockhash:b,lastValidBlockHeight:O}=await e.getLatestBlockhash(o),I;try{let c=we(p,t.publicKey,b,R);c.sign([t]),I=c.serialize()}catch(c){throw/overrun|too large/i.test(String(c?.message??c))?new Error(`composed revoke-then-register v0 tx exceeds the ${j}B wire cap \u2014 too many sibling PDAs outside the lookup table`):c}if(I.length>j)throw new Error(`composed revoke-then-register v0 tx ${I.length}B exceeds the ${j}B wire cap \u2014 too many sibling PDAs outside the lookup table`);try{let c=await e.sendRawTransaction(I,{skipPreflight:!1,maxRetries:5}),A=await e.confirmTransaction({signature:c,blockhash:b,lastValidBlockHeight:O},o);if(A.value.err)throw new Error(`composed tx failed on-chain: ${JSON.stringify(A.value.err)}`);return c}catch(c){if(Le(c)&&P<re-1){console.warn(`${M} compose tx expired before landing (attempt ${P+1}, priorityFee ${f}) \u2014 rebroadcasting with a fresh blockhash`),S=c;continue}let A=Array.isArray(c?.logs)?c.logs:[];throw A.length?new Error(`${c?.message??c} | ${A.join(" | ")}`):c}}throw S instanceof Error?S:new Error("compose tx did not land after rebroadcast attempts")}async function y(){if(u)try{let h=K.AddressLookupTableProgram.deactivateLookupTable({lookupTable:u,authority:t.publicKey}),f=await d([h],"ALT deactivate");console.info(`${M} ephemeral compose ALT deactivated: ${u.toBase58()} (${f}) \u2014 rent reclaimable via close_lookup_table after the deactivation cooldown`)}catch(h){console.warn(`${M} ALT deactivate failed for ${u?.toBase58()} \u2014 rent parks until a later cleanup retries (the compose already landed): ${String(h?.message??h)}`)}}return{send:_,getAltAddress:()=>u,deactivateAlt:y}}var B=require("@solana/web3.js"),ue=require("@noble/hashes/utils"),H=require("@dexterai/vault/credit"),Z=require("@dexterai/vault/constants"),Xe=require("@dexterai/vault/instructions"),je=require("@dexterai/vault/reader"),G=require("@dexterai/vault/session");var xe=require("@noble/hashes/sha256"),L=require("@noble/hashes/utils"),De=/^[0-9a-f]{64}$/,ze=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/,It=/^[1-9A-HJ-NP-Za-km-z]{32,100}$/,Me="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",qe="dexter-native-tab-v2-reservation/v1",Ct=`${qe}:`;function Se(e){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new Error("canonical_non_finite_number");return e}if(typeof e=="bigint")return e.toString();if(Array.isArray(e))return e.map(Se);if(typeof e=="object")return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Se(n)]));throw new Error("canonical_value_unsupported")}function He(e){return JSON.stringify(Se(e))}function Pe(e){if(e==="solana:mainnet"||e===Me)return Me;throw new Error("native_tab_v2_reservation_network_unsupported")}function Ge(e){return(0,L.bytesToHex)((0,xe.sha256)(new TextEncoder().encode(He({channelId:e.payload.channelId,cumulativeAmount:e.payload.cumulativeAmount,sequenceNumber:e.payload.sequenceNumber,sessionPublicKey:(0,L.bytesToHex)(e.sessionPublicKey),sessionSignature:(0,L.bytesToHex)(e.sessionSignature),sessionRegistration:(0,L.bytesToHex)(e.sessionRegistration)}))))}function Vt(e){return(0,L.bytesToHex)((0,xe.sha256)(new TextEncoder().encode(He({contract:qe,network:Pe(e.network),programId:e.programId,buyerSwigAddress:e.buyerSwigAddress,vaultPda:e.vaultPda,sessionPda:e.sessionPda,seller:e.seller,channelId:e.channelId,sessionNonce:e.sessionNonce,reservationAmountAtomic:e.reservationAmountAtomic,previousCumulativeAtomic:e.previousCumulativeAtomic,voucherDigest:e.voucherDigest,cumulativeAmountAtomic:e.cumulativeAmountAtomic,sequenceNumber:e.sequenceNumber}))))}function kt(e){let t=Ge(e.voucher);return Vt({network:e.network,programId:e.programId,buyerSwigAddress:e.buyerSwigAddress,vaultPda:e.vaultPda,sessionPda:e.sessionPda,seller:e.seller,channelId:e.channelId,sessionNonce:e.sessionNonce,reservationAmountAtomic:e.reservationAmountAtomic,previousCumulativeAtomic:e.previousCumulativeAtomic,voucherDigest:t,cumulativeAmountAtomic:e.voucher.payload.cumulativeAmount,sequenceNumber:e.voucher.payload.sequenceNumber})}function Je(e){return`${Ct}${kt(e)}`}function V(e){throw new Error(`native_tab_v2_reservation_receipt_invalid:${e}`)}function ce(e,t){(!Number.isSafeInteger(e)||e<0)&&V(t)}function We(e,t){(!t||typeof t!="object")&&V("missing");let n=Ge(e.voucher);(!De.test(e.voucherDigest)||e.voucherDigest!==n)&&V("input_voucher_digest"),e.idempotencyKey!==`native-tab-v2:${n}`&&V("input_idempotency_identity");let o=BigInt(e.voucher.payload.cumulativeAmount),i=BigInt(e.previousCumulativeAtomic),r=BigInt(e.reservationAmountAtomic);(o<=i||o-i!==r||r<=0n)&&V("input_reservation_delta"),(e.voucher.payload.channelId!==e.channelId||(e.voucher.payload.sequenceNumber&2147483648)===0||(e.sessionNonce&2147483648)===0||e.voucher.sessionPublicKey.length!==32||e.voucher.sessionSignature.length!==64||e.voucher.sessionRegistration.length!==188)&&V("input_voucher_identity"),t.contract!=="dexter-native-tab-open-receipt/v1"&&t.contract!=="dexter-native-tab-open-receipt/v2"&&V("contract"),De.test(t.operationId)||V("operation_id"),ze.test(t.callerOperationId)||V("caller_operation_id"),It.test(t.transaction)||V("transaction"),t.commitment!=="finalized"&&V("commitment"),ce(t.confirmationSlot,"confirmation_slot"),ce(t.postStateSlot,"post_state_slot"),(t.confirmationSlot===0||t.postStateSlot<t.confirmationSlot)&&V("post_state_slot");let s,a;try{s=Pe(e.network),a=Pe(t.network)}catch{return V("network")}(a!==s||t.buyerSwigAddress!==e.buyerSwigAddress||t.vaultPda!==e.vaultPda||t.sessionPda!==e.sessionPda||t.seller!==e.seller||t.channelId!==e.channelId||t.sessionPublicKey!==(0,L.bytesToHex)(e.voucher.sessionPublicKey)||t.voucherDigest!==n||t.cumulativeAmountAtomic!==e.voucher.payload.cumulativeAmount||t.sequenceNumber!==e.voucher.payload.sequenceNumber||!ze.test(t.providerReceiptId)||t.reservationAmountAtomic!==e.reservationAmountAtomic||t.currentOutstandingBeforeAtomic!=="0"||t.currentOutstandingAfterAtomic!==e.reservationAmountAtomic)&&V("economic_identity"),ce(t.pendingVoucherCountBefore,"pending_voucher_count_before"),ce(t.pendingVoucherCountAfter,"pending_voucher_count_after"),t.contract==="dexter-native-tab-open-receipt/v1"?t.callerOperationId!==e.idempotencyKey&&V("idempotency_key"):(t.rootOperationId!==e.idempotencyKey||!Number.isSafeInteger(t.generation)||Number(t.generation)<2||!t.predecessorCallerOperationId||!t.predecessorLifecycleOperationId||!t.predecessorReleaseDigest||!t.stableReservationId||!t.economicEffectDigest)&&V("successor_identity")}var Kt=Uint8Array.from([56,67,4,209,238,143,0,129]),Tt=74,Ye=new Set([1,2]),Et=188,Ze=new B.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Ot=(()=>{let e=Buffer.alloc(32);return e.write("OTS_SESSION_REGISTER_V2","ascii"),e})(),Y=class extends Error{constructor(n,o){super(`native_tab_v2_solana_reservation_invalid:${n}`+(o?`:${o}`:""));this.code=n;this.name="SolanaFinalVoucherV2ReservationError"}code};function l(e,t){throw new Y(e,t)}function T(e,t){try{return new B.PublicKey(e)}catch{return l(t)}}function le(e,t){return e.length===t.length&&e.every((n,o)=>n===t[o])}async function Bt(e){let t=await e.connection.getTransaction(e.signature,{commitment:e.commitment,maxSupportedTransactionVersion:0});if(!t)return null;t.meta||l("transaction_meta_missing");let n=t.transaction.message,o=n.version===0?n.getAccountKeys({accountKeysFromLookups:t.meta.loadedAddresses??null}):n.getAccountKeys(),i=(r,s)=>{let a=o.get(r);return a||l(s),a};return{slot:t.slot,err:t.meta.err,signatures:[...t.transaction.signatures],accountKeys:Array.from({length:o.length},(r,s)=>({address:i(s,"transaction_account_key").toBase58(),signer:n.isAccountSigner(s),writable:n.isAccountWritable(s)})),instructions:n.compiledInstructions.map(r=>({programId:i(r.programIdIndex,"transaction_program_id").toBase58(),accounts:r.accountKeyIndexes.map(s=>i(s,"transaction_instruction_account").toBase58()),data:Uint8Array.from(r.data)}))}}function Ut(e,t,n,o){o.length!==Tt&&l("binding_length"),le(o.subarray(0,8),Kt)||l("binding_discriminator");let i=o.readUInt8(8),r=o.readUInt8(9);return Ye.has(i)||l("binding_version"),r!==t&&l("binding_bump"),{address:e.toBase58(),owner:n.toBase58(),version:i,bump:r,swig:new B.PublicKey(o.subarray(10,42)).toBase58(),vault:new B.PublicKey(o.subarray(42,74)).toBase58()}}async function Nt(e){let t=T(e.input.programId,"program_id"),n=T(e.input.buyerSwigAddress,"buyer_swig"),o=T(e.input.vaultPda,"vault_pda"),i=T(e.input.seller,"seller"),[r,s]=(0,H.deriveSwigVaultBindingPda)(n,t),[a]=(0,G.deriveSessionPda)(o,i,t),u=await e.connection.getMultipleAccountsInfoAndContext([r,o,a],{commitment:e.receipt.commitment,minContextSlot:e.receipt.postStateSlot}),[d,m,v]=u.value;d||l("binding_missing"),m||l("vault_missing"),v||l("session_missing");let g,_;try{g=(0,je.decodeVaultFull)(Buffer.from(m.data)),_=(0,G.decodeSessionAccount)(a,v.data)}catch(h){return l("post_state_decode",h instanceof Error?h.message:String(h))}let y=_.session;return{contextSlot:u.context.slot,binding:Ut(r,s,d.owner,Buffer.from(d.data)),vault:{owner:m.owner.toBase58(),exists:g.exists,version:g.version,swigAddress:g.swigAddress,dexterAuthority:g.dexterAuthority,pendingVoucherCount:g.pendingVoucherCount},session:{owner:v.owner.toBase58(),version:_.version,bump:_.bump,vault:_.vault,sessionPublicKey:(0,ue.bytesToHex)(y.sessionPubkey),maxAmount:y.maxAmount,expiresAt:y.expiresAt,seller:y.allowedCounterparty,nonce:y.nonce,spent:y.spent,currentOutstanding:y.currentOutstanding,maxRevolvingCapacity:y.maxRevolvingCapacity,crystallizedCumulative:y.crystallizedCumulative}}}function $t(e){let t=Buffer.from(e.voucher.sessionRegistration);return t.length!==Et&&l("registration_length"),le(t.subarray(0,32),Ot)||l("registration_domain"),{programId:new B.PublicKey(t.subarray(32,64)).toBase58(),vaultPda:new B.PublicKey(t.subarray(64,96)).toBase58(),sessionPublicKey:(0,ue.bytesToHex)(t.subarray(96,128)),maxAmount:t.readBigUInt64LE(128),expiresAt:t.readBigInt64LE(136),seller:new B.PublicKey(t.subarray(144,176)).toBase58(),nonce:t.readUInt32LE(176),maxRevolvingCapacity:t.readBigUInt64LE(180)}}function q(e,t,n){let o=e.accountKeys.filter(i=>i.address===t);return o.length!==1&&l(`${n}_account_key`),o[0]}function Ft(e,t,n){(!Number.isSafeInteger(n.slot)||n.slot<=0)&&l("transaction_slot"),n.slot!==t.confirmationSlot&&l("transaction_confirmation_slot"),n.err!==null&&l("transaction_failed"),n.signatures[0]!==t.transaction&&l("transaction_signature"),n.instructions.length!==2&&l("transaction_instruction_count");let o=T(e.programId,"program_id"),i=T(e.buyerSwigAddress,"buyer_swig"),r=T(e.vaultPda,"vault_pda"),s=T(e.seller,"seller"),a=T(e.sessionPda,"session_pda"),[u]=(0,G.deriveSessionPda)(r,s,o),d=(0,H.deriveSwigVaultBindingPda)(i,o)[0],m=(0,Xe.deriveSwigWalletAddress)(i),v=(0,H.deriveGraphConfigPda)(o)[0];a.equals(u)||l("session_pda_derivation");let g=Buffer.from(Z.DISCRIMINATORS.settle_voucher),_=n.instructions.filter(c=>{if(c.programId!==e.programId)return!1;let A=c.data;return A.length>=g.length&&le(A.subarray(0,g.length),g)});_.length!==1&&l("settle_voucher_instruction_count");let y=_[0];n.instructions[0]!==y&&l("settle_voucher_instruction_order");let h=Buffer.from(y.data);h.length!==49&&l("settle_voucher_instruction_length"),h.readBigUInt64LE(8).toString()!==e.reservationAmountAtomic&&l("settle_voucher_amount"),h.readUInt8(16)!==1&&l("settle_voucher_increment"),new B.PublicKey(h.subarray(17,49)).equals(s)||l("settle_voucher_seller"),y.accounts.length<8&&l("settle_voucher_accounts"),[r.toBase58(),null,a.toBase58(),null,i.toBase58(),m.toBase58(),d.toBase58(),v.toBase58()].forEach((c,A)=>{c!==null&&y.accounts[A]!==c&&l(`settle_voucher_account_${A}`)});let p=y.accounts[1];p||l("dexter_authority");let R=q(n,y.accounts[0],"vault"),S=q(n,p,"dexter_authority"),P=q(n,y.accounts[2],"session");(!R.writable||R.signer)&&l("vault_privileges"),S.signer||l("dexter_authority_signature"),(!P.writable||P.signer)&&l("session_privileges");for(let c=3;c<Math.min(y.accounts.length,8);c+=1)q(n,y.accounts[c],`account_${c}`).signer&&l(`settle_voucher_account_${c}_signer`);for(let c=8;c<y.accounts.length;c+=1){let A=q(n,y.accounts[c],`sibling_${c-8}`);(!A.writable||A.signer)&&l("settle_voucher_sibling_privileges")}let b=n.instructions[1];b.programId!==Ze.toBase58()&&l("reservation_memo_program"),(b.accounts.length!==1||b.accounts[0]!==p)&&l("reservation_memo_authority"),q(n,p,"reservation_memo_authority").signer||l("reservation_memo_authority_signature");let I=new TextEncoder().encode(Je(e));return le(b.data,I)||l("reservation_memo_digest"),p}function Lt(e,t,n,o){let i=T(e.programId,"program_id"),r=T(e.buyerSwigAddress,"buyer_swig"),s=T(e.vaultPda,"vault_pda"),a=T(e.seller,"seller"),[u,d]=(0,H.deriveSwigVaultBindingPda)(r,i),[m,v]=(0,G.deriveSessionPda)(s,a,i);(!Number.isSafeInteger(o.contextSlot)||o.contextSlot<t.postStateSlot||o.contextSlot<t.confirmationSlot)&&l("post_state_slot"),(o.binding.address!==u.toBase58()||o.binding.owner!==e.programId||o.binding.bump!==d||!Ye.has(o.binding.version)||o.binding.swig!==e.buyerSwigAddress||o.binding.vault!==e.vaultPda)&&l("binding_identity"),(o.vault.owner!==e.programId||!o.vault.exists||o.vault.version!==7||o.vault.swigAddress!==e.buyerSwigAddress||o.vault.dexterAuthority!==n)&&l("vault_post_state"),(e.sessionPda!==m.toBase58()||o.session.owner!==e.programId||o.session.version!==1||o.session.bump!==v||o.session.vault!==e.vaultPda||o.session.sessionPublicKey!==(0,ue.bytesToHex)(e.voucher.sessionPublicKey)||o.session.seller!==e.seller||o.session.nonce!==e.sessionNonce||o.session.currentOutstanding.toString()!==e.reservationAmountAtomic)&&l("session_post_state");let g=$t(e);(g.programId!==e.programId||g.vaultPda!==e.vaultPda||g.sessionPublicKey!==o.session.sessionPublicKey||g.seller!==e.seller||g.nonce!==e.sessionNonce||g.maxAmount!==o.session.maxAmount||g.expiresAt!==BigInt(o.session.expiresAt)||g.maxRevolvingCapacity!==o.session.maxRevolvingCapacity)&&l("registration_post_state"),(o.session.spent>o.session.crystallizedCumulative?o.session.spent:o.session.crystallizedCumulative).toString()!==e.previousCumulativeAtomic&&l("session_frontier")}async function Q(e,t,n,o={}){try{We(t,n)}catch(a){return l("provider_receipt",a instanceof Error?a.message:String(a))}t.network!=="solana:mainnet"&&l("network"),t.programId!==Z.DEXTER_VAULT_PROGRAM_ID.toBase58()&&l("program_id");let i=await(o.readTransaction??Bt)({connection:e,signature:n.transaction,commitment:n.commitment});i||l("transaction_missing");let r=Ft(t,n,i),s=await(o.readPostState??Nt)({connection:e,input:t,receipt:n});Lt(t,n,r,s)}function Qe(e,t={}){return(n,o)=>Q(e,n,o,t)}var et=Z.DEXTER_VAULT_PROGRAM_ID,tt=Ze;var _e=require("@noble/curves/p256"),J=require("@noble/hashes/sha256"),de=require("@dexterai/vault"),ot=require("@dexterai/vault/messages"),it="dexter.cash";function Dt(e){return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function zt(e,t=`https://${it}`){let o={type:"webauthn.get",challenge:Dt(e),origin:t,crossOrigin:!1};return new TextEncoder().encode(JSON.stringify(o))}function Mt(e=1){let t=(0,J.sha256)(new TextEncoder().encode(it)),n=new Uint8Array(37);return n.set(t,0),n[32]=5,new DataView(n.buffer).setUint32(33,e,!1),n}function nt(e,t){let n=zt(t),o=Mt(1),i=new Uint8Array(o.length+32);i.set(o,0),i.set((0,J.sha256)(n),o.length);let r=(0,J.sha256)(i);return{signature:_e.p256.sign(r,e.privateKey,{lowS:!0}).toCompactRawBytes(),clientDataJSON:n,authenticatorData:o}}function st(e,t={}){return{credentialId:new Uint8Array(0),publicKey:e.publicKey,signOperation:async n=>{let o=t.resolveAuthorizationContext?await t.resolveAuthorizationContext(n.slice()):qt(n);if(!o){if(t.allowLegacyOperationHash===!0)return nt(e,(0,J.sha256)(n));throw new Error("passkey_authorization_context_required")}let i=t.ceremonyNonce?t.ceremonyNonce():_e.p256.utils.randomPrivateKey();if(i.length!==32)throw new Error("ceremonyNonce must be exactly 32 bytes");let r=(0,de.buildPasskeyAuthorizationChallenge)({programId:o.programId,vault:o.vault,nonce:o.nonce,operationHash:(0,J.sha256)(n),ceremonyNonce:i});return nt(e,r)}}}function qt(e){let t=(0,de.classifyPasskeyAuthorizationOperation)(e);return t.kind==="session_register_v2"?{programId:t.fields.programId,vault:t.fields.vault,nonce:BigInt((0,ot.sessionVoucherV2AuthorizationNonce)(t.fields.registrationNonce))}:t.kind==="session_replace_v1"?{programId:t.fields.programId,vault:t.fields.vault,nonce:t.fields.authorizationNonce}:null}async function Ht({connection:e,vaultPda:t,allowedCounterparty:n,programId:o=C.DEXTER_VAULT_PROGRAM_ID,commitment:i="finalized"}){let[r]=(0,w.deriveSessionPda)(t,n,o),s=await e.getMultipleAccountsInfoAndContext([t,r],{commitment:i}),[a,u]=s.value;if(!a)throw new Error("close revocation: vault account not found");if(!a.owner.equals(o))throw new Error("close revocation: vault has the wrong owner");let d=(0,ct.decodeVaultFull)(Buffer.from(a.data));if(!d.exists||d.version!==7)throw new Error("close revocation: Vault V7 required");if(!u)return{kind:"invalidated",contextSlot:s.context.slot,sessionPda:r,reason:"absent"};if(!u.owner.equals(o))throw new Error("close revocation: session has the wrong owner");let m=(0,w.decodeSessionAccount)(r,u.data);if(m.version===0)return{kind:"invalidated",contextSlot:s.context.slot,sessionPda:r,reason:"cleared"};if(m.version!==1)throw new Error("close revocation: live SessionAccount required");if(m.vault!==t.toBase58())throw new Error("close revocation: session belongs to a different vault");if(m.session.allowedCounterparty!==n.toBase58())throw new Error("close revocation: session counterparty mismatch");return{kind:"live",snapshot:{contextSlot:s.context.slot,programId:new k.PublicKey(o),vaultPda:new k.PublicKey(t),sessionPda:r,sessionPubkey:Uint8Array.from(m.session.sessionPubkey),maxAmount:m.session.maxAmount,expiresAt:Buffer.from(u.data).readBigInt64LE(82),allowedCounterparty:new k.PublicKey(n),nonce:m.session.nonce,spent:m.session.spent,currentOutstanding:m.session.currentOutstanding,maxRevolvingCapacity:m.session.maxRevolvingCapacity,crystallizedCumulative:m.session.crystallizedCumulative,lastLockedSequence:m.session.lastLockedSequence,expectedPendingVoucherCount:d.pendingVoucherCount}}}function lt(e){return(0,N.buildRegisterSessionKeyInstruction)({vaultPda:e.vaultPda,sessionPubkey:e.sessionPubkey,maxAmount:e.maxAmount,maxRevolvingCapacity:e.maxRevolvingCapacity,expiresAt:e.expiresAt,allowedCounterparty:e.allowedCounterparty,nonce:e.nonce,swigAddress:e.swigAddress,vaultUsdcAta:e.vaultUsdcAta,clientDataJSON:e.clientDataJSON,authenticatorData:e.authenticatorData,payer:e.payer,siblingSessionPdas:e.siblingSessionPdas})}var Ie=class{network="solana:mainnet";sessionVoucherVersion=2;swigAddress;vaultPda;connection;vaultPdaKey;passkey;feePayer;confirmOptions;seams;pendingCloseRevocations=new Map;completedCloseRevocations=new Map;constructor(t){this.connection=t.connection,this.swigAddress=typeof t.swigAddress=="string"?t.swigAddress:t.swigAddress.toBase58(),this.vaultPdaKey=typeof t.vaultPda=="string"?new k.PublicKey(t.vaultPda):t.vaultPda,this.vaultPda=this.vaultPdaKey.toBase58(),this.passkey=t.passkeySigner,this.feePayer=t.feePayer,this.confirmOptions=t.confirmOptions??{commitment:"confirmed"},this.seams=t.seams??{}}closeRevocationKey(t){let n=ie(t.registration),[o]=(0,w.deriveSessionPda)(this.vaultPdaKey,n.allowedCounterparty,C.DEXTER_VAULT_PROGRAM_ID);return[o.toBase58(),(0,me.bytesToHex)(n.sessionPubkey),n.nonce.toString()].join(":")}async readCloseTargetState(t){let n={connection:this.connection,vaultPda:this.vaultPdaKey,allowedCounterparty:t,programId:C.DEXTER_VAULT_PROGRAM_ID,commitment:"finalized"};if(this.seams.readCloseRevocationTargetState)return this.seams.readCloseRevocationTargetState(n);if(this.seams.readCloseRevocationSnapshot)try{return{kind:"live",snapshot:await this.seams.readCloseRevocationSnapshot(n)}}catch{return null}return Ht(n)}targetInvalidated(t,n){if(t.kind==="invalidated")return!0;let o=t.snapshot,[i]=(0,w.deriveSessionPda)(this.vaultPdaKey,n.allowedCounterparty,C.DEXTER_VAULT_PROGRAM_ID);if(!o.programId.equals(C.DEXTER_VAULT_PROGRAM_ID)||!o.vaultPda.equals(this.vaultPdaKey)||!o.sessionPda.equals(i)||!o.allowedCounterparty.equals(n.allowedCounterparty))throw new Error("session revocation snapshot identity mismatch");if(!Buffer.from(o.sessionPubkey).equals(Buffer.from(n.sessionPubkey))||o.nonce!==n.nonce)return!0;if(o.maxAmount!==n.maxAmount||o.expiresAt!==n.expiresAt||o.maxRevolvingCapacity!==n.maxRevolvingCapacity)throw new Error("session revocation snapshot identity mismatch");return!1}rememberCompletedClose(t,n){let o=Uint8Array.from(n);return this.pendingCloseRevocations.delete(t),this.completedCloseRevocations.set(t,o),Uint8Array.from(o)}async reconcilePendingClose(t,n,o){let i=!1,r=null;try{let u=await this.connection.getSignatureStatuses([t.signature],{searchTransactionHistory:!0});if(i=!0,r=u.value[0]??null,r?.confirmationStatus==="finalized")return r.err===null?"complete":"fresh_allowed"}catch{}let s=!1;try{let u=await this.connection.getTransaction(t.signature,{commitment:"finalized",maxSupportedTransactionVersion:0});if(s=!0,u)return!u.meta||!Object.prototype.hasOwnProperty.call(u.meta,"err")?"unresolved":u.meta.err===null?"complete":"fresh_allowed"}catch{}let a=await this.readCloseTargetState(n.allowedCounterparty).catch(()=>null);if(a&&this.targetInvalidated(a,n))return"complete";if(o&&i&&r===null)try{if((await this.connection.isBlockhashValid(t.blockhash,{commitment:"confirmed"})).value)return await this.connection.sendRawTransaction(t.serializedTransaction,{skipPreflight:!1,preflightCommitment:this.confirmOptions.preflightCommitment??this.confirmOptions.commitment})!==t.signature?"unresolved":(await this.connection.confirmTransaction({signature:t.signature,blockhash:t.blockhash,lastValidBlockHeight:t.lastValidBlockHeight},"finalized")).value.err===null?"complete":"fresh_allowed"}catch{}if(i&&r!==null||!i||!s||t.finalizedHistoryFloorSlot===null)return"unresolved";try{let[u,d]=await Promise.all([this.connection.getBlockHeight("finalized"),this.connection.getMinimumLedgerSlot()]);if(u>t.lastValidBlockHeight&&d<=t.finalizedHistoryFloorSlot)return"fresh_allowed"}catch{}return"unresolved"}async authorizeSession(t,n){let o=new k.PublicKey(t.allowedCounterparty),i=$(t.revolvingCapacityAtomic??t.maxAmountAtomic),s=await(this.seams.fetchSession??w.fetchSessionAccount)(this.connection,this.vaultPdaKey,o),a=s!==null&&(0,w.isSessionLive)(s);if(a&&(n?.onLiveSession??"error")!=="replace"){let f=s.session.spent,p=s.session.crystallizedCumulative;throw new z({allowedCounterparty:t.allowedCounterparty,sessionPubkeyHex:(0,me.bytesToHex)(s.session.sessionPubkey),expiresAtUnix:s.session.expiresAt,spentAtomic:f.toString(),crystallizedCumulativeAtomic:p.toString(),currentOutstandingAtomic:s.session.currentOutstanding.toString(),frontierAtomic:(f>p?f:p).toString()})}let d=await(this.seams.fetchPasskeyAuthorization??ge.fetchPasskeyAuthorizationState)(this.connection,this.vaultPdaKey,C.DEXTER_VAULT_PROGRAM_ID);if(d===null||d.version!==1||!d.vault.equals(this.vaultPdaKey))throw new Error("passkey_authorization_guard_unavailable");let m=Ke(),v=(0,x.sessionVoucherV2Nonce)(d.nonce),g=(0,x.sessionRegisterMessage)({programId:C.DEXTER_VAULT_PROGRAM_ID,vaultPda:this.vaultPdaKey,sessionPubkey:m.publicKey,maxAmount:$(t.maxAmountAtomic),maxRevolvingCapacity:i,expiresAt:BigInt(t.expiresAtUnix),allowedCounterparty:o,nonce:v}),_=a?(0,x.sessionReplaceV1Message)({programId:C.DEXTER_VAULT_PROGRAM_ID,vaultPda:this.vaultPdaKey,sessionPda:new k.PublicKey(s.address),authorizationNonce:d.nonce,retired:{sessionPubkey:s.session.sessionPubkey,maxAmount:s.session.maxAmount,expiresAt:BigInt(s.session.expiresAt),allowedCounterparty:new k.PublicKey(s.session.allowedCounterparty),nonce:s.session.nonce,spent:s.session.spent,currentOutstanding:s.session.currentOutstanding,maxRevolvingCapacity:s.session.maxRevolvingCapacity,crystallizedCumulative:s.session.crystallizedCumulative,lastLockedSequence:s.session.lastLockedSequence},replacement:{sessionPubkey:m.publicKey,maxAmount:$(t.maxAmountAtomic),expiresAt:BigInt(t.expiresAtUnix),allowedCounterparty:o,nonce:v,maxRevolvingCapacity:i}}):g,y=await this.passkey.signOperation(_);if(a)await this.sendAtomicReplace(t,o,m.publicKey,v,i,y);else{if((0,ge.validatePasskeyAuthorizationClientData)({clientDataJSON:y.clientDataJSON,operationMessage:_,expectedVault:this.vaultPdaKey,expectedProgramId:C.DEXTER_VAULT_PROGRAM_ID}).nonce!==d.nonce)throw new Error("passkey_authorization_guard_changed");await this.sendBareRegister(t,o,m.publicKey,v,i,y)}return await(this.seams.waitForSession??w.waitForSession)(this.connection,this.vaultPdaKey,o,{expectedSessionPubkey:m.publicKey,timeoutMs:2e4}),Te(m,t,g)}async sendBareRegister(t,n,o,i,r,s){let{signature:a,clientDataJSON:u,authenticatorData:d}=s,m=rt(d,(0,Re.sha256)(u)),v=(0,ne.buildSecp256r1VerifyInstruction)(this.passkey.publicKey,a,m),g=this.seams.fetchSessions??w.fetchVaultSessionAccounts,_=(0,w.sessionPdasOf)(await g(this.connection,this.vaultPdaKey)),h=await(this.seams.resolveUsdcAta??w.resolveVaultUsdcAta)(this.connection,new k.PublicKey(this.swigAddress)),f=lt({vaultPda:this.vaultPdaKey,swigAddress:new k.PublicKey(this.swigAddress),sessionPubkey:o,maxAmount:$(t.maxAmountAtomic),maxRevolvingCapacity:r,expiresAt:BigInt(t.expiresAtUnix),allowedCounterparty:n,nonce:i,clientDataJSON:u,authenticatorData:d,payer:this.feePayer.publicKey,siblingSessionPdas:_,vaultUsdcAta:h}),p=new k.Transaction().add(v,f);p.feePayer=this.feePayer.publicKey;let{blockhash:R}=await this.connection.getLatestBlockhash(this.confirmOptions.commitment);p.recentBlockhash=R,p.sign(this.feePayer);let S=await this.connection.sendRawTransaction(p.serialize(),{skipPreflight:!1,preflightCommitment:this.confirmOptions.preflightCommitment??this.confirmOptions.commitment});await this.connection.confirmTransaction({signature:S,blockhash:R,lastValidBlockHeight:(await this.connection.getLatestBlockhash(this.confirmOptions.commitment)).lastValidBlockHeight},this.confirmOptions.commitment)}async sendAtomicReplace(t,n,o,i,r,s){let u=await(this.seams.resolveUsdcAta??w.resolveVaultUsdcAta)(this.connection,new k.PublicKey(this.swigAddress)),d=this.seams.composeSend?{send:this.seams.composeSend,deactivateAlt:async()=>{}}:ae(this.connection,this.feePayer,{commitment:this.confirmOptions.commitment});try{await(0,w.composeRevokeThenRegister)({connection:this.connection,vaultPda:this.vaultPdaKey,allowedCounterparty:n,registerArgs:{sessionPubkey:o,maxAmount:$(t.maxAmountAtomic),maxRevolvingCapacity:r,expiresAt:BigInt(t.expiresAtUnix),nonce:i,swigAddress:new k.PublicKey(this.swigAddress),vaultUsdcAta:u,payer:this.feePayer.publicKey},registerCeremony:{clientDataJSON:s.clientDataJSON,authenticatorData:s.authenticatorData,signature:s.signature},credentialPublicKey:this.passkey.publicKey,send:d.send,fetchSession:this.seams.fetchSession,fetchSessions:this.seams.fetchSessions,fetchPasskeyAuthorization:this.seams.fetchPasskeyAuthorization})}finally{d.deactivateAlt()}}async signWithSession(t,n){let o=await Jt(n.channelId),i=ie(t.registration);if((i.nonce&2147483648)!==0){let[r]=(0,w.deriveSessionPda)(i.vaultPda,i.allowedCounterparty,i.programId),s=Oe({programId:i.programId.toBase58(),vaultPda:i.vaultPda.toBase58(),sessionPda:r.toBase58(),seller:i.allowedCounterparty.toBase58(),sessionNonce:i.nonce,channelId:(0,me.bytesToHex)(o),cumulativeAmountAtomic:n.cumulativeAmount,sequenceOrdinal:n.sequenceNumber,sessionPrivateKey:t.privateKey,sessionPublicKey:t.publicKey,sessionRegistration:t.registration});return{payload:{channelId:s.channelId,cumulativeAmount:s.cumulativeAmount,sequenceNumber:s.sequenceNumber},sessionPublicKey:Uint8Array.from(Buffer.from(s.sessionPublicKey,"hex")),sessionSignature:Uint8Array.from(Buffer.from(s.sessionSignature,"hex")),sessionRegistration:Uint8Array.from(Buffer.from(s.sessionRegistration,"hex"))}}return Ee(t,n,o)}async signOpenTab(t,n){return t.registration}async verifyFinalVoucherV2Reservation(t,n){await Q(this.connection,t,n)}async signCloseTab(t,n,o){let i=ie(t.registration);if(!i.vaultPda.equals(this.vaultPdaKey)||!Buffer.from(i.sessionPubkey).equals(Buffer.from(t.publicKey)))throw new Error("session registration identity mismatch");let r=this.closeRevocationKey(t),s=this.completedCloseRevocations.get(r);if(s)return Uint8Array.from(s);let a=this.pendingCloseRevocations.get(r);if(a){let E=await this.reconcilePendingClose(a,i,!0);if(E==="complete")return this.rememberCompletedClose(r,a.message);if(E==="unresolved")throw new Error(`session revoke finality unresolved for ${a.signature}; retry close`);this.pendingCloseRevocations.delete(r)}let u=await this.readCloseTargetState(i.allowedCounterparty);if(!u)throw new Error("close revocation target state unavailable");if(u.kind==="invalidated"||this.targetInvalidated(u,i))return this.rememberCompletedClose(r,t.registration);let d=u.snapshot,m=$(o);if((d.spent>d.crystallizedCumulative?d.spent:d.crystallizedCumulative)<m)throw new Error("session revocation snapshot is behind final settlement");let g=(0,x.sessionRevokeMessage)(d),{signature:_,clientDataJSON:y,authenticatorData:h}=await this.passkey.signOperation(g),f=rt(h,(0,Re.sha256)(y)),p=(0,ne.buildSecp256r1VerifyInstruction)(this.passkey.publicKey,_,f),R=(0,N.buildRevokeSessionKeyInstruction)({vaultPda:this.vaultPdaKey,allowedCounterparty:d.allowedCounterparty,expectedPendingVoucherCount:d.expectedPendingVoucherCount,clientDataJSON:y,authenticatorData:h}),S=new k.Transaction().add(p,R);S.feePayer=this.feePayer.publicKey;let P=null;try{let E=await this.connection.getSlot("finalized");P=Number.isSafeInteger(E)&&E>=0?E:null}catch{}let{blockhash:b,lastValidBlockHeight:O}=await this.connection.getLatestBlockhash(this.confirmOptions.commitment);if(S.recentBlockhash=b,S.sign(this.feePayer),!S.signature)throw new Error("session revoke transaction is unsigned");let I=Uint8Array.from(S.serialize()),c=at.default.encode(S.signature),A={key:r,message:Uint8Array.from(g),serializedTransaction:I,signature:c,blockhash:b,lastValidBlockHeight:O,finalizedHistoryFloorSlot:P};this.pendingCloseRevocations.set(r,A);let D;try{let E=await this.connection.sendRawTransaction(I,{skipPreflight:!1,preflightCommitment:this.confirmOptions.preflightCommitment??this.confirmOptions.commitment});if(E!==c)throw new Error(`session revoke signature mismatch expected=${c} returned=${E}`);D=await this.connection.confirmTransaction({signature:c,blockhash:b,lastValidBlockHeight:O},"finalized")}catch(E){let Ce=await this.reconcilePendingClose(A,i,!1);if(Ce==="complete")return this.rememberCompletedClose(r,g);throw Ce==="fresh_allowed"?(this.pendingCloseRevocations.delete(r),new Error("session revoke transaction finalized without effect; retry close",{cause:E})):new Error(`session revoke finality unresolved for ${c}; retry close`,{cause:E})}if(D.value.err)throw this.pendingCloseRevocations.delete(r),new Error(`session revoke transaction failed: ${JSON.stringify(D.value.err)}`);return this.rememberCompletedClose(r,g)}};function Gt(e){return new Ie(e)}function rt(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}async function Jt(e){if(/^[0-9a-f]{64}$/i.test(e))return Wt(e);let{sha256:t}=await import("@noble/hashes/sha256");return t(new TextEncoder().encode(e))}function Wt(e){let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.substr(n*2,2),16);return t}0&&(module.exports={LiveSessionExistsError,SOLANA_FINAL_VOUCHER_V2_MEMO_PROGRAM_ID,SOLANA_FINAL_VOUCHER_V2_PROGRAM_ID,SolanaFinalVoucherV2ReservationError,TX_SIZE_LIMIT_BYTES,buildAdapterRegisterInstruction,collectAltAddresses,compileComposeV0,createSelfPayingComposeSend,createSolanaFinalVoucherV2ReservationVerifier,createSolanaVaultAdapter,deriveChannelId,passkeySignerFromP256Keypair,verifySolanaFinalVoucherV2Reservation});
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { V as VaultAdapter } from '../../../types-
|
|
3
|
-
export { A as AuthorizeSessionOptions, L as LiveSessionDetails,
|
|
4
|
-
export { d as deriveChannelId } from '../../../sessions-
|
|
1
|
+
import { PublicKey, Connection, TransactionInstruction, Commitment, AddressLookupTableAccount, VersionedTransaction, Signer, ConfirmOptions } from '@solana/web3.js';
|
|
2
|
+
import { F as FinalVoucherV2ReservationInput, a as FinalVoucherV2ReservationReceipt, V as VerifyFinalVoucherV2Reservation, b as VaultAdapter } from '../../../types-45M9fb5M.cjs';
|
|
3
|
+
export { A as AuthorizeSessionOptions, L as LiveSessionDetails, c as LiveSessionExistsError } from '../../../types-45M9fb5M.cjs';
|
|
4
|
+
export { d as deriveChannelId } from '../../../sessions-rPdO1CgK.cjs';
|
|
5
5
|
import { fetchSessionAccount, fetchVaultSessionAccounts, resolveVaultUsdcAta, waitForSession } from '@dexterai/vault/session';
|
|
6
|
+
import { fetchPasskeyAuthorizationState } from '@dexterai/vault';
|
|
6
7
|
import { PasskeySignerWithPublicKey } from '@dexterai/vault/signers';
|
|
7
8
|
export { PasskeySignerWithPublicKey as PasskeySigner } from '@dexterai/vault/signers';
|
|
8
9
|
import '@dexterai/vault/types';
|
|
@@ -19,8 +20,10 @@ import '@dexterai/vault/types';
|
|
|
19
20
|
*
|
|
20
21
|
* From the on-chain program's perspective the two paths are
|
|
21
22
|
* indistinguishable: both produce a 64-byte (r||s) low-S secp256r1
|
|
22
|
-
* signature over `authenticatorData || sha256(clientDataJSON)
|
|
23
|
-
* `clientDataJSON.challenge`
|
|
23
|
+
* signature over `authenticatorData || sha256(clientDataJSON)`. For V7,
|
|
24
|
+
* `clientDataJSON.challenge` is the canonical 200-byte authorization envelope
|
|
25
|
+
* binding program, vault, monotonic guard nonce, operation hash, and fresh
|
|
26
|
+
* ceremony entropy.
|
|
24
27
|
*
|
|
25
28
|
* This module mirrors the helper at
|
|
26
29
|
* dexter-vault/tests/helpers/secp256r1.ts (signOperationWithPasskey).
|
|
@@ -33,12 +36,34 @@ interface P256Keypair {
|
|
|
33
36
|
/** 32-byte raw scalar. NEVER persist this anywhere user-readable. */
|
|
34
37
|
privateKey: Uint8Array;
|
|
35
38
|
}
|
|
39
|
+
interface NodePasskeyAuthorizationContext {
|
|
40
|
+
programId: PublicKey;
|
|
41
|
+
vault: PublicKey;
|
|
42
|
+
nonce: bigint;
|
|
43
|
+
}
|
|
44
|
+
interface NodePasskeySignerOptions {
|
|
45
|
+
/**
|
|
46
|
+
* Optional authoritative nonce resolver for operations whose wire format
|
|
47
|
+
* does not itself carry enough guard-generation context. The session V2
|
|
48
|
+
* register/replace/revoke messages are recognized locally; callers using
|
|
49
|
+
* this development signer for any other V7 operation should provide this.
|
|
50
|
+
*/
|
|
51
|
+
resolveAuthorizationContext?: (operationMessage: Uint8Array) => Promise<NodePasskeyAuthorizationContext>;
|
|
52
|
+
/**
|
|
53
|
+
* Explicit opt-in for pre-V7 development fixtures whose challenge was the
|
|
54
|
+
* bare sha256(operation). The safe default is false: an unknown operation
|
|
55
|
+
* must never be signed under a weaker authorization envelope merely because
|
|
56
|
+
* the node helper did not recognize its wire format.
|
|
57
|
+
*/
|
|
58
|
+
allowLegacyOperationHash?: boolean;
|
|
59
|
+
/** Deterministic test seam. Production defaults to fresh random 32 bytes. */
|
|
60
|
+
ceremonyNonce?: () => Uint8Array;
|
|
61
|
+
}
|
|
36
62
|
/**
|
|
37
|
-
* Build a unified `PasskeySignerWithPublicKey` (
|
|
63
|
+
* Build a unified `PasskeySignerWithPublicKey` (Vault 0.43.1's canonical shape)
|
|
38
64
|
* from a locally-held P-256 keypair — the node/CLI path. Returns
|
|
39
65
|
* `{ credentialId, publicKey, signOperation(operationMessage) }`. The signer
|
|
40
|
-
* owns
|
|
41
|
-
* internally (mirroring vault's `DexterApiBrowserPasskeySigner.signOperation`),
|
|
66
|
+
* owns canonical challenge construction for recognized V7 session operations,
|
|
42
67
|
* so the adapter hands it the RAW operation message and never pre-hashes.
|
|
43
68
|
* The adapter still rebuilds the precompile message from the returned bytes.
|
|
44
69
|
*
|
|
@@ -47,18 +72,104 @@ interface P256Keypair {
|
|
|
47
72
|
* secp256r1 precompile over the clientDataJSON/authenticatorData, not the
|
|
48
73
|
* credentialId, so an empty value is correct here.
|
|
49
74
|
*/
|
|
50
|
-
declare function passkeySignerFromP256Keypair(kp: P256Keypair): PasskeySignerWithPublicKey;
|
|
75
|
+
declare function passkeySignerFromP256Keypair(kp: P256Keypair, options?: NodePasskeySignerOptions): PasskeySignerWithPublicKey;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Independent Solana proof for a FINAL Native Tab V2 reservation.
|
|
79
|
+
*
|
|
80
|
+
* The transaction must contain exactly two top-level instructions: the exact
|
|
81
|
+
* Vault `settle_voucher(increment=true)` reservation followed by an SPL Memo
|
|
82
|
+
* carrying the domain-separated digest of the complete FINAL voucher and its
|
|
83
|
+
* reservation identity. The Vault's recorded Dexter authority must sign both
|
|
84
|
+
* instruction accounts. The provider receipt is still checked as durable
|
|
85
|
+
* lifecycle evidence, but it is no longer the only voucher-to-transaction
|
|
86
|
+
* binding.
|
|
87
|
+
*/
|
|
88
|
+
|
|
89
|
+
declare class SolanaFinalVoucherV2ReservationError extends Error {
|
|
90
|
+
readonly code: string;
|
|
91
|
+
constructor(code: string, detail?: string);
|
|
92
|
+
}
|
|
93
|
+
interface TransactionAccountEvidence {
|
|
94
|
+
address: string;
|
|
95
|
+
signer: boolean;
|
|
96
|
+
writable: boolean;
|
|
97
|
+
}
|
|
98
|
+
interface TransactionInstructionEvidence {
|
|
99
|
+
programId: string;
|
|
100
|
+
accounts: string[];
|
|
101
|
+
data: Uint8Array;
|
|
102
|
+
}
|
|
103
|
+
interface SolanaReservationTransactionEvidence {
|
|
104
|
+
slot: number;
|
|
105
|
+
err: unknown | null;
|
|
106
|
+
signatures: string[];
|
|
107
|
+
accountKeys: TransactionAccountEvidence[];
|
|
108
|
+
instructions: TransactionInstructionEvidence[];
|
|
109
|
+
}
|
|
110
|
+
interface SolanaReservationPostStateEvidence {
|
|
111
|
+
contextSlot: number;
|
|
112
|
+
binding: {
|
|
113
|
+
address: string;
|
|
114
|
+
owner: string;
|
|
115
|
+
version: number;
|
|
116
|
+
bump: number;
|
|
117
|
+
swig: string;
|
|
118
|
+
vault: string;
|
|
119
|
+
};
|
|
120
|
+
vault: {
|
|
121
|
+
owner: string;
|
|
122
|
+
exists: boolean;
|
|
123
|
+
version: number;
|
|
124
|
+
swigAddress: string | null;
|
|
125
|
+
dexterAuthority: string | null;
|
|
126
|
+
pendingVoucherCount: number;
|
|
127
|
+
};
|
|
128
|
+
session: {
|
|
129
|
+
owner: string;
|
|
130
|
+
version: number;
|
|
131
|
+
bump: number;
|
|
132
|
+
vault: string;
|
|
133
|
+
sessionPublicKey: string;
|
|
134
|
+
maxAmount: bigint;
|
|
135
|
+
expiresAt: number;
|
|
136
|
+
seller: string;
|
|
137
|
+
nonce: number;
|
|
138
|
+
spent: bigint;
|
|
139
|
+
currentOutstanding: bigint;
|
|
140
|
+
maxRevolvingCapacity: bigint;
|
|
141
|
+
crystallizedCumulative: bigint;
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
interface ReadTransactionArgs {
|
|
145
|
+
connection: Connection;
|
|
146
|
+
signature: string;
|
|
147
|
+
commitment: 'finalized';
|
|
148
|
+
}
|
|
149
|
+
interface ReadPostStateArgs {
|
|
150
|
+
connection: Connection;
|
|
151
|
+
input: FinalVoucherV2ReservationInput;
|
|
152
|
+
receipt: FinalVoucherV2ReservationReceipt;
|
|
153
|
+
}
|
|
154
|
+
interface SolanaReservationVerifierSeams {
|
|
155
|
+
readTransaction?: (args: ReadTransactionArgs) => Promise<SolanaReservationTransactionEvidence | null>;
|
|
156
|
+
readPostState?: (args: ReadPostStateArgs) => Promise<SolanaReservationPostStateEvidence>;
|
|
157
|
+
}
|
|
158
|
+
declare function verifySolanaFinalVoucherV2Reservation(connection: Connection, input: FinalVoucherV2ReservationInput, receipt: FinalVoucherV2ReservationReceipt, seams?: SolanaReservationVerifierSeams): Promise<void>;
|
|
159
|
+
declare function createSolanaFinalVoucherV2ReservationVerifier(connection: Connection, seams?: SolanaReservationVerifierSeams): VerifyFinalVoucherV2Reservation;
|
|
160
|
+
/** Production program ID is exported here only as a caller-side convenience;
|
|
161
|
+
* verification itself always uses the programId explicitly bound in input. */
|
|
162
|
+
declare const SOLANA_FINAL_VOUCHER_V2_PROGRAM_ID: PublicKey;
|
|
163
|
+
declare const SOLANA_FINAL_VOUCHER_V2_MEMO_PROGRAM_ID: PublicKey;
|
|
51
164
|
|
|
52
165
|
/**
|
|
53
166
|
* createSelfPayingComposeSend — the CLIENT-SIDE v0 + Address-Lookup-Table
|
|
54
167
|
* transport for the atomic revoke-then-register compose (K-T4e).
|
|
55
168
|
*
|
|
56
|
-
* WHY THIS EXISTS:
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
* dexter-vault-sdk tests/session.composeTxSize.test.ts; constants reused
|
|
61
|
-
* here, not re-derived). The LIVE (revoke-composed) path must therefore
|
|
169
|
+
* WHY THIS EXISTS: the live replacement carries a large, fully bound operation
|
|
170
|
+
* plus the V7 account set. The compatibility compose routes it through a v0
|
|
171
|
+
* transaction and address lookup table instead of relying on the legacy
|
|
172
|
+
* 1232-byte wire envelope. The LIVE replacement path therefore
|
|
62
173
|
* assemble a v0 `VersionedTransaction` with an ephemeral address lookup
|
|
63
174
|
* table holding every non-signer account of the composed instructions
|
|
64
175
|
* (vault, target session PDA, vaultUsdcAta, swig, swig wallet PDA, sysvar,
|
|
@@ -168,12 +279,11 @@ declare function createSelfPayingComposeSend(conn: Connection, feePayer: Signer,
|
|
|
168
279
|
* expose voucher signing for the session, and (e) tear the session down
|
|
169
280
|
* at close.
|
|
170
281
|
*
|
|
171
|
-
* The adapter does NOT
|
|
282
|
+
* The adapter does NOT mutate pending_voucher_count. That counter belongs
|
|
172
283
|
* to the facilitator's dexter_authority and is decremented inside the
|
|
173
|
-
* facilitator's `POST /tab/settle` tx
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
* passkey-signed session register/revoke layer.
|
|
284
|
+
* facilitator's `POST /tab/settle` tx atomically with the USDC transfer.
|
|
285
|
+
* After that POST lands, the adapter reads the Vault counter and SessionAccount
|
|
286
|
+
* in one RPC context and binds both into the passkey-signed V3 revocation.
|
|
177
287
|
*/
|
|
178
288
|
|
|
179
289
|
interface CreateSolanaVaultAdapterOptions {
|
|
@@ -195,9 +305,10 @@ interface CreateSolanaVaultAdapterOptions {
|
|
|
195
305
|
* vault account is not a signer for register/revoke (the passkey
|
|
196
306
|
* signature in the precompile sibling is the authorization). */
|
|
197
307
|
feePayer: Signer;
|
|
198
|
-
/** Confirmation options for
|
|
199
|
-
* match
|
|
200
|
-
*
|
|
308
|
+
/** Confirmation/preflight options for registration and replacement.
|
|
309
|
+
* Defaults to `confirmed` to match those existing paths. Session close is
|
|
310
|
+
* stricter: it always proves the exact revoke at `finalized` before the SDK
|
|
311
|
+
* reports the credential revoked or allows the key to be wiped. */
|
|
201
312
|
confirmOptions?: ConfirmOptions;
|
|
202
313
|
/** Testing/production seams (default: the real chain readers + the
|
|
203
314
|
* self-paying v0+ALT compose transport). Same seam idiom as
|
|
@@ -208,15 +319,56 @@ interface CreateSolanaVaultAdapterOptions {
|
|
|
208
319
|
interface SolanaAdapterSeams {
|
|
209
320
|
fetchSession?: typeof fetchSessionAccount;
|
|
210
321
|
fetchSessions?: typeof fetchVaultSessionAccounts;
|
|
322
|
+
fetchPasskeyAuthorization?: typeof fetchPasskeyAuthorizationState;
|
|
323
|
+
readCloseRevocationSnapshot?: ReadCloseRevocationSnapshot;
|
|
324
|
+
/** Full target-state reader used by close retry reconciliation. Unlike the
|
|
325
|
+
* legacy snapshot seam, this can prove that the old credential is already
|
|
326
|
+
* cleared or has been replaced without ever targeting the replacement. */
|
|
327
|
+
readCloseRevocationTargetState?: ReadCloseRevocationTargetState;
|
|
211
328
|
resolveUsdcAta?: typeof resolveVaultUsdcAta;
|
|
212
329
|
waitForSession?: typeof waitForSession;
|
|
213
330
|
/** Atomic-compose transport override: receives the FULL composed
|
|
214
|
-
* instruction list ([secp(
|
|
331
|
+
* instruction list ([secp(replace), replace] for a live V7 target),
|
|
215
332
|
* must send + confirm ATOMICALLY in one transaction. Production default:
|
|
216
333
|
* `createSelfPayingComposeSend` (v0+ALT — the compose does NOT fit a
|
|
217
334
|
* legacy transaction, K-T4a). */
|
|
218
335
|
composeSend?: (instructions: TransactionInstruction[]) => Promise<string>;
|
|
219
336
|
}
|
|
337
|
+
interface CloseRevocationSnapshot {
|
|
338
|
+
contextSlot: number;
|
|
339
|
+
programId: PublicKey;
|
|
340
|
+
vaultPda: PublicKey;
|
|
341
|
+
sessionPda: PublicKey;
|
|
342
|
+
sessionPubkey: Uint8Array;
|
|
343
|
+
maxAmount: bigint;
|
|
344
|
+
expiresAt: bigint;
|
|
345
|
+
allowedCounterparty: PublicKey;
|
|
346
|
+
nonce: number;
|
|
347
|
+
spent: bigint;
|
|
348
|
+
currentOutstanding: bigint;
|
|
349
|
+
maxRevolvingCapacity: bigint;
|
|
350
|
+
crystallizedCumulative: bigint;
|
|
351
|
+
lastLockedSequence: number;
|
|
352
|
+
expectedPendingVoucherCount: number;
|
|
353
|
+
}
|
|
354
|
+
interface ReadCloseRevocationSnapshotArgs {
|
|
355
|
+
connection: Connection;
|
|
356
|
+
vaultPda: PublicKey;
|
|
357
|
+
allowedCounterparty: PublicKey;
|
|
358
|
+
programId?: PublicKey;
|
|
359
|
+
commitment?: Commitment;
|
|
360
|
+
}
|
|
361
|
+
type ReadCloseRevocationSnapshot = (args: ReadCloseRevocationSnapshotArgs) => Promise<CloseRevocationSnapshot>;
|
|
362
|
+
type CloseRevocationTargetState = {
|
|
363
|
+
kind: 'live';
|
|
364
|
+
snapshot: CloseRevocationSnapshot;
|
|
365
|
+
} | {
|
|
366
|
+
kind: 'invalidated';
|
|
367
|
+
contextSlot: number;
|
|
368
|
+
sessionPda: PublicKey;
|
|
369
|
+
reason: 'absent' | 'cleared';
|
|
370
|
+
};
|
|
371
|
+
type ReadCloseRevocationTargetState = (args: ReadCloseRevocationSnapshotArgs) => Promise<CloseRevocationTargetState>;
|
|
220
372
|
interface AdapterRegisterIxParams {
|
|
221
373
|
vaultPda: PublicKey;
|
|
222
374
|
/** Swig STATE account (== vault.swig_address). */
|
|
@@ -243,4 +395,4 @@ declare function buildAdapterRegisterInstruction(p: AdapterRegisterIxParams): Tr
|
|
|
243
395
|
/** Factory entry point. */
|
|
244
396
|
declare function createSolanaVaultAdapter(opts: CreateSolanaVaultAdapterOptions): VaultAdapter;
|
|
245
397
|
|
|
246
|
-
export { type AdapterRegisterIxParams, type CreateSolanaVaultAdapterOptions, type SelfPayingComposeSend, type SelfPayingComposeSendOptions, type SolanaAdapterSeams, TX_SIZE_LIMIT_BYTES, buildAdapterRegisterInstruction, collectAltAddresses, compileComposeV0, createSelfPayingComposeSend, createSolanaVaultAdapter, passkeySignerFromP256Keypair };
|
|
398
|
+
export { type AdapterRegisterIxParams, type CreateSolanaVaultAdapterOptions, SOLANA_FINAL_VOUCHER_V2_MEMO_PROGRAM_ID, SOLANA_FINAL_VOUCHER_V2_PROGRAM_ID, type SelfPayingComposeSend, type SelfPayingComposeSendOptions, type SolanaAdapterSeams, SolanaFinalVoucherV2ReservationError, type SolanaReservationPostStateEvidence, type SolanaReservationTransactionEvidence, type SolanaReservationVerifierSeams, TX_SIZE_LIMIT_BYTES, buildAdapterRegisterInstruction, collectAltAddresses, compileComposeV0, createSelfPayingComposeSend, createSolanaFinalVoucherV2ReservationVerifier, createSolanaVaultAdapter, passkeySignerFromP256Keypair, verifySolanaFinalVoucherV2Reservation };
|