mppx 0.17.3 → 0.17.4

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 (41) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/Errors.d.ts +94 -0
  3. package/dist/Errors.js +83 -0
  4. package/dist/Store.d.ts +199 -11
  5. package/dist/Store.js +527 -48
  6. package/dist/cli/cli.js +141 -137
  7. package/dist/cli/internal.js +28 -6
  8. package/dist/cli/plugins/index.js +16 -12
  9. package/dist/cli/validate/challenge.d.ts +4 -0
  10. package/dist/cli/validate/challenge.js +9 -6
  11. package/dist/cloudflare/ChannelStore.d.ts +97 -0
  12. package/dist/cloudflare/ChannelStore.js +304 -0
  13. package/dist/cloudflare/Channels.d.ts +92 -0
  14. package/dist/cloudflare/Channels.js +325 -0
  15. package/dist/cloudflare/index.d.ts +5 -0
  16. package/dist/cloudflare/index.js +5 -0
  17. package/dist/internal/sse.js +32 -15
  18. package/dist/internal/version.d.ts +2 -2
  19. package/dist/internal/version.js +1 -1
  20. package/dist/stripe/server/Methods.d.ts +2 -0
  21. package/dist/stripe/server/Methods.js +2 -1
  22. package/dist/stripe/server/internal/record-payment.d.ts +49 -0
  23. package/dist/stripe/server/internal/record-payment.js +75 -18
  24. package/dist/tempo/Methods.d.ts +8 -0
  25. package/dist/tempo/Methods.js +18 -2
  26. package/dist/tempo/client/Charge.d.ts +32 -1
  27. package/dist/tempo/client/Charge.js +201 -3
  28. package/dist/tempo/client/Methods.d.ts +16 -0
  29. package/dist/tempo/internal/fee-payer.d.ts +0 -25
  30. package/dist/tempo/internal/fee-payer.js +50 -3
  31. package/dist/tempo/internal/zone.d.ts +79 -0
  32. package/dist/tempo/internal/zone.js +133 -0
  33. package/dist/tempo/server/Charge.d.ts +7 -3
  34. package/dist/tempo/server/Charge.js +98 -4
  35. package/dist/tempo/server/Methods.d.ts +40 -0
  36. package/dist/tempo/server/internal/html.gen.js +1 -1
  37. package/dist/tempo/session/server/ChannelStore.d.ts +5 -0
  38. package/dist/tempo/session/server/ChannelStore.js +2 -2
  39. package/dist/tempo/session/server/CredentialVerification.js +1 -1
  40. package/dist/validation/core.js +2 -0
  41. package/package.json +5 -1
@@ -1,18 +1,22 @@
1
- import{createClient as e,createTransport as t,custom as n,encodeFunctionData as r,erc20Abi as i,getAddress as a,hashTypedData as o,http as s,isAddress as c,isAddressEqual as l,keccak256 as u,parseAbi as d,parseUnits as f}from"viem";import{call as p,prepareTransactionRequest as m,readContract as h,sendCallsSync as g,sendTransactionSync as _,signTransaction as v,signTypedData as y}from"viem/actions";import*as b from"viem/chains";import{tempo as x}from"viem/chains";import{AbiParameters as S,Base64 as C,Bytes as w,Hash as T,Hex as E,Json as D}from"ox";import*as O from"zod/mini";import*as k from"node:child_process";import*as A from"node:fs";import*as j from"node:os";import*as M from"node:path";import{z as N}from"zod";import"node:readline";import{tempo as P,tempoModerato as F}from"viem/tempo/chains";import{ousd as ee,pathusd as I,usdce as te}from"viem/tokens";import{Abis as ne,Account as re,Actions as L,Addresses as ie,TokenId as ae,Transaction as oe,withFeePayer as se}from"viem/tempo";import{parseAccount as ce,privateKeyToAccount as le}from"viem/accounts";import{Channel as ue,KeyAuthorization as R,SignatureEnvelope as z,TempoAddress as de,TxEnvelopeTempo as fe}from"ox/tempo";var pe=Object.defineProperty,me=Object.getOwnPropertyDescriptor,he=Object.getOwnPropertyNames,ge=Object.prototype.hasOwnProperty,_e=(e,t)=>{let n={};for(var r in e)pe(n,r,{get:e[r],enumerable:!0});return t||pe(n,Symbol.toStringTag,{value:`Module`}),n},ve=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=he(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ge.call(e,s)&&s!==n&&pe(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=me(t,s))||r.enumerable});return e},ye=(e,t,n)=>(ve(e,t,`default`),n&&ve(n,t,`default`));const be=Symbol(`mppx.x402.asset`);function xe(e){return{[be]:!0,address:e.address,decimals:e.decimals,network:e.network,transfer:e.transfer}}function Se(e,t){let n=e(t.chainId);return xe({address:n.address,decimals:n.decimals,network:Me(t.chainId),transfer:Pe(t.transfer,n)})}const Ce={USDC:xe({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},we={USDC:xe({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},Te={USDC:xe({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:xe({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},Ee={USDC:xe({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})};function De(e){return typeof e!=`object`||!e?!1:e[be]===!0}function Oe(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function ke(e){return typeof e==`string`}function Ae(e,t){if(De(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(Oe(e)){let n=e.addresses[Ne(t)];return n?{address:n,decimals:e.decimals,name:e.name}:void 0}return{address:e}}function je(e,t,n){let r=Ae(e,n);return r?a(r.address)===a(t):!1}function Me(e){return`eip155:${e}`}function Ne(e){return Number(e.slice(7))}function Pe(e,t){if(e.type!==`eip3009`)return e;if(e.name)return{...e,name:e.name};if(!t.name)throw Error(`EIP-3009 token assets require a token name.`);return{...e,name:t.name}}var Fe=_e({base:()=>Ce,baseSepolia:()=>we,celo:()=>Te,celoSepolia:()=>Ee,define:()=>xe,fromToken:()=>Se,isAsset:()=>De,isRawAddress:()=>ke,isToken:()=>Oe,matches:()=>je,resolve:()=>Ae,toChainId:()=>Ne,toNetwork:()=>Me}),Ie=_e({base:()=>Le,baseSepolia:()=>Re,celo:()=>ze,celoSepolia:()=>Be});const Le=8453,Re=84532,ze=42220,Be=11142220,B={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},V={payment:`Payment`},Ve={evm:`evm`,stripe:`stripe`,tempo:`tempo`},He={charge:`charge`,session:`session`,subscription:`subscription`},Ue={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},We={v1:`v1`,v2:`v2`};function Ge(e,t){if(!(!e||typeof e!=`object`))return e[t]}function Ke(e){let t=C.toString(e);return JSON.parse(t)}function H(e){let t=D.canonicalize(e);return C.fromString(t,{pad:!1,url:!0})}var U=_e({address:()=>G,amount:()=>W,datetime:()=>Je,datetimeInput:()=>Ye,hash:()=>K,period:()=>Qe,signature:()=>q,toDate:()=>Xe,toDatetimeString:()=>Ze,unwrapOptional:()=>$e});import*as qe from"zod/mini";ye(U,qe);function W(){return O.string().check(O.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function Je(){return O.string().check(O.regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,`Invalid ISO 8601 datetime`))}function Ye(e=`Invalid ISO 8601 datetime`){return O.pipe(O.union([Je(),O.custom(e=>e instanceof Date)]),O.transform(Xe)).check(O.refine(e=>Number.isFinite(e.getTime()),e))}function Xe(e){return e instanceof Date?e:new Date(e)}function Ze(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function G(){return O.string().check(O.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function K(){return O.string().check(O.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function Qe(){return O.string().check(O.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function q(){return O.string().check(O.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function $e(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}const et=U.object({description:U.optional(U.string()),digest:U.optional(U.string().check(U.regex(/^sha-256=/,`Invalid digest format`))),expires:U.optional(Je()),header:U.optional(U.string().check(U.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,`Invalid HTTP header name`))),id:U.string().check(U.minLength(1)),intent:U.string(),method:U.string(),meta:U.optional(U.record(U.string(),U.string())),opaque:U.optional(U.string()),realm:U.string(),request:U.record(U.string(),U.unknown())});function tt(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=gt(o)?void 0:o,f=e.expires?Ze(e.expires):void 0,p=e.opaque??(i===void 0?void 0:H(i)),m=u?_t({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return et.parse({id:m,realm:c,method:a,intent:s,request:l,...n&&{description:n},...r&&{digest:r},...f&&{expires:f},...d!==void 0&&{header:d},...i!==void 0&&{meta:i},...p!==void 0&&{opaque:p}})}function nt(e){let t=[J(`id`,e.id),J(`realm`,e.realm),J(`method`,e.method),J(`intent`,e.intent),J(`request`,H(e.request))];e.description!==void 0&&t.push(J(`description`,e.description)),e.digest!==void 0&&t.push(J(`digest`,e.digest)),e.expires!==void 0&&t.push(J(`expires`,e.expires));let n=e.header;return n!==void 0&&!gt(n)&&t.push(J(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(J(`opaque`,H(e.meta))):t.push(J(`opaque`,e.opaque)),`${V.payment} ${t.join(`, `)}`}function J(e,t){if(/[\r\n]/.test(t))throw Error(`Invalid quoted-string value.`);return`${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`}function rt(e,t){let n=it(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=at(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>16384)throw Error(`Request parameter too large.`);if(a.method&&!/^[a-z][a-z0-9:_-]*$/.test(a.method))throw Error(`Invalid method: "${a.method}". Must be lowercase per spec.`);return tt({...a,request:Ke(r),...i&&{opaque:i}},t)}function it(e){let t=V.payment,[n]=ut(e,t);if(n===void 0)return null;let r=n+t.length;for(;r<e.length&&/\s/.test(e[r]??``);)r++;return e.slice(r)}function at(e){let t=Object.create(null),n=0;for(;n<e.length;){for(;n<e.length&&/[\s,]/.test(e[n]??``);)n++;if(n>=e.length)break;let r=n;for(;n<e.length&&/[A-Za-z0-9_-]/.test(e[n]??``);)n++;let i=e.slice(r,n).toLowerCase();if(!i)throw Error(`Malformed auth-param.`);for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]!==`=`)break;for(n++;n<e.length&&/\s/.test(e[n]??``);)n++;let[a,o]=ot(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function ot(e,t){if(e[t]===`"`)return st(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function st(e,t){let n=t,r=!1,i=t,a;for(;n<e.length;){let o=e[n];if(n++,r){a??=[];let t=o===`u`?e.slice(n,n+4):void 0;t&&/^[0-9A-Fa-f]{4}$/.test(t)?(a.push(String.fromCharCode(Number.parseInt(t,16))),n+=4):a.push(o),i=n,r=!1;continue}if(o===`\\`){a??=[],a.push(e.slice(i,n-1)),i=n,r=!0;continue}if(o===`"`)return[a?[...a,e.slice(i,n-1)].join(``):e.slice(t,n-1),n]}throw Error(`Unterminated quoted-string.`)}function ct(e,t,n){if(e.slice(t,t+n.length).toLowerCase()!==n.toLowerCase())return!1;let r=e[t+n.length];return!!(r&&/\s/.test(r))}function lt(e){return ut(e,V.payment).length>0||e.split(`,`).some(e=>e.trim().toLowerCase()===V.payment.toLowerCase())}function ut(e,t){let n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(r){i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}if(!ct(e,a,t))continue;let s=a-1;for(;s>=0&&/\s/.test(e[s]??``);)s--;s>=0&&e[s]!==`,`||n.push(a)}return n}function dt(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return ft(e.headers,t)}function ft(e,t){let n=e.get(B.wwwAuthenticate);if(!n)throw Error(`Missing ${B.wwwAuthenticate} header.`);return pt(n,t)}function pt(e,t){let n=ut(e,V.payment);if(n.length===0)throw Error(`No Payment schemes found.`);return n.map((r,i)=>{let a=i+1<n.length?n[i+1]:e.length;return rt(e.slice(r,a).replace(/,\s*$/,``),t)})}function mt(e){let t=[e.realm,e.method,e.intent,H(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!gt(n)&&t.push(n),t.push(e.opaque??(e.meta?H(e.meta):``)),t.join(`|`)}function ht(e){return e.header??B.authorization}function gt(e){return e?.toLowerCase()===B.authorization.toLowerCase()}function _t(e,t){let n=mt(e),r=w.fromString(t.secretKey),i=w.fromString(n),a=T.hmac256(r,i,{as:`Bytes`});return C.fromBytes(a,{url:!0,pad:!1})}const vt=65536;var yt=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},bt=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function xt(e){if(e.length>vt)throw new bt;let t=e.match(RegExp(`^${V.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new yt;try{let e=C.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=St(r);return{challenge:et.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:Ke(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new bt}}function St(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!Ct(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:H(e)}}function Ct(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function wt(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function Tt(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:H(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:H(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=C.fromString(s,{pad:!1,url:!0});return`${V.payment} ${c}`}function Et(e){return e.length>vt?null:e.split(`,`).map(e=>e.trim()).find(e=>RegExp(`^${V.payment}\\s+`,`i`).test(e))??null}var Dt=class extends Error{details;status=402;hint;constructor(e,t={}){super(e),this.details=t.details,t.cause!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t.cause,writable:!0})}toProblemDetails(e){return{type:this.type,title:this.title,status:this.status,detail:this.message,...this.details&&Object.keys(this.details).length>0&&{details:this.details},...this.hint&&{hint:this.hint},...e&&{challengeId:e}}}},Ot=class extends Dt{name=`InvalidChallengeError`;title=`Invalid Challenge`;status=402;type=`https://paymentauth.org/problems/invalid-challenge`;constructor(e={}){let{id:t,reason:n}=e,r=t?` "${t}"`:``,i=n?`: ${n}`:``;super(`Challenge${r} is invalid${i}.`)}},Y=class extends Dt{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,reason:n}=e;super(n?`Payment verification failed: ${n}.`:`Payment verification failed.`,{details:t})}},kt=class extends Dt{name=`PaymentExpiredError`;title=`Payment Expired`;type=`https://paymentauth.org/problems/payment-expired`;constructor(e={}){let{expires:t}=e;super(t?`Payment expired at ${t}.`:`Payment has expired.`)}},At=class extends Dt{name=`PaymentOutcomeUnknownError`;title=`Payment Outcome Unknown`;type=`https://paymentauth.org/problems/payment-outcome-unknown`;challenge;credential;transactionHash;constructor(e){let{cause:t,challenge:n,credential:r,transactionHash:i}=e;super(`Payment outcome is unknown after sending a credential for challenge "${n.id}". Do not blindly retry.`,{cause:t}),this.challenge=n,this.credential=r,this.transactionHash=i}};function jt(e,t){if(!e)throw new Ot({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new Ot({...t&&{id:t},reason:`malformed expires timestamp`});if(Date.parse(e)<=Date.now())throw new kt({expires:e})}function Mt(e){return e}function Nt(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}function Pt(e){return{encode(t){return C.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(C.toString(t)))}catch{throw new Ft}}}}var Ft=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const It=[`exact`],Lt=`PAYMENT-REQUIRED`,Rt=`PAYMENT-SIGNATURE`,zt=U.string().check(U.minLength(1)),Bt=U.number().check(U.refine(e=>e>0,`Must be positive`)),Vt=U.string().check(U.regex(/^\d+$/,`Invalid atomic amount`)),Ht=G(),Ut=U.string().check(U.regex(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),Wt=U.object({description:U.optional(U.string()),iconUrl:U.optional(U.string()),mimeType:U.optional(U.string()),serviceName:U.optional(U.string()),tags:U.optional(U.array(U.string())),url:zt});U.discriminatedUnion(`type`,[U.object({name:zt,type:U.literal(`eip3009`),version:zt}),U.object({name:U.optional(U.string()),type:U.literal(`permit2`),version:U.optional(U.string())})]);const Gt=U.object({amount:Vt,asset:zt,extra:U.optional(U.record(U.string(),U.unknown())),maxTimeoutSeconds:Bt,network:Ut,payTo:zt,scheme:U.enum(It)}),Kt=U.object({info:U.record(U.string(),U.unknown()),schema:U.record(U.string(),U.unknown())}),qt=U.record(U.string(),Kt),Jt=U.object({accepts:U.array(Gt).check(U.minLength(1)),error:U.optional(U.string()),extensions:U.optional(qt),resource:Wt,x402Version:U.literal(2)}),Yt=U.object({authorization:U.object({from:Ht,nonce:K(),to:Ht,validAfter:Vt,validBefore:Vt,value:Vt}),signature:q()}),Xt=U.object({permit2Authorization:U.object({deadline:Vt,from:Ht,nonce:Vt,permitted:U.object({amount:Vt,token:Ht}),spender:Ht,witness:U.object({to:Ht,validAfter:Vt})}),signature:q()}),Zt=U.union([Yt,Xt]),Qt=U.object({accepted:Gt,extensions:U.optional(qt),payload:Zt,resource:U.optional(Wt),x402Version:U.literal(2)});U.object({extensions:U.optional(qt),extra:U.optional(U.record(U.string(),U.unknown())),invalidMessage:U.optional(U.string()),invalidReason:U.optional(U.string()),isValid:U.boolean(),payer:U.optional(U.string())});const $t=U.object({amount:U.optional(Vt),errorMessage:U.optional(U.string()),errorReason:U.optional(U.string()),extensions:U.optional(qt),extra:U.optional(U.record(U.string(),U.unknown())),network:zt,payer:U.optional(U.string()),success:U.boolean(),transaction:U.string()});function en(e){let{extensions:t,resource:n,...r}=e;return Gt.parse(r)}const tn=Pt(Jt),nn=Pt(Qt),rn=Pt($t);tn.encode,tn.decode;function an(e){try{let t=JSON.parse(C.toString(e));return sn(t)}catch{throw new Ft}}const on=nn.encode;nn.decode,rn.encode,rn.decode;const sn=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new Ft;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new Ft;let n=Wt.parse(t.resource),r=t.extensions===void 0?void 0:qt.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}};function cn(e){let t=[H(e.accepted),H(e.resource),H(e.extensions)].join(`|`);return T.sha256(w.fromString(t),{as:`Hex`})}async function ln(e){let t=e.context?.account??e.config.account;if(!t?.signTypedData)throw Error(`x402 exact requires a typed-data signer.`);let n=e.challenge.request,r=en(n);if(pn(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?hn(n.extensions):n.extensions,o=r.extra?.assetTransferMethod??`eip3009`;if(o!==`eip3009`)throw Error(`x402 exact ${String(o)} signing is not implemented yet.`);let s=r.extra?.name,c=r.extra?.version;if(typeof s!=`string`||typeof c!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let l=Math.floor(Date.now()/1e3),u={from:a(t.address),nonce:i?.mppx?cn({accepted:r,extensions:i,resource:n.resource}):_n(),to:a(r.payTo),validAfter:(l-600).toString(),validBefore:(l+r.maxTimeoutSeconds).toString(),value:r.amount},d=await t.signTypedData({domain:{chainId:fn(r.network),name:s,verifyingContract:a(r.asset),version:c},message:{...u,value:BigInt(u.value),validAfter:BigInt(u.validAfter),validBefore:BigInt(u.validBefore)},primaryType:`TransferWithAuthorization`,types:dn});return on({accepted:r,...i?{extensions:i}:{},payload:{authorization:u,signature:d},...n.resource?{resource:n.resource}:{},x402Version:2})}function un(e){let t=e.challenge.request,n;try{n=en(t),pn(e.config,n)}catch{return!1}if(!t.resource||(n.extra?.assetTransferMethod??`eip3009`)!==`eip3009`)return!1;let r=n.extra?.name,i=n.extra?.version;return typeof r==`string`&&typeof i==`string`}const dn={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function fn(e){return Number(e.slice(7))}function pn(e,t){let n=fn(t.network);if(e.networks&&!e.networks.includes(n))throw Error(`x402 exact chain ID is not allowed: ${n}.`);let r=e.currencies??e.assets;if(r?.some(e=>ke(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=a(t.asset);if(!r.some(n=>je(n,e,t.network)))throw Error(`x402 exact currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`x402 exact amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=mn(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>f(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function mn(e,t){let n=e.currencies??e.assets,r=a(t.asset),i=n?.find(e=>je(e,r,t.network)),o=i?Ae(i,t.network):void 0;return o?.decimals===void 0?e.decimals:o.decimals}function hn(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:gn()}}}:e}function gn(){return vn().slice(2)}function _n(){return vn()}function vn(){let e=globalThis.crypto;if(!e?.getRandomValues)throw Error(`x402 exact requires crypto randomness.`);let t=e.getRandomValues(new Uint8Array(32));return`0x${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}const yn=Symbol.for(`mppx.x402.challenge`);function bn(e){return Object.defineProperty(e,yn,{value:!0}),e}function xn(e){return!!e?.[yn]}const Sn=[`authorization`],Cn=U.string().check(U.regex(/^\d+$/,`Invalid atomic amount`));U.object({name:U.string().check(U.minLength(1)),version:U.string().check(U.minLength(1))});const wn=U.object({chainId:U.number(),credentialTypes:U.optional(U.array(U.enum(Sn)).check(U.minLength(1))),decimals:U.optional(U.number()),permit2Address:U.optional(G()),splits:U.optional(U.array(U.object({amount:Cn,recipient:G()})))});U.object({amount:Cn,currency:G(),description:U.optional(U.string()),externalId:U.optional(U.string()),methodDetails:wn,recipient:G()});const Tn=U.object({amount:W(),chainId:U.number(),currency:G(),credentialTypes:U.optional(U.array(U.enum(Sn)).check(U.minLength(1))),decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),permit2Address:U.optional(G()),recipient:G(),splits:U.optional(U.array(U.object({amount:Cn,recipient:G()})))}),En=U.object({from:G(),nonce:K(),signature:q(),to:G(),type:U.literal(`authorization`),validAfter:Cn,validBefore:Cn,value:Cn}),Dn={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function On(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function kn(e){return T.keccak256(w.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function An(e){return`eip155:${e}`}function jn(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const Mn=Mt({name:`evm`,intent:`charge`,schema:{credential:{payload:En},request:U.pipe(Tn,U.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:o,recipient:s,splits:c,...l})=>({...l,amount:f(e,i).toString(),currency:a(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...o?{permit2Address:a(o)}:{},...c?{splits:c}:{}},recipient:a(s)})))}});function Nn(e){return Nt(Mn,{canHandleChallenge({challenge:t}){return!Pn(t)||un({challenge:t,config:e})},context:U.object({account:U.optional(U.custom())}),async createCredential({challenge:t,context:n}){if(Pn(t))return ln({challenge:t,config:e,context:n});let r=n?.account??e.account;if(!r?.signTypedData)throw Error(`EVM authorization requires a typed-data signer.`);let i=t.request;if(Fn(e,i),!i.methodDetails.credentialTypes?.includes(`authorization`))throw Error(`EVM authorization is not accepted by this challenge.`);if(i.methodDetails.splits?.length)throw Error(`EVM authorization does not support payment splits.`);let o=In(e,i),s=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return Tt(wt({challenge:t,payload:{from:a(r.address),nonce:kn(t),signature:await r.signTypedData({domain:On({authorization:o,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:a(r.address),nonce:kn(t),to:a(i.recipient),validAfter:0n,validBefore:BigInt(s),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:Dn}),to:a(i.recipient),type:`authorization`,validAfter:`0`,validBefore:s,value:i.amount},source:jn({address:a(r.address),chainId:i.methodDetails.chainId})}))}})}function Pn(e){return xn(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function Fn(e,t){let n=t.methodDetails.chainId,r=An(n);if(e.networks&&!e.networks.includes(n))throw Error(`EVM chain ID is not allowed: ${n}.`);let i=e.currencies??e.assets;if(i?.some(e=>ke(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=a(t.currency);if(!i.some(t=>je(t,e,r)))throw Error(`EVM currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`EVM charge amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=Ln(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>f(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function In(e,t){let n=e.currencies??e.assets,r=a(t.currency),i=An(t.methodDetails.chainId),o=n?.find(e=>je(e,r,i)),s=o?Ae(o,i):void 0;if(s?.transfer?.type===`eip3009`)return{name:s.transfer.name,version:s.transfer.version};if(e.authorization)return e.authorization;throw Error(`EVM authorization requires token name and version.`)}function Ln(e,t){let n=e.currencies??e.assets,r=a(t.currency),i=An(t.methodDetails.chainId),o=n?.find(e=>je(e,r,i)),s=o?Ae(o,i):void 0;return s?.decimals===void 0?e.decimals:s.decimals}function Rn(e){return[Rn.charge(e)]}(function(e){e.charge=Nn,e.assets=Fe,e.chains=Ie})(Rn||={});var zn=class extends Error{name=`Incur.BaseError`;shortMessage;details;constructor(e,t={}){let n=t.cause instanceof Error?t.cause.message:void 0,r=n?`${e}\n\nDetails: ${n}`:e;super(r,t.cause?{cause:t.cause}:void 0),this.shortMessage=e,this.details=n}walk(e){return Vn(this,e)}},Bn=class extends zn{name=`Incur.IncurError`;code;hint;retryable;exitCode;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.code=e.code,this.hint=e.hint,this.retryable=e.retryable??!1,this.exitCode=e.exitCode}};function Vn(e,t){if(t){let n=e?.cause;for(;n;){if(t(n))return n;n=n?.cause}return}let n=e;for(;n?.cause;)n=n.cause;return n}const X={mainnet:4217,testnet:42431},Hn={ousd:ee(X.mainnet).address,usdc:a(te(X.mainnet).address),pathUsd:I(X.mainnet).address},Un={[X.mainnet]:Hn.usdc,[X.testnet]:Hn.pathUsd},Wn=Object.freeze({[X.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[X.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})});X.mainnet,X.testnet;const Gn={[X.mainnet]:`https://rpc.tempo.xyz`,[X.testnet]:`https://rpc.moderato.tempo.xyz`},Z=(()=>{let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes(`--no-color`))&&(!!n.FORCE_COLOR||t.includes(`--color`)||(e.stdout||{}).isTTY&&n.TERM!==`dumb`||!!n.CI),i=(e,t,n,r)=>{let i=``,a=0,o=r;do i+=e.substring(a,o)+n,a=o+t.length,o=e.indexOf(t,a);while(~o);return i+e.substring(a)},a=r?(e,t,n=e)=>r=>{let a=`${r}`,o=a.indexOf(t,e.length);return~o?e+i(a,t,n,o)+t:e+a+t}:()=>String;return{isColorSupported:r,reset:a(`\x1B[0m`,`\x1B[0m`),bold:a(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:a(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:a(`\x1B[3m`,`\x1B[23m`),underline:a(`\x1B[4m`,`\x1B[24m`),inverse:a(`\x1B[7m`,`\x1B[27m`),hidden:a(`\x1B[8m`,`\x1B[28m`),strikethrough:a(`\x1B[9m`,`\x1B[29m`),black:a(`\x1B[30m`,`\x1B[39m`),red:a(`\x1B[31m`,`\x1B[39m`),green:a(`\x1B[32m`,`\x1B[39m`),yellow:a(`\x1B[33m`,`\x1B[39m`),blue:a(`\x1B[34m`,`\x1B[39m`),magenta:a(`\x1B[35m`,`\x1B[39m`),cyan:a(`\x1B[36m`,`\x1B[39m`),white:a(`\x1B[37m`,`\x1B[39m`),gray:a(`\x1B[90m`,`\x1B[39m`),bgBlack:a(`\x1B[40m`,`\x1B[49m`),bgRed:a(`\x1B[41m`,`\x1B[49m`),bgGreen:a(`\x1B[42m`,`\x1B[49m`),bgYellow:a(`\x1B[43m`,`\x1B[49m`),bgBlue:a(`\x1B[44m`,`\x1B[49m`),bgMagenta:a(`\x1B[45m`,`\x1B[49m`),bgCyan:a(`\x1B[46m`,`\x1B[49m`),bgWhite:a(`\x1B[47m`,`\x1B[49m`),blackBright:a(`\x1B[90m`,`\x1B[39m`),redBright:a(`\x1B[91m`,`\x1B[39m`),greenBright:a(`\x1B[92m`,`\x1B[39m`),yellowBright:a(`\x1B[93m`,`\x1B[39m`),blueBright:a(`\x1B[94m`,`\x1B[39m`),magentaBright:a(`\x1B[95m`,`\x1B[39m`),cyanBright:a(`\x1B[96m`,`\x1B[39m`),whiteBright:a(`\x1B[97m`,`\x1B[39m`),bgBlackBright:a(`\x1B[100m`,`\x1B[49m`),bgRedBright:a(`\x1B[101m`,`\x1B[49m`),bgGreenBright:a(`\x1B[102m`,`\x1B[49m`),bgYellowBright:a(`\x1B[103m`,`\x1B[49m`),bgBlueBright:a(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:a(`\x1B[105m`,`\x1B[49m`),bgCyanBright:a(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:a(`\x1B[107m`,`\x1B[49m`),link(e,t,n){return r?`\x1b]8;;${e}\x07${n?t:Z.underline(t)}\x1b]8;;\x07`:t}}})();function Kn(e,t){return Z.link(e,t)}function qn(e){return e.startsWith(`tempo:`)}function Jn(e,t,n=6,r){let[i,a]=(Number(e)/10**n).toString().split(`.`),o=i.replace(/\B(?=(\d{3})+(?!\d))/g,`_`),s=r?.explorerUrl&&r.token?Z.dim(Z.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):Z.dim(t);return`${a?`${o}.${a}`:o} ${s}`}const Yn={mainnet:Gn[X.mainnet],testnet:Gn[X.testnet]};function Xn(e,t={}){return e??(t.network?Yn[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}async function Zn(t={}){let n=Xn(t.rpcUrl,{network:t.network});if(!n)return P;let{getChainId:r}=await import(`viem/actions`),i=await r(e({transport:s(n)})),a=Object.values(await import(`viem/tempo/chains`)).filter(e=>typeof e==`object`&&!!e&&`id`in e&&e.id===i),o=a.find(e=>`serializers`in e&&e.serializers)??a[0];if(!o)throw Error(`Unknown chain ID ${i} from RPC ${n}`);return o}function Qn(e){return typeof e==`bigint`?e:e.amount}function $n(e){return e.id!==P.id}async function er(e,t,n,r={}){let{Actions:i}=await import(`viem/tempo`),[a,o]=await Promise.all([i.token.getBalance(e,{account:n,token:t}).then(Qn).catch(()=>0n),i.token.getMetadata(e,{token:t}).catch(e=>{if(r.requireDecimals)throw e;return{symbol:t}})]),s={"0x20c0000000000000000000000000000000000000":`PathUSD`,"0x20C000000000000000000000b9537d11c60E8b50":`USDC`}[t]??o.symbol,c=`decimals`in o&&typeof o.decimals==`number`?o.decimals:6;if(r.requireDecimals&&!(`decimals`in o&&typeof o.decimals==`number`))throw Error(`Token decimals are unavailable.`);return{balance:a,symbol:s,decimals:c,token:t}}function tr(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:1e4}function nr(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function rr(e){return new Bn({code:`KEYCHAIN_UNAVAILABLE`,message:`Linux keyring requires secret-tool. Install libsecret-tools.`,hint:`On Debian/Ubuntu, run: sudo apt install libsecret-tools gnome-keyring dbus-x11`,exitCode:69,cause:e})}function ir(e){if(e&&nr(e,`secret-tool`))throw rr(e)}function ar(e,t){return new Promise(n=>{k.execFile(e,t,{timeout:tr()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function or(){let e=M.join(process.env.XDG_CONFIG_HOME||M.join(j.homedir(),`.config`),`mppx`,`default`);return{get(){try{return A.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(t){A.mkdirSync(M.dirname(e),{recursive:!0}),A.writeFileSync(e,t,`utf-8`)},clear(){try{A.unlinkSync(e)}catch{}}}}function sr(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:or().get())}function cr(e=`main`){let t=`mppx`;return{async list(){let e=j.platform();if(e===`darwin`){let{stdout:e,error:n}=await ar(`security`,[`dump-keychain`]);if(n)return[];let r=[],i=e.split(`keychain:`);for(let e of i){let n=e.match(/"svce"<blob>="([^"]*)"/),i=e.match(/"acct"<blob>="([^"]*)"/);n?.[1]===t&&i?.[1]&&r.push(i[1])}return r}if(e===`linux`){let{stdout:e,stderr:n,error:r}=await ar(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(ir(r),r)return[];let i=`${e}\n${n}`,a=[],o=i.matchAll(/\baccount = (.+)/g);for(let e of o)e[1]&&a.push(e[1]);return a}throw Error(`Unsupported platform: ${e}`)},async get(){let n=j.platform();if(n===`darwin`){let{stdout:n,error:r}=await ar(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await ar(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return ir(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=j.platform();if(r===`darwin`){await ar(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await ar(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=k.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),tr());return r.stdin?.write(n),r.stdin?.end(),new Promise((e,t)=>{r.on(`close`,n=>{clearTimeout(i),n===0?e():t(Error(`secret-tool exited with code ${n}`))}),r.on(`error`,e=>{clearTimeout(i),t(nr(e,`secret-tool`)?rr(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=j.platform();if(n===`darwin`){await ar(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await ar(`secret-tool`,[`clear`,`service`,t,`account`,e]);ir(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function lr(e){let{privateKeyToAccount:t}=await import(`viem/accounts`),n=process.env.MPPX_PRIVATE_KEY?.trim();if(n)return{account:t(n),source:`environment`};let r=sr(e),i=await cr(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function ur(e){return(await lr(e)).account}function dr(e){return e}function fr(){return dr({method:`evm`,supports:e=>e.method===`evm`&&!xn(e),async setup({challenge:t,options:n}){let r=t.request,a=r.methodDetails,o=a?.chainId,c=o?pr(o):void 0,l=r.currency,u=await ur(n.account),d=[...Object.values(Ce),...Object.values(we),...Object.values(Te),...Object.values(Ee)],f=l??``;if(c&&l)try{let t=e({chain:c,transport:s()}),n=await h(t,{address:l,abi:i,functionName:`symbol`});n&&(f=n)}catch{}return{tokenSymbol:f,tokenDecimals:a?.decimals??6,explorerUrl:c?.blockExplorers?.default?.url,methods:[...Rn({account:u,currencies:d})]}}})}function pr(e){return Object.values(b).find(t=>t.id===e)}function mr(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`Decimals must be a non-negative integer.`);if(!/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))throw TypeError(`Value \`${e}\` is not a valid decimal number.`);let n=e.startsWith(`-`),[r=`0`,i=``]=(n?e.slice(1):e).split(`.`),a=i.slice(0,t).padEnd(t,`0`),o=BigInt(`${r||`0`}${a}`);return i.length>t&&i[t]>=`5`&&(o+=1n),n?-o:o}const hr=U.object({customer:U.optional(U.string().check(U.minLength(1))),hooks:U.optional(U.object({inputs:U.object({tax:U.object({calculation:U.string().check(U.minLength(1))})})})),metadata:U.optional(U.record(U.string(),U.string())),receipt_email:U.optional(U.string().check(U.minLength(1)))}),gr=U.custom(e=>typeof e==`function`),_r=U.union([hr,gr]),vr=Mt({name:`stripe`,intent:`charge`,schema:{credential:{payload:U.object({externalId:U.optional(U.string()),spt:U.string()})},request:U.pipe(U.object({amount:W(),currency:U.string(),decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),metadata:U.optional(U.record(U.string(),U.string())),networkId:U.string(),paymentIntentOptions:U.optional(_r),paymentMethodTypes:U.array(U.string()).check(U.minLength(1)),recipient:U.optional(U.string())}),U.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:mr(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});function yr(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return Nt(vr,{context:U.object({paymentMethod:U.optional(U.string())}),async createCredential({challenge:e,context:a}){let o=a?.paymentMethod??i;if(!o)throw Error(`paymentMethod is required (pass via context or parameters)`);let s=e.request.amount,c=e.request.currency,l=typeof e.request.externalId==`string`?e.request.externalId:void 0,u=e.request.methodDetails?.networkId;if(!u)throw Error(`networkId is required in challenge.methodDetails`);let d=e.request.methodDetails?.metadata;if(d?.externalId)throw Error(`methodDetails.metadata.externalId is reserved; use credential externalId instead`);let f=e.expires?Math.floor(new Date(e.expires).getTime()/1e3):Math.floor(Date.now()/1e3)+3600,p=await n({amount:s,challenge:e,client:t,currency:c,expiresAt:f,metadata:d,networkId:u,paymentMethod:o}),m=l??r;return Tt({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function br(e){return[yr(e)]}(function(e){e.charge=yr})(br||={});function xr(){return dr({method:`stripe`,supports(e){return e.method===`stripe`&&e.intent===`charge`},async setup({challenge:e,methodOpts:t}){let n=e.request,r=n.currency,i=Cr(N.object({paymentMethod:N.string(),secretKey:N.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new Bn({code:`MISSING_ENV`,message:`MPPX_STRIPE_SECRET_KEY environment variable is required for Stripe payments.`,exitCode:2});return{tokenSymbol:r?.toUpperCase()??``,tokenDecimals:n.decimals??2,methods:[br.charge({paymentMethod:i.paymentMethod,createToken:async({paymentMethod:e,amount:t,currency:n,networkId:r,expiresAt:i,metadata:o})=>{let s=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()}),c=Sr(a),l=process.env.MPPX_STRIPE_SPT_URL?process.env.MPPX_STRIPE_SPT_URL:c?`https://api.stripe.com/v1/test_helpers/shared_payment/granted_tokens`:`https://api.stripe.com/v1/shared_payment/issued_tokens`;if(r){let e=c?`seller_details[network_id]`:`seller_details[network_business_profile]`;s.set(e,r)}if(o)for(let[e,t]of Object.entries(o))s.set(`metadata[${e}]`,t);let u={Authorization:`Basic ${btoa(`${a}:`)}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":`2026-07-29.preview`},d=await globalThis.fetch(l,{method:`POST`,headers:u,body:s});if(!d.ok){let a=await d.json();if(c&&(o||r)&&a.error.message.includes(`Received unknown parameter`)){let r=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()});if(d=await globalThis.fetch(l,{method:`POST`,headers:u,body:r}),!d.ok)throw new Bn({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${(await d.json()).error.message}`,exitCode:77})}else throw new Bn({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${a.error.message}`,exitCode:77})}let{id:f}=await d.json();return f}})]}},formatReceiptField(e,t){if(e===`reference`&&typeof t==`string`&&t.startsWith(`pi_`)){let e=process.env.MPPX_STRIPE_SECRET_KEY,n=`https://dashboard.stripe.com${e!==void 0&&Sr(e)?`/test`:``}/payments/${t}`;return Z.link(n,t,!0)}}})}function Sr(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function Cr(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}const wr=Symbol.for(`mppx.fetch.skipPayment`);function Tr(e,t,n){return async(r,i)=>{let a=new Request(r,i),o=Dr(a.headers)??n?.challenge,{response:s}=await t.send((t,n)=>e(t,{...n,...i?.[wr]?{[wr]:!0}:{}}),a,{...n,challenge:o});if(s.status===402&&o)for(let e of Er(s))e.method===o.method&&e.intent===o.intent&&await t.challenge(s,{...n,challenge:e},a.url);return s}}function Er(e){try{return dt(e)}catch{return[]}}function Dr(e){for(let[,t]of e){let e=Et(t);if(e)try{return xt(e).challenge}catch{}}}const Or=Symbol(`mppx.deferredContext`);function kr(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=Pr(n)}return t}function Ar(e,t){let n=kr(e),r=Vr(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[Pr(e)]??1,index:t}));return{definition:r,entries:i,header:Mr(i),keys:n}}function jr(e){let t=e.split(/\s*,\s*/).map(e=>e.trim()).filter(Boolean);if(t.length===0)throw Error(`Accept-Payment header is empty.`);return t.map((e,t)=>zr(e,t))}function Mr(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${Gr(n)}`}).join(`, `)}function Nr(e,t,n,r){let i=new Map;for(let e of t){let t=Pr(e),n=i.get(t);n?n.push(e):i.set(t,[e])}return e.flatMap((e,t)=>{let a=i.get(Pr(e));if(!a)return[];let o=Fr(e,n);return!o||o.q<=0?[]:a.filter(t=>t.canHandleChallenge?.(r===void 0?{challenge:e}:{challenge:e,context:r})??!0).map(n=>({challenge:e,index:t,match:o,method:n}))}).sort((e,t)=>Rr(e.challenge)-Rr(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function Pr(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function Fr(e,t){let n;for(let r of t){if(!Ir(e,r))continue;let t={...r,specificity:Lr(r)};(!n||t.specificity>n.specificity||t.specificity===n.specificity&&t.q>n.q||t.specificity===n.specificity&&t.q===n.q&&t.index<n.index)&&(n=t)}return n}function Ir(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function Lr(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function Rr(e){return+!!xn(e)}function zr(e,t){let n=/^(?<method>[^/;\s]+|\*)\s*\/\s*(?<intent>[^/;\s]+|\*)(?<params>(?:\s*;\s*.+)?)$/u.exec(e),r=n?.groups?.method,i=n?.groups?.intent;if(!r||!i)throw Error(`Invalid Accept-Payment entry: ${e}`);Kr(r,`method`),Kr(i,`intent`);let a=1;for(let t of Br(n.groups?.params)){if(!t)continue;let n=/^(?<name>[A-Za-z0-9_-]+)\s*=\s*(?<value>\S+)$/u.exec(t),r=n?.groups?.name,i=n?.groups?.value;if(!r||!i)throw Error(`Invalid Accept-Payment parameter: ${t}`);r===`q`&&(a=Ur(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function Br(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function Vr(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>Pr(e))),a={};for(let[e,t]of Object.entries(r??{})){if(!i.has(e))throw Error(`Unknown payment preference "${e}". Available: ${[...i].join(`, `)}`);a[e]=Hr(t,`payment preference "${e}"`)}return a}function Hr(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return Wr(e,t)}function Ur(e,t){if(!/^0(?:\.\d{0,3})?$|^1(?:\.0{0,3})?$/.test(e))throw Error(`Invalid q-value for ${t}. Expected an HTTP qvalue.`);return Wr(Number(e),t)}function Wr(e,t){if(e<0||e>1)throw Error(`Invalid q-value for ${t}. Expected a value between 0 and 1.`);let n=Math.round(e*1e3);if(Math.abs(e*1e3-n)>1e-9)throw Error(`Invalid q-value for ${t}. Expected at most 3 decimal places.`);return n/1e3}function Gr(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function Kr(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}function qr(e){let t=``,n=!1,r=!1,i,a=``;function o(t){if(t===``){i!==void 0&&e({data:i,event:a||`message`}),i=void 0,a=``;return}if(t.startsWith(`:`))return;let n=t.indexOf(`:`),r=n===-1?t:t.slice(0,n),o=n===-1?``:t.slice(n+1);o.startsWith(` `)&&(o=o.slice(1)),r===`data`?i=i===void 0?o:`${i}\n${o}`:r===`event`&&(a=o)}return{feed(e){if(!n&&e&&(n=!0,e.startsWith(``)&&(e=e.slice(1))),r&&e&&(r=!1,e.startsWith(`
2
- `)&&(e=e.slice(1))),t+=e,!/[\r\n]/.test(e))return;let i=0,a=/\r\n?|\n/g;for(let e=a.exec(t);e;e=a.exec(t))o(t.slice(i,e.index)),i=a.lastIndex,e[0]===`\r`&&i===t.length&&(r=!0);t=t.slice(i)}}}const Jr=[B.authorization,Lt,`PAYMENT-RESPONSE`,Rt];function Yr(e,t,n){let r=new Headers(e.headers);for(let e of Jr)e===B.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}function Xr(e){if(typeof e==`string`)try{let t=JSON.parse(e),n=t?.id;return t?.jsonrpc!==`2.0`||typeof t?.method!=`string`?void 0:typeof n==`string`||typeof n==`number`?n:void 0}catch{return}}function Zr(e){if(typeof e?.body!=`string`)return!1;try{let t=JSON.parse(e.body);return t?.jsonrpc===`2.0`&&t?.method===`tools/call`&&t.params?._meta?.[`mppx/payment-client`]===!0}catch{return!1}}const Qr=1048576,$r=new WeakMap;function ei(e){let t=Xr(e?.body);if(t===void 0)return;let n=new Headers(e?.headers);if(n.has(`mcp-method`))return t;let r=n.get(`accept`)?.toLowerCase()??``;return r.includes(`application/json`)&&r.includes(`text/event-stream`)?t:void 0}function ti(e){if(!e||typeof e!=`object`)return;let t=e,n=t.id;if(t.jsonrpc!==`2.0`||n!==void 0&&typeof n!=`string`&&typeof n!=`number`)return;let r=`error`in t;if(r!==`result`in t)return r?Number.isInteger(t.error?.code)&&typeof t.error?.message==`string`?e:void 0:n!==void 0&&typeof t.result==`object`?e:void 0}function ni(e){if(!e||typeof e!=`object`)return;let t=e?.challenges;if(!Array.isArray(t)||t.length===0)return;let n=[];for(let e of t){let t=et.safeParse(e);if(!t.success)return;n.push(t.data)}let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function ri(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:ni(e.error.data):ni(e.result?._meta?.[`org.paymentauth/payment-required`])}function ii(e,t){return!e||e.id!==t?[]:ri(e)?.challenges??[]}async function ai(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=qr(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=ti(JSON.parse(e.data))}catch{}});try{for(;;){if(i)return a;let{done:e,value:s}=await t.read();if(e)return o.feed(n.decode()),a;if(r+=s.byteLength,r>Qr)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function oi(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=``;try{for(;;){let{done:e,value:a}=await t.read();if(e)return ti(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>Qr)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function si(e){let t=$r.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>Qr)){if(t.includes(`application/json`))return oi(e);if(t.includes(`text/event-stream`))return ai(e)}})();return $r.set(e,n),n}function ci(){return{getChallenges(e,t){let n=ei(t);return e.status===402||n===void 0?[]:si(e).then(e=>ii(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=xt(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}function li(){return{getChallenges(e){let t=e.headers.get(B.wwwAuthenticate);return e.status!==402||!t||!lt(t)?[]:dt(e)},setCredential(e,t,n){return Yr(e,n?.challenge?ht(n.challenge):B.authorization,t)}}}function ui(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(Lt);if(!t)return[];let n=an(t);return n.accepts.flatMap((e,t)=>{let r=Gt.safeParse(e);if(!r.success)return[];let i=r.data;return bn(tt({id:`x402:${t}`,intent:`charge`,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return Yr(e,Rt,t)}}}function di(e){return e}function fi(){let e=[li(),ui(),ci()],t=new WeakMap,n=(e,n)=>{for(let r of n)t.set(r,e);return n},r=(t,r)=>{let i=(a,o)=>{for(let s=a;s<e.length;s++){let a=e[s],c=a.getChallenges(t,r);if(c instanceof Promise)return c.then(e=>i(s+1,[...o,...n(a,e)]));o.push(...n(a,c))}return o};return i(0,[])};return di({name:`http`,isPaymentRequired(e,t){if(e.status===402)return!0;let n=r(e,t);return n instanceof Promise?n.then(e=>e.length>0):n.length>0},getChallenges(e,t){return r(e,t)},setCredential(n,r,i){let a=i?.challenge?t.get(i.challenge):void 0,o=e[0];if(!a&&!o)throw Error(`No protocol to attach the credential.`);return(a??o).setCredential(n,r,i)}})}const pi=new WeakMap;function mi(e,t){return pi.set(e,t),e}function hi(e){return pi.has(e)}function gi(e,t){return Promise.resolve(pi.get(e)?.(t))}function _i(e){return pi.get(e)}const vi=new WeakMap,yi=new WeakMap,bi=new WeakMap,xi=new WeakMap;function Si(e,t){return vi.set(e,t),e}function Ci(e){vi.delete(e)}function wi(e,t,n){vi.has(e)&&yi.set(t,n)}function Ti(e){return yi.get(e)}function Ei(e,t){return Promise.resolve(vi.get(e)?.(t)??t.response)}function Di(e,t){return xi.set(e,t),e}function Oi(e,t){try{return xi.get(e)?.(t)}catch{return}}function ki(e,t){bi.set(e,t)}function Ai(e){return bi.get(e)??yi.get(e)?.origin}function ji(e,t,n){if(!Mi(e)&&(e.method!==`tempo`||e.intent!==`session`))return;t=typeof t==`function`?t():t;let{realm:r}=e;if(r.toLowerCase()===t.hostname.toLowerCase())return;let i=t.origin.toLowerCase();for(let[e,t]of Object.entries(n??{}))if(t===r&&Ni(e)===i)return;throw Error(`Refusing to sign Tempo proof for realm ${JSON.stringify(r)} from ${t.origin}. Pin the realm to this origin with \`trustedTempoProofRealms\` if this server is expected to issue it.`)}function Mi(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Ni(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}const Pi=Symbol.for(`mppx.fetch.wrapper`),Fi=Symbol.for(`mppx.fetch.identity`),Ii=Symbol.for(`mppx.fetch.skipPayment`),Li=65536,Ri=new WeakMap;async function zi(e){if(!e.body)return e;let t=e.clone().body.getReader(),n=[],r=0,i=!1,a=setTimeout(()=>{i=!0,t.cancel().catch(()=>{})},2e3);try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(n.push(a),r+=a.byteLength,r>Li){i=!0;break}}}finally{clearTimeout(a),t.cancel().catch(()=>{})}if(!i)return e;e.body.cancel().catch(()=>{});let o=new Headers(e.headers);o.delete(`content-length`),o.set(`Mppx-Body-Truncated`,`true`);let s=new Response(new Blob(n).slice(0,Li),{headers:o,status:e.status,statusText:e.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{value:e[t]});return s}async function Bi(e,t){let n=e?.attempt.settle;if(!n)return t.status!==`pending`;e.attempt.settle=void 0;let r=await n(t);return r||(e.attempt.settle=n),r}function Vi(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=fi(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&ua(e.fetch)),d=e.eventDispatcher??Ui(),f=t??Ar(a),p=da(r),m=async(e,t,n)=>u?(await u.send(p,new Request(e,t),n)).response:p(e,t),h=async(e,t,r)=>{let g=la(e,t?.headers),_=g.has(B.acceptPayment),v=ga(g,f),y=sa(e,t,g),b=oa(e,t,g,v.header,_,n),x=await m(fa(b.input),b.init),S=ca(b.init,await y);if(t?.[Ii]||Zr(S)||!await c.isPaymentRequired(x,S))return x;let C=t?.context,{context:w,orderChallenges:T,...E}=S??{},D,O,k,A,j;try{for(let n=0;n<i;n++){O=await c.getChallenges(x,S);let i=(await _a(Nr(O,a,v.entries,C),T??s))[0];if(!i){if(await Bi(A,{challenges:O,response:x,status:`rejected`}),n>0)return x;throw Error(`No method found for challenges: ${O.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let f=i.challenge;D=f,k=i.method,D.expires&&jt(D.expires,D.id),await u?.challenge(x,{challenge:f},xa(b.input).href);let g=await Ca(x,b.input,b.input,E);ji(f,()=>xa(g),l);let _=A,y=nt(f),w=_?.method===i.method&&_?.key===y,M=!1;if(_){let e=await Bi(_,{challenges:O,response:x,status:w?`pending`:`rejected`});M=w&&!e}A=M?_:void 0;let N=Ji(async n=>{if(n===void 0&&M&&_)return _.promise;M&&_&&(await Bi(_,{status:`rejected`}),A=void 0),pa(e,t)?.throwIfAborted();let r=n??C;if(!hi(i.method))return ha(f,i.method,r);let a={origin:xa(g).origin,prepare:()=>gi(i.method,{challenge:f,context:r,fetch:u?Tr(p,u,{challenge:f}):p,input:g,signal:pa(e,t)})},o=a.prepare().then(()=>ha(f,i.method,r,a));return A={context:r,attempt:a,key:n===void 0?y:void 0,method:i.method,promise:o},o}),P=await d.emit(`challenge.received`,Yi({challenge:f,challenges:O,createCredential:N,init:t,input:e,method:i.method,response:x}))??(o?await o(D,{createCredential:N}):void 0)??await N(),F=A;F&&await F.promise.catch(()=>void 0)!==P&&(await Bi(F,{status:`rejected`}),A=void 0);let ee=A?A.context:C;ma(P),await d.emit(`credential.created`,Xi({challenge:f,credential:P,init:t,input:e,method:i.method,response:x}));let I=e=>new At({cause:e,challenge:f,credential:P,transactionHash:Oi(i.method,P)});try{x=await m(g,{...c.setCredential({...E,headers:b.headers},P,{challenge:f}),redirect:`manual`},{challenge:f})}catch(e){throw j=I(e),e}let te=await c.isPaymentRequired(x,S);if(te||(await Bi(F,{response:x,status:x.status>=300&&x.status<400?`pending`:x.ok?`accepted`:`rejected`}),A=void 0),x.ok&&Wi(d,`payment.response`)&&await d.emit(`payment.response`,Zi({challenge:f,credential:P,init:t,input:e,method:i.method,response:x})),!te){if(x.status>=500&&Wi(d,`payment.failed`)){try{x=await zi(x)}catch(e){throw j=I(e),x=new Response(null,{headers:x.headers,status:x.status,statusText:x.statusText}),e}await d.emit(`payment.failed`,Qi({challenge:f,challenges:O,error:I(),init:t,input:e,method:i.method,response:x}))}return x.ok?Ei(i.method,{context:ee,challenge:f,credential:P,fetch:p,headers:b.headers,input:g,...r?{refetch:()=>h(fa(b.input),t,!1)}:{},response:x,signal:pa(e,t)}):x}}O=void 0;try{O=await c.getChallenges(x,S)}catch{}return await Bi(A,{challenges:O,response:x,status:`rejected`}),x}catch(n){throw await Bi(A,{challenges:O,response:x,status:`rejected`}),await d.emit(`payment.failed`,Qi({challenge:D,challenges:O,error:j??n,init:t,input:e,method:k,response:x})),n}},g=(e,t)=>h(e,t,!0);return g[Pi]=p,u&&(g[Fi]=u),g}function Hi(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return Array.isArray(e)?Object.fromEntries(e):e}function Ui(){let e={"*":new Set,"challenge.received":new Set,"credential.created":new Set,"payment.failed":new Set,"payment.response":new Set},t={async emit(t,n){switch(t){case`challenge.received`:{let r;for(let t of e[`challenge.received`]){let e=await Gi(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await qi(e[`*`],t,n),r}case`credential.created`:await Ki(e[`credential.created`],n),await qi(e[`*`],t,n);return;case`payment.failed`:await Ki(e[`payment.failed`],n),await qi(e[`*`],t,n);return;case`payment.response`:await Ki(e[`payment.response`],n),await qi(e[`*`],t,n);return}},on:(t,n)=>{switch(t){case`*`:case`challenge.received`:case`credential.created`:case`payment.failed`:case`payment.response`:return e[t].add(n),()=>e[t].delete(n);default:throw Error(`Unknown client event "${String(t)}".`)}}};return Ri.set(t,t=>e[t].size>0||e[`*`].size>0),t}function Wi(e,t){return Ri.get(e)?.(t)??!0}async function Gi(e,t){try{return await e(t)}catch{return}}async function Ki(e,t){for(let n of e)try{await n(t)}catch{}}async function qi(e,t,n){await Ki(e,Object.freeze({name:t,payload:n}))}function Ji(e){let t;return n=>(t??=e(n),t)}function Yi(e){return Object.freeze({challenge:ra(e.challenge),challenges:e.challenges.map(e=>ra(e)),createCredential:e.createCredential,init:$i(e.init),input:ea(e.input),method:ta(e.method),response:na(e.response)})}function Xi(e){return Object.freeze({challenge:ra(e.challenge),credential:e.credential,init:$i(e.init),input:ea(e.input),method:ta(e.method),...e.response===void 0?{}:{response:na(e.response)}})}function Zi(e){return Object.freeze({challenge:ra(e.challenge),credential:e.credential,init:$i(e.init),input:ea(e.input),method:ta(e.method),response:na(e.response)})}function Qi(e){return Object.freeze({...e.challenge?{challenge:ra(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>ra(e))}:{},error:e.error,init:$i(e.init),input:ea(e.input),...e.method?{method:ta(e.method)}:{},...e.response===void 0?{}:{response:na(e.response)}})}function $i(e){if(e)return aa({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function ea(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function ta(e){return aa(Object.assign({},e))}function na(e){if(e instanceof Response)try{return e.clone()}catch{let t=new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText});for(let n of[`redirected`,`type`,`url`])Object.defineProperty(t,n,{value:e[n]});return t}return ra(e)}function ra(e){try{return ia(structuredClone(e))}catch{return aa(e)}}function ia(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))ia(t);return e}function aa(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function oa(e,t,n,r,i,a){let o=!!r&&!i&&va(e,a);if(!o)return{headers:n,init:t,input:e};let s=new Headers(e instanceof Request?e.headers:void 0);return n.forEach((e,t)=>{s.set(t,e)}),s.set(B.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function sa(e,t,n){if(!(!(e instanceof Request)||t?.body!==void 0||!e.body||e.bodyUsed)){if(!n.has(`mcp-method`)){let e=n.get(`accept`)?.toLowerCase()??``;if(!e.includes(`application/json`)||!e.includes(`text/event-stream`))return}try{return e.clone().text().catch(()=>void 0)}catch{return}}}function ca(e,t){return t===void 0?e:{...e,body:t}}function la(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function ua(e){return e[Fi]}function da(e){let t=e;for(;t[Pi];)t=t[Pi];return t}function fa(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function pa(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function ma(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
3
- `))throw Error(`Credential header value contains illegal newline characters`)}async function ha(e,t,n,r){let i=t.context&&n!==void 0?t.context.parse(n):void 0,a=i===void 0?{challenge:e}:{challenge:e,context:i};return r?.origin&&ki(a,r.origin),r&&wi(t,a,r),t.createCredential(a)}function ga(e,t){let n=e.get(B.acceptPayment);if(!n)return t;try{return{...t,entries:jr(n),header:n}}catch{return t}}async function _a(e,t){return t?t(e):e}function va(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=xa(e);return t===`same-origin`?!ba()||n.origin===globalThis.location.origin:t.origins.some(e=>ya(n,e))}function ya(e,t){if(t.startsWith(`*.`)){let n=t.slice(1);return e.hostname.endsWith(n)||e.hostname===t.slice(2)}return e.origin===new URL(t).origin}function ba(){return globalThis.location!==void 0}function xa(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,ba()?globalThis.location.href:void 0)}function Sa(e,t){let n=e instanceof Request?e:void 0;if((t.mode??n?.mode)===`no-cors`)throw Error(`Cannot automatically pay a no-cors request: it cannot carry a credential.`);if((t.cache??n?.cache)===`only-if-cached`)throw Error(`Cannot automatically pay an only-if-cached request: its retry cannot reach the server.`)}async function Ca(e,t,n,r){if(Sa(t,r),!e.url)return t;let i=new URL(e.url),a=xa(n);if(i.origin!==a.origin)throw Error(`Refusing to send payment credential across redirect from ${a.origin} to ${i.origin}`);let o=(r.method??(t instanceof Request?t.method:`GET`)).toUpperCase();if(e.redirected&&o!==`GET`&&o!==`HEAD`)throw Error(`Cannot automatically pay a redirected ${o} request. Use prepareRequest() to preserve redirect semantics.`);if(t instanceof Request){let n=r.body==null?t.clone():t,i=new Request(n,t.mode===`navigate`&&r.mode===void 0?{...r,mode:`same-origin`}:r);return i.url.split(`#`)[0]===e.url?i:i.body?new Request(e.url,{body:await i.arrayBuffer(),cache:i.cache,credentials:i.credentials,headers:i.headers,integrity:i.integrity,keepalive:i.keepalive,method:i.method,mode:i.mode,redirect:i.redirect,referrer:i.referrer,referrerPolicy:i.referrerPolicy,signal:i.signal}):new Request(e.url,i)}return e.url}function wa(e={}){let{account:t}=e;return(e,{account:n}={})=>{let r=n??t;if(!r){if(!e.account)throw Error("No `account` provided. Pass `account` to parameters or context.");return e.account}return ce(r)}}function Ta(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}const Ea={[P.id]:P,[F.id]:F};function Da(e,t={}){return s(e.url,{fetchFn:e.fetch,fetchOptions:{headers:Ta(e)},...t})}function Oa(r){let{chain:i,getClient:a,remoteFeePayer:o,rpcUrl:c}=r;return a?!i?.serializers&&!o?a:async e=>{let r=await a(e),s=r;if(o&&r.transport.key!==`feePayer`){let e=r.request.bind(r),i=se(n({request:t=>e(t)},{retryCount:0}),Da(o,{retryCount:r.transport.retryCount}))({account:r.account,chain:r.chain,pollingInterval:r.pollingInterval,retryCount:0}),a=t({...i.config,retryCount:0},i.value);s=Object.assign({},r,{request:a.request,transport:{...a.config,...a.value}})}return!i?.serializers||s.chain?.serializers?.transaction?s:Object.assign({},s,{chain:{...i,...e.chainId===void 0?{}:{id:e.chainId},...s.chain,formatters:s.chain?.formatters??i.formatters,prepareTransactionRequest:s.chain?.prepareTransactionRequest??i.prepareTransactionRequest,serializers:s.chain?.serializers?.transaction?s.chain.serializers:i.serializers}})}:({chainId:t})=>{if(!c)throw Error("No `rpcUrl` provided.");let n=t||Number(Object.keys(c)[0]),r=c[n];if(!r)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let a=o?se(s(r),Da(o)):s(r);return e({chain:Ea[n]??{...i,id:n},transport:a})}}function ka(e,t){if(t!==void 0&&e.chain?.id!==void 0&&e.chain.id!==t)throw Error(`Chain ID mismatch: expected ${t}, got ${e.chain.id}.`)}function Aa(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}const ja=E.slice(T.keccak256(w.fromString(`mpp`),{as:`Hex`}),0,4);function Ma(e){let t=T.keccak256(w.fromString(e),{as:`Hex`});return E.toBytes(E.slice(t,0,10))}function Na(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(E.toBytes(ja),0),i[4]=1,i.set(Ma(t),5),n&&i.set(Ma(n),15),i.set(Pa(r),25),E.fromBytes(i)}function Pa(e){let t=T.keccak256(w.fromString(e),{as:`Hex`});return E.toBytes(E.slice(t,0,7))}function Fa(e,t){return de.resolve(e).toLowerCase()===de.resolve(t).toLowerCase()}const Ia=10000n,La=[Hn.pathUsd,Hn.usdc,Hn.ousd];async function Ra(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t;if(!Number.isFinite(o)||o<0||o>50)throw Error(`Auto-swap slippage must be between 0 and 50 percent.`);if(t.maxAmountIn!==void 0&&t.maxAmountIn<=0n)throw Error(`Auto-swap maxAmountIn must be positive.`);let s=a.filter(e=>!Fa(e,i)),c=await Promise.allSettled([h(e,{...L.token.getBalance.call(e,{account:n,token:i}),account:null}),...s.map(t=>h(e,{...L.token.getBalance.call(e,{account:n,token:t}),account:null}))]),l=c[0];if(l.status!==`fulfilled`)throw l.reason;let u=l.value;if(u>=r)return;let d=r-u,f=BigInt(Math.round(o*100)),p=t.maxAmountIn??d+d*f/Ia;for(let t=0;t<s.length;t++){let n=c[t+1];if(n.status!==`fulfilled`)continue;let r=n.value;if(r<=0n)continue;let a=s[t];try{let t=await L.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:d});if(t<=0n||t>p)continue;let n=t+t*f/Ia,o=n<p?n:p;if(r>=o)return[L.token.approve.call(e,{amount:o,spender:ie.stablecoinDex,token:a}),L.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:d,maxAmountIn:o})]}catch{}}throw new Ba({currency:i})}function za(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...e.fallback===!1?[]:t.filter(t=>!e.tokenIn.some(e=>Fa(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var Ba=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}};function Va(e){let t=BigInt(e.amount),n=e.methodDetails?.splits??[],r=n.reduce((e,t)=>e+BigInt(t.amount),0n);if(r>=t)throw Error(`Invalid charge request: split total must be less than total amount.`);let i=t-r;if(i<=0n)throw Error(`Invalid charge request: primary transfer amount must be positive.`);return[{amount:i.toString(),memo:e.methodDetails?.memo,recipient:e.recipient},...n.map(e=>({amount:BigInt(e.amount).toString(),memo:e.memo,recipient:e.recipient}))]}function Ha(e,t,n){t&&(n&&!n.some(e=>Fa(e,t))||e.some(e=>Fa(e,t))||e.push(t))}async function Ua(e,t,n){try{return(await L.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function Wa(e){let t=e.chain?.feeToken;if(t)return ae.toAddress(t);let n=e.chain?.id;return n?Un[n]:void 0}function Ga(e){let t=[];return Ha(t,Hn.pathUsd),Ha(t,Un[e]),t}async function Ka(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])Ha(o,e,n);if(Ha(o,await L.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),Ha(o,Wa(i),n),!a)for(let e of r??[])Ha(o,e,n);for(let e of o)if(await Ua(i,t,e))return e;return o[0]}const qa=d([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]);function Ja(e){if(e!==void 0)return Wn[e]}function Ya(e){let t=Ja(e.chainId);return!!t&&c(e.currency,{strict:!1})&&l(e.currency,t.token)}function Xa(e){let t=Ja(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let i=BigInt(n.amount),a=n.memo;return{calls:[{data:r({abi:ne.tip20,functionName:`approve`,args:[t.swap,i]}),to:t.token},{data:r({abi:qa,functionName:`swapTo`,args:[t.token,i,e.currency,n.recipient,a]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:i,memo:a,recipient:n.recipient}]}}async function Za(e,t){let n=Xa(t);if(n)try{return await h(e,L.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await p(e,{account:t.account,calls:n.calls}),n)}catch{return}}const Qa={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]};function $a(e){return{name:`MPP`,version:`3`,chainId:e}}function eo(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function to(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:$a(n),types:Qa,primaryType:`Proof`,message:eo({account:t,challengeId:r,realm:i})}}function no(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const ro=[`push`,`pull`],io=U.object({amount:W(),memo:U.optional(K()),recipient:U.pipe(U.string(),U.transform(e=>e))}),ao=(1n<<64n)-1n,oo={dev_second:1n,day:86400n,week:604800n},so=U.pipe(G(),U.transform(e=>e.toLowerCase())),co=U.object({accessKeyAddress:so,keyType:U.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:U.optional(U.pipe(U.string().check(U.regex(/^0x[0-9a-fA-F]{120}$/)),U.transform(e=>e)))}),lo=U.object({accessKey:U.optional(co),chainId:U.optional(U.number())}),uo=Ye(`subscriptionExpires must be a valid date`).check(U.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),fo=U.enum([`dev_second`,`day`,`week`]),po=U.pipe(U.union([U.string(),U.bigint(),U.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),U.transform(e=>e.toString())).check(U.regex(/^[1-9]\d*$/,`Invalid periodCount`),U.refine(e=>{try{return BigInt(e)<=ao}catch{return!1}},`periodCount exceeds uint64`));function mo(e){return U.refine(e=>{let{amount:t,decimals:n}=e;return f(t,n)>0n},e)}function ho(e){let{periodCount:t,periodUnit:n}=e;try{let e=oo[n];return e!==void 0&&BigInt(t)*e<=ao}catch{return!1}}const go=Mt({name:`tempo`,intent:`charge`,schema:{credential:{payload:U.discriminatedUnion(`type`,[U.object({hash:K(),type:U.literal(`hash`)}),U.object({signature:q(),type:U.literal(`transaction`)}),U.object({signature:q(),type:U.literal(`proof`)})])},request:U.pipe(U.object({machineTokenEnabled:U.optional(U.boolean()),amount:W(),chainId:U.optional(U.number()),currency:U.string(),decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),feePayer:U.optional(U.pipe(U.union([U.boolean(),U.custom()]),U.transform(e=>typeof e==`object`||e))),memo:U.optional(U.never()),recipient:U.optional(U.string()),splits:U.optional(U.array(io).check(U.minLength(1),U.maxLength(10))),supportedModes:U.optional(U.array(U.enum(ro)).check(U.minLength(1)))}).check(U.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=f(e,t),i=n.reduce((e,n)=>e+f(n.amount,t),0n);return n.every(e=>f(e.amount,t)>0n)&&i<r},`Invalid splits`)),U.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,...c})=>({...c,amount:f(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:f(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s}}}:{}})))}}),_o=Mt({name:`tempo`,intent:`session`,schema:{credential:{payload:U.discriminatedUnion(`action`,[U.object({action:U.literal(`open`),authorizedSigner:U.optional(U.string()),channelId:K(),cumulativeAmount:W(),descriptor:U.optional(U.custom()),signature:q(),transaction:q(),type:U.literal(`transaction`)}),U.object({action:U.literal(`topUp`),additionalDeposit:W(),channelId:K(),descriptor:U.optional(U.custom()),transaction:q(),type:U.literal(`transaction`)}),U.object({action:U.literal(`voucher`),channelId:K(),cumulativeAmount:W(),descriptor:U.optional(U.custom()),signature:q()}),U.object({action:U.literal(`close`),channelId:K(),closeSignature:q(),cumulativeAmount:W(),descriptor:U.optional(U.custom()),signature:q()})])},request:U.pipe(U.object({amount:W(),chainId:U.optional(U.number()),channelId:U.optional(K()),currency:U.string(),decimals:U.number(),escrowContract:U.optional(U.string()),feePayer:U.optional(U.pipe(U.union([U.boolean(),U.custom()]),U.transform(e=>typeof e==`object`||e))),feeToken:U.optional(G()),minVoucherDelta:U.optional(W()),operator:U.optional(G()),recipient:U.optional(U.string()),sessionProtocol:U.optional(U.enum([We.v2,We.v1])),sessionSnapshot:U.optional(U.custom()),suggestedDeposit:U.optional(W()),unitType:U.string()}).check(U.refine(({amount:e,decimals:t})=>f(e,t)>0n,`Session amount must be greater than 0`)),U.transform(({amount:e,chainId:t,channelId:n,decimals:r,escrowContract:i,feePayer:a,feeToken:o,minVoucherDelta:s,operator:c,sessionProtocol:l,sessionSnapshot:u,suggestedDeposit:d,...p})=>({...p,amount:f(e,r).toString(),...d?{suggestedDeposit:f(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:f(s,r).toString()},...t!==void 0&&{chainId:t},...a!==void 0&&{feePayer:a},...o!==void 0&&{feeToken:o},...c!==void 0&&{operator:c},...l!==void 0&&{[Ue.sessionProtocol]:l},...u!==void 0&&{[Ue.sessionSnapshot]:u}}})))}}),vo=Mt({name:`tempo`,intent:`subscription`,schema:{credential:{payload:U.object({signature:q(),type:U.literal(`keyAuthorization`)})},request:U.pipe(U.object({amount:W(),accessKey:U.optional(co),chainId:U.optional(U.number()),currency:so,decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),methodDetails:U.optional(lo),periodCount:po,periodUnit:fo,recipient:so,subscriptionExpires:uo}).check(mo(`Subscription amount must be greater than 0`),U.refine(ho,`Subscription period exceeds uint64`)),U.transform(({accessKey:e,amount:t,chainId:n,decimals:r,methodDetails:i,subscriptionExpires:a,...o})=>{let s={...i,...e!==void 0&&{accessKey:e},...n!==void 0&&{chainId:n}};return{...o,amount:f(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}}),yo=U.object({account:U.optional(U.custom()),autoSwap:U.optional(U.custom()),feeToken:U.optional(U.custom()),mode:U.optional(U.enum(ro))});function bo(e={}){let{clientId:t}=e;if((e.maxAmount!==void 0||e.maxAtomicAmount!==void 0)&&e.currencies===void 0)throw Error(`Tempo charge maxAmount and maxAtomicAmount require currencies.`);let n={maxAmount:So(e.maxAmount,e.decimals),maxAtomicAmount:e.maxAtomicAmount===void 0?void 0:BigInt(e.maxAtomicAmount)},r=Oa({chain:P,getClient:e.getClient,rpcUrl:Gn}),i=wa({account:e.account}),a=Nt(go,{canHandleChallenge({challenge:t}){try{return Co(e,n,t.request),!0}catch{return!1}},context:yo,async createCredential({challenge:a,context:o}){Co(e,n,a.request);let s=a.request.methodDetails?.chainId??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),c=await r({chainId:s});ka(c,s);let l=s??c.chain?.id;if(Aa(e.allowedChainIds,l),l===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");let{request:u}=a,{amount:d,methodDetails:f}=u,p=f?.supportedModes??[`pull`,`push`],h=i(c,o),b=async t=>await e.resolveAccount?.({account:h,chainId:l,operation:t})??h;if(BigInt(d)===0n){let e=await b({kind:`signPaymentProof`});return Tt({challenge:a,payload:{signature:await y(c,{account:e,...to({account:e.address,chainId:l,challengeId:a.id,realm:a.realm})}),type:`proof`},source:no({address:e.address,chainId:l})})}let x=u.currency,S=Ya({chainId:l,currency:x}),C=Na({challengeId:a.id,clientId:t,serverId:a.realm}),w=Va({amount:d,methodDetails:{...f,memo:C},recipient:u.recipient}),T=w.map(e=>L.token.transfer.call(c,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:x})),E=za(o?.autoSwap??e.autoSwap,La),D=f?.machineTokenEnabled===!0?Xa({chainId:l,currency:x,transfers:w}):void 0,O=h,k;if(D){let e=await(async()=>{try{return await b({calls:D.calls,kind:`executeCalls`})}catch{return}})();e&&(k=await Za(c,{account:e.address,chainId:l,currency:x,transfers:w}),k&&(O=e))}let A;k||(O=await b({kind:`executeCalls`,...E?{}:{calls:T}}),A=E?await Ra(c,{account:O.address,amountOut:BigInt(d),tokenOut:x,tokenIn:E.tokenIn,slippage:E.slippage,maxAmountIn:E.maxAmountIn}):void 0);let j=k?.calls??[...A??[],...T],M=Ga(l),N=(o?.feeToken??e.feeToken)||(k||S?await Ka({account:O.address,allowedTokens:M,candidateTokens:M,client:c,prioritizeCandidates:!0}):void 0),P=(()=>{let t=o?.mode??e.mode;if(t){if(!p.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=O.type===`json-rpc`?`push`:`pull`;return p.includes(n)?n:p[0]})(),F=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!a.expires)return e;let t=Math.floor(new Date(a.expires).getTime()/1e3)+1;return Math.min(e,t)})();if(P===`push`){let{receipts:e}=O.type===`local`?{receipts:[await _(c,{account:O,calls:j,...N?{feeToken:N}:{},nonceKey:`expiring`,validBefore:F})]}:await g(c,{account:O,...N?{capabilities:{feeToken:N}}:{},calls:j,experimental_fallback:j.length===1,forceAtomic:j.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return Tt({challenge:a,payload:{hash:t,type:`hash`},source:no({address:O.address,chainId:l})})}let ee=()=>{if(f?.feePayer!==!0)return;let e=15e3,t=a.expires?new Date(a.expires).getTime():1/0,n=Date.now();if(!(t-n>=e))throw Error(`Sponsored challenge expires in less than 15 seconds; the fee payer would reject the transaction. Request a new challenge.`);if(!(F*1e3-n>=e))throw Error(`Sponsored transaction preparation took too long: less than 15 seconds of its validity window remain, so the fee payer would reject it.`)};ee();let I=await m(c,{account:O,calls:j,...N?{feeToken:N}:{},nonceKey:`expiring`,validBefore:F});if(I.gas=(I.gas??0n)+5000n,f?.feePayer){let e=I;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return ee(),Tt({challenge:a,payload:{signature:await v(c,I),type:`transaction`},source:no({address:O.address,chainId:l})})}}),o=new Map,s=async t=>{Co(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,s=o.get(i);return s||(s=a.createCredential(t).finally(()=>o.delete(i)),o.set(i,s)),s};return Di({...a,createCredential:s},xo)}function xo(e){let t=go.schema.credential.payload.safeParse(xt(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(fe.serializedType))return;let i=fe.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&fe.serialize(i)===r)return u(r)}function So(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo charge maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo charge maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return f(e,t)}}function Co(e,t,n){let{amount:r,methodDetails:i,recipient:a}=n,o=i?.chainId;if(e.expectedChainId!==void 0&&o!==void 0&&o!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${o}.`);if((o!==void 0||e.allowedChainIds?.length===0)&&Aa(e.allowedChainIds,o),e.currencies&&!e.currencies.some(e=>e.toLowerCase()===n.currency.toLowerCase()))throw Error(`Tempo charge currency is not allowed: ${n.currency}.`);if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!a||!t.has(a.toLowerCase()))throw Error(`Unexpected primary recipient: ${a}`);let n=i?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}if(t.maxAtomicAmount!==void 0&&BigInt(r)>t.maxAtomicAmount)throw Error(`Tempo charge amount exceeds maxAtomicAmount.`);if(t.maxAmount!==void 0&&BigInt(r)>t.maxAmount)throw Error(`Tempo charge amount exceeds maxAmount.`)}const wo=(1n<<96n)-1n;function To(e){return e>=0n&&e<=wo}function Eo(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return To(t)?t:void 0}function Do(e){return Oo(e),e}function Oo(e){if(!To(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const ko=new Set([`open`,`topUp`,`voucher`,`close`]);function Ao(e){return typeof e==`object`&&!!e}function jo(e){return typeof e==`string`&&ko.has(e)}function Mo(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!jo(t.action))}function No(e,t=`No session credential context available.`){if(!Mo(e))throw Error(t);return e}function Po(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function Fo(e){return Ao(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function Io(e){return Ao(e)?e.method===`tempo`&&e.intent===`session`&&e.status===`success`&&typeof e.timestamp==`string`&&typeof e.reference==`string`&&typeof e.challengeId==`string`&&typeof e.channelId==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.spent==`string`&&(e.units===void 0||typeof e.units==`number`)&&(e.txHash===void 0||typeof e.txHash==`string`):!1}function Lo(e){let t=C.toString(e),n=JSON.parse(t);if(!Io(n))throw Error(`Invalid session receipt.`);return n}function Ro(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function zo(e){let t=`message`,n=[];for(let r of e.split(`
1
+ import{createClient as e,createTransport as t,custom as n,encodeFunctionData as r,erc20Abi as i,getAbiItem as a,getAddress as o,hashTypedData as s,http as c,isAddress as l,isAddressEqual as u,keccak256 as d,parseAbi as f,parseEventLogs as p,parseUnits as m}from"viem";import{call as h,getBlockNumber as g,getLogs as _,prepareTransactionRequest as v,readContract as y,sendCallsSync as b,sendRawTransactionSync as x,sendTransactionSync as S,signTransaction as C,signTypedData as w,waitForTransactionReceipt as ee}from"viem/actions";import*as T from"viem/chains";import{tempo as te}from"viem/chains";import{AbiParameters as E,Base64 as D,Bytes as O,Hash as k,Hex as A,Json as j}from"ox";import*as M from"zod/mini";import*as N from"node:child_process";import*as P from"node:fs";import*as F from"node:os";import*as I from"node:path";import{z as L}from"zod";import"node:readline";import{tempo as R,tempoModerato as ne}from"viem/tempo/chains";import{ousd as re,pathusd as ie,usdce as ae}from"viem/tokens";import{Abis as oe,Account as se,Actions as z,Addresses as ce,TokenId as le,Transaction as ue,withFeePayer as de}from"viem/tempo";import{parseAccount as fe,privateKeyToAccount as pe}from"viem/accounts";import{Channel as me,KeyAuthorization as he,SignatureEnvelope as B,TempoAddress as ge,TxEnvelopeTempo as _e}from"ox/tempo";var ve=Object.defineProperty,ye=Object.getOwnPropertyDescriptor,be=Object.getOwnPropertyNames,xe=Object.prototype.hasOwnProperty,Se=(e,t)=>{let n={};for(var r in e)ve(n,r,{get:e[r],enumerable:!0});return t||ve(n,Symbol.toStringTag,{value:`Module`}),n},Ce=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=be(t),a=0,o=i.length,s;a<o;a++)s=i[a],!xe.call(e,s)&&s!==n&&ve(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=ye(t,s))||r.enumerable});return e},we=(e,t,n)=>(Ce(e,t,`default`),n&&Ce(n,t,`default`));const Te=Symbol(`mppx.x402.asset`);function Ee(e){return{[Te]:!0,address:e.address,decimals:e.decimals,network:e.network,transfer:e.transfer}}function De(e,t){let n=e(t.chainId);return Ee({address:n.address,decimals:n.decimals,network:Le(t.chainId),transfer:ze(t.transfer,n)})}const Oe={USDC:Ee({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},ke={USDC:Ee({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},Ae={USDC:Ee({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:Ee({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},je={USDC:Ee({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})};function Me(e){return typeof e!=`object`||!e?!1:e[Te]===!0}function Ne(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function Pe(e){return typeof e==`string`}function Fe(e,t){if(Me(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(Ne(e)){let n=e.addresses[Re(t)];return n?{address:n,decimals:e.decimals,name:e.name}:void 0}return{address:e}}function Ie(e,t,n){let r=Fe(e,n);return r?o(r.address)===o(t):!1}function Le(e){return`eip155:${e}`}function Re(e){return Number(e.slice(7))}function ze(e,t){if(e.type!==`eip3009`)return e;if(e.name)return{...e,name:e.name};if(!t.name)throw Error(`EIP-3009 token assets require a token name.`);return{...e,name:t.name}}var Be=Se({base:()=>Oe,baseSepolia:()=>ke,celo:()=>Ae,celoSepolia:()=>je,define:()=>Ee,fromToken:()=>De,isAsset:()=>Me,isRawAddress:()=>Pe,isToken:()=>Ne,matches:()=>Ie,resolve:()=>Fe,toChainId:()=>Re,toNetwork:()=>Le}),Ve=Se({base:()=>He,baseSepolia:()=>Ue,celo:()=>We,celoSepolia:()=>Ge});const He=8453,Ue=84532,We=42220,Ge=11142220,V={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},Ke={payment:`Payment`},qe={evm:`evm`,stripe:`stripe`,tempo:`tempo`},Je={charge:`charge`,session:`session`,subscription:`subscription`},Ye={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},Xe={v1:`v1`,v2:`v2`};function Ze(e,t){if(!(!e||typeof e!=`object`))return e[t]}function Qe(e){let t=D.toString(e);return JSON.parse(t)}function H(e){let t=j.canonicalize(e);return D.fromString(t,{pad:!1,url:!0})}var U=Se({address:()=>G,amount:()=>W,datetime:()=>et,datetimeInput:()=>tt,hash:()=>K,period:()=>it,signature:()=>q,toDate:()=>nt,toDatetimeString:()=>rt,unwrapOptional:()=>at});import*as $e from"zod/mini";we(U,$e);function W(){return M.string().check(M.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function et(){return M.string().check(M.regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,`Invalid ISO 8601 datetime`))}function tt(e=`Invalid ISO 8601 datetime`){return M.pipe(M.union([et(),M.custom(e=>e instanceof Date)]),M.transform(nt)).check(M.refine(e=>Number.isFinite(e.getTime()),e))}function nt(e){return e instanceof Date?e:new Date(e)}function rt(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function G(){return M.string().check(M.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function K(){return M.string().check(M.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function it(){return M.string().check(M.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function q(){return M.string().check(M.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function at(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}const ot=U.object({description:U.optional(U.string()),digest:U.optional(U.string().check(U.regex(/^sha-256=/,`Invalid digest format`))),expires:U.optional(et()),header:U.optional(U.string().check(U.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,`Invalid HTTP header name`))),id:U.string().check(U.minLength(1)),intent:U.string(),method:U.string(),meta:U.optional(U.record(U.string(),U.string())),opaque:U.optional(U.string()),realm:U.string(),request:U.record(U.string(),U.unknown())});function st(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=St(o)?void 0:o,f=e.expires?rt(e.expires):void 0,p=e.opaque??(i===void 0?void 0:H(i)),m=u?Ct({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return ot.parse({id:m,realm:c,method:a,intent:s,request:l,...n&&{description:n},...r&&{digest:r},...f&&{expires:f},...d!==void 0&&{header:d},...i!==void 0&&{meta:i},...p!==void 0&&{opaque:p}})}function ct(e){let t=[J(`id`,e.id),J(`realm`,e.realm),J(`method`,e.method),J(`intent`,e.intent),J(`request`,H(e.request))];e.description!==void 0&&t.push(J(`description`,e.description)),e.digest!==void 0&&t.push(J(`digest`,e.digest)),e.expires!==void 0&&t.push(J(`expires`,e.expires));let n=e.header;return n!==void 0&&!St(n)&&t.push(J(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(J(`opaque`,H(e.meta))):t.push(J(`opaque`,e.opaque)),`${Ke.payment} ${t.join(`, `)}`}function J(e,t){if(/[\r\n]/.test(t))throw Error(`Invalid quoted-string value.`);return`${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`}function lt(e,t){let n=ut(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=dt(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>16384)throw Error(`Request parameter too large.`);if(a.method&&!/^[a-z][a-z0-9:_-]*$/.test(a.method))throw Error(`Invalid method: "${a.method}". Must be lowercase per spec.`);return st({...a,request:Qe(r),...i&&{opaque:i}},t)}function ut(e){let t=Ke.payment,[n]=gt(e,t);if(n===void 0)return null;let r=n+t.length;for(;r<e.length&&/\s/.test(e[r]??``);)r++;return e.slice(r)}function dt(e){let t=Object.create(null),n=0;for(;n<e.length;){for(;n<e.length&&/[\s,]/.test(e[n]??``);)n++;if(n>=e.length)break;let r=n;for(;n<e.length&&/[A-Za-z0-9_-]/.test(e[n]??``);)n++;let i=e.slice(r,n).toLowerCase();if(!i)throw Error(`Malformed auth-param.`);for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]!==`=`)break;for(n++;n<e.length&&/\s/.test(e[n]??``);)n++;let[a,o]=ft(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function ft(e,t){if(e[t]===`"`)return pt(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function pt(e,t){let n=t,r=!1,i=t,a;for(;n<e.length;){let o=e[n];if(n++,r){a??=[];let t=o===`u`?e.slice(n,n+4):void 0;t&&/^[0-9A-Fa-f]{4}$/.test(t)?(a.push(String.fromCharCode(Number.parseInt(t,16))),n+=4):a.push(o),i=n,r=!1;continue}if(o===`\\`){a??=[],a.push(e.slice(i,n-1)),i=n,r=!0;continue}if(o===`"`)return[a?[...a,e.slice(i,n-1)].join(``):e.slice(t,n-1),n]}throw Error(`Unterminated quoted-string.`)}function mt(e,t,n){if(e.slice(t,t+n.length).toLowerCase()!==n.toLowerCase())return!1;let r=e[t+n.length];return!!(r&&/\s/.test(r))}function ht(e){return gt(e,Ke.payment).length>0||e.split(`,`).some(e=>e.trim().toLowerCase()===Ke.payment.toLowerCase())}function gt(e,t){let n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(r){i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}if(!mt(e,a,t))continue;let s=a-1;for(;s>=0&&/\s/.test(e[s]??``);)s--;s>=0&&e[s]!==`,`||n.push(a)}return n}function _t(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return vt(e.headers,t)}function vt(e,t){let n=e.get(V.wwwAuthenticate);if(!n)throw Error(`Missing ${V.wwwAuthenticate} header.`);return yt(n,t)}function yt(e,t){let n=gt(e,Ke.payment);if(n.length===0)throw Error(`No Payment schemes found.`);return n.map((r,i)=>{let a=i+1<n.length?n[i+1]:e.length;return lt(e.slice(r,a).replace(/,\s*$/,``),t)})}function bt(e){let t=[e.realm,e.method,e.intent,H(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!St(n)&&t.push(n),t.push(e.opaque??(e.meta?H(e.meta):``)),t.join(`|`)}function xt(e){return e.header??V.authorization}function St(e){return e?.toLowerCase()===V.authorization.toLowerCase()}function Ct(e,t){let n=bt(e),r=O.fromString(t.secretKey),i=O.fromString(n),a=k.hmac256(r,i,{as:`Bytes`});return D.fromBytes(a,{url:!0,pad:!1})}const wt=65536;var Tt=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},Et=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function Dt(e){if(e.length>wt)throw new Et;let t=e.match(RegExp(`^${Ke.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new Tt;try{let e=D.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=Ot(r);return{challenge:ot.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:Qe(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new Et}}function Ot(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!kt(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:H(e)}}function kt(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function At(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function jt(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:H(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:H(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=D.fromString(s,{pad:!1,url:!0});return`${Ke.payment} ${c}`}function Mt(e){return e.length>wt?null:e.split(`,`).map(e=>e.trim()).find(e=>RegExp(`^${Ke.payment}\\s+`,`i`).test(e))??null}var Nt=class extends Error{details;status=402;hint;constructor(e,t={}){super(e),this.details=t.details,t.cause!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t.cause,writable:!0})}toProblemDetails(e){return{type:this.type,title:this.title,status:this.status,detail:this.message,...this.details&&Object.keys(this.details).length>0&&{details:this.details},...this.hint&&{hint:this.hint},...e&&{challengeId:e}}}},Pt=class extends Nt{name=`InvalidChallengeError`;title=`Invalid Challenge`;status=402;type=`https://paymentauth.org/problems/invalid-challenge`;constructor(e={}){let{id:t,reason:n}=e,r=t?` "${t}"`:``,i=n?`: ${n}`:``;super(`Challenge${r} is invalid${i}.`)}},Y=class extends Nt{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,reason:n}=e;super(n?`Payment verification failed: ${n}.`:`Payment verification failed.`,{details:t})}},Ft=class extends Nt{name=`PaymentExpiredError`;title=`Payment Expired`;type=`https://paymentauth.org/problems/payment-expired`;constructor(e={}){let{expires:t}=e;super(t?`Payment expired at ${t}.`:`Payment has expired.`)}},It=class extends Nt{name=`PaymentOutcomeUnknownError`;title=`Payment Outcome Unknown`;type=`https://paymentauth.org/problems/payment-outcome-unknown`;challenge;credential;transactionHash;constructor(e){let{cause:t,challenge:n,credential:r,transactionHash:i}=e;super(`Payment outcome is unknown after sending a credential for challenge "${n.id}". Do not blindly retry.`,{cause:t}),this.challenge=n,this.credential=r,this.transactionHash=i}},Lt=class extends Error{name=`ZoneSettlementPendingError`;challengeId;senderTag;zoneId;constructor(e){let{cause:t,challengeId:n,senderTag:r,zoneId:i}=e;super(`Zone ${i} withdrawal ${r} for challenge "${n}" has not settled on Tempo yet. Retry the challenge to resume waiting instead of paying again.`),this.challengeId=n,this.senderTag=r,this.zoneId=i,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}};function Rt(e,t){if(!e)throw new Pt({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new Pt({...t&&{id:t},reason:`malformed expires timestamp`});if(Date.parse(e)<=Date.now())throw new Ft({expires:e})}function zt(e){return e}function Bt(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}function Vt(e){return{encode(t){return D.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(D.toString(t)))}catch{throw new Ht}}}}var Ht=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const Ut=[`exact`],Wt=`PAYMENT-REQUIRED`,Gt=`PAYMENT-SIGNATURE`,Kt=U.string().check(U.minLength(1)),qt=U.number().check(U.refine(e=>e>0,`Must be positive`)),Jt=U.string().check(U.regex(/^\d+$/,`Invalid atomic amount`)),Yt=G(),Xt=U.string().check(U.regex(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),Zt=U.object({description:U.optional(U.string()),iconUrl:U.optional(U.string()),mimeType:U.optional(U.string()),serviceName:U.optional(U.string()),tags:U.optional(U.array(U.string())),url:Kt});U.discriminatedUnion(`type`,[U.object({name:Kt,type:U.literal(`eip3009`),version:Kt}),U.object({name:U.optional(U.string()),type:U.literal(`permit2`),version:U.optional(U.string())})]);const Qt=U.object({amount:Jt,asset:Kt,extra:U.optional(U.record(U.string(),U.unknown())),maxTimeoutSeconds:qt,network:Xt,payTo:Kt,scheme:U.enum(Ut)}),$t=U.object({info:U.record(U.string(),U.unknown()),schema:U.record(U.string(),U.unknown())}),en=U.record(U.string(),$t),tn=U.object({accepts:U.array(Qt).check(U.minLength(1)),error:U.optional(U.string()),extensions:U.optional(en),resource:Zt,x402Version:U.literal(2)}),nn=U.object({authorization:U.object({from:Yt,nonce:K(),to:Yt,validAfter:Jt,validBefore:Jt,value:Jt}),signature:q()}),rn=U.object({permit2Authorization:U.object({deadline:Jt,from:Yt,nonce:Jt,permitted:U.object({amount:Jt,token:Yt}),spender:Yt,witness:U.object({to:Yt,validAfter:Jt})}),signature:q()}),an=U.union([nn,rn]),on=U.object({accepted:Qt,extensions:U.optional(en),payload:an,resource:U.optional(Zt),x402Version:U.literal(2)});U.object({extensions:U.optional(en),extra:U.optional(U.record(U.string(),U.unknown())),invalidMessage:U.optional(U.string()),invalidReason:U.optional(U.string()),isValid:U.boolean(),payer:U.optional(U.string())});const sn=U.object({amount:U.optional(Jt),errorMessage:U.optional(U.string()),errorReason:U.optional(U.string()),extensions:U.optional(en),extra:U.optional(U.record(U.string(),U.unknown())),network:Kt,payer:U.optional(U.string()),success:U.boolean(),transaction:U.string()});function cn(e){let{extensions:t,resource:n,...r}=e;return Qt.parse(r)}const ln=Vt(tn),un=Vt(on),dn=Vt(sn);ln.encode,ln.decode;function fn(e){try{let t=JSON.parse(D.toString(e));return mn(t)}catch{throw new Ht}}const pn=un.encode;un.decode,dn.encode,dn.decode;const mn=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new Ht;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new Ht;let n=Zt.parse(t.resource),r=t.extensions===void 0?void 0:en.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}};function hn(e){let t=[H(e.accepted),H(e.resource),H(e.extensions)].join(`|`);return k.sha256(O.fromString(t),{as:`Hex`})}async function gn(e){let t=e.context?.account??e.config.account;if(!t?.signTypedData)throw Error(`x402 exact requires a typed-data signer.`);let n=e.challenge.request,r=cn(n);if(bn(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?Sn(n.extensions):n.extensions,a=r.extra?.assetTransferMethod??`eip3009`;if(a!==`eip3009`)throw Error(`x402 exact ${String(a)} signing is not implemented yet.`);let s=r.extra?.name,c=r.extra?.version;if(typeof s!=`string`||typeof c!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let l=Math.floor(Date.now()/1e3),u={from:o(t.address),nonce:i?.mppx?hn({accepted:r,extensions:i,resource:n.resource}):wn(),to:o(r.payTo),validAfter:(l-600).toString(),validBefore:(l+r.maxTimeoutSeconds).toString(),value:r.amount},d=await t.signTypedData({domain:{chainId:yn(r.network),name:s,verifyingContract:o(r.asset),version:c},message:{...u,value:BigInt(u.value),validAfter:BigInt(u.validAfter),validBefore:BigInt(u.validBefore)},primaryType:`TransferWithAuthorization`,types:vn});return pn({accepted:r,...i?{extensions:i}:{},payload:{authorization:u,signature:d},...n.resource?{resource:n.resource}:{},x402Version:2})}function _n(e){let t=e.challenge.request,n;try{n=cn(t),bn(e.config,n)}catch{return!1}if(!t.resource||(n.extra?.assetTransferMethod??`eip3009`)!==`eip3009`)return!1;let r=n.extra?.name,i=n.extra?.version;return typeof r==`string`&&typeof i==`string`}const vn={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function yn(e){return Number(e.slice(7))}function bn(e,t){let n=yn(t.network);if(e.networks&&!e.networks.includes(n))throw Error(`x402 exact chain ID is not allowed: ${n}.`);let r=e.currencies??e.assets;if(r?.some(e=>Pe(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=o(t.asset);if(!r.some(n=>Ie(n,e,t.network)))throw Error(`x402 exact currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`x402 exact amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=xn(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>m(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function xn(e,t){let n=e.currencies??e.assets,r=o(t.asset),i=n?.find(e=>Ie(e,r,t.network)),a=i?Fe(i,t.network):void 0;return a?.decimals===void 0?e.decimals:a.decimals}function Sn(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:Cn()}}}:e}function Cn(){return Tn().slice(2)}function wn(){return Tn()}function Tn(){let e=globalThis.crypto;if(!e?.getRandomValues)throw Error(`x402 exact requires crypto randomness.`);let t=e.getRandomValues(new Uint8Array(32));return`0x${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}const En=Symbol.for(`mppx.x402.challenge`);function Dn(e){return Object.defineProperty(e,En,{value:!0}),e}function On(e){return!!e?.[En]}const kn=[`authorization`],An=U.string().check(U.regex(/^\d+$/,`Invalid atomic amount`));U.object({name:U.string().check(U.minLength(1)),version:U.string().check(U.minLength(1))});const jn=U.object({chainId:U.number(),credentialTypes:U.optional(U.array(U.enum(kn)).check(U.minLength(1))),decimals:U.optional(U.number()),permit2Address:U.optional(G()),splits:U.optional(U.array(U.object({amount:An,recipient:G()})))});U.object({amount:An,currency:G(),description:U.optional(U.string()),externalId:U.optional(U.string()),methodDetails:jn,recipient:G()});const Mn=U.object({amount:W(),chainId:U.number(),currency:G(),credentialTypes:U.optional(U.array(U.enum(kn)).check(U.minLength(1))),decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),permit2Address:U.optional(G()),recipient:G(),splits:U.optional(U.array(U.object({amount:An,recipient:G()})))}),Nn=U.object({from:G(),nonce:K(),signature:q(),to:G(),type:U.literal(`authorization`),validAfter:An,validBefore:An,value:An}),Pn={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function Fn(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function In(e){return k.keccak256(O.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function Ln(e){return`eip155:${e}`}function Rn(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const zn=zt({name:`evm`,intent:`charge`,schema:{credential:{payload:Nn},request:U.pipe(Mn,U.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:s,splits:c,...l})=>({...l,amount:m(e,i).toString(),currency:o(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:o(a)}:{},...c?{splits:c}:{}},recipient:o(s)})))}});function Bn(e){return Bt(zn,{canHandleChallenge({challenge:t}){return!Vn(t)||_n({challenge:t,config:e})},context:U.object({account:U.optional(U.custom())}),async createCredential({challenge:t,context:n}){if(Vn(t))return gn({challenge:t,config:e,context:n});let r=n?.account??e.account;if(!r?.signTypedData)throw Error(`EVM authorization requires a typed-data signer.`);let i=t.request;if(Hn(e,i),!i.methodDetails.credentialTypes?.includes(`authorization`))throw Error(`EVM authorization is not accepted by this challenge.`);if(i.methodDetails.splits?.length)throw Error(`EVM authorization does not support payment splits.`);let a=Un(e,i),s=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return jt(At({challenge:t,payload:{from:o(r.address),nonce:In(t),signature:await r.signTypedData({domain:Fn({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:o(r.address),nonce:In(t),to:o(i.recipient),validAfter:0n,validBefore:BigInt(s),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:Pn}),to:o(i.recipient),type:`authorization`,validAfter:`0`,validBefore:s,value:i.amount},source:Rn({address:o(r.address),chainId:i.methodDetails.chainId})}))}})}function Vn(e){return On(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function Hn(e,t){let n=t.methodDetails.chainId,r=Ln(n);if(e.networks&&!e.networks.includes(n))throw Error(`EVM chain ID is not allowed: ${n}.`);let i=e.currencies??e.assets;if(i?.some(e=>Pe(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=o(t.currency);if(!i.some(t=>Ie(t,e,r)))throw Error(`EVM currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`EVM charge amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=Wn(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>m(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function Un(e,t){let n=e.currencies??e.assets,r=o(t.currency),i=Ln(t.methodDetails.chainId),a=n?.find(e=>Ie(e,r,i)),s=a?Fe(a,i):void 0;if(s?.transfer?.type===`eip3009`)return{name:s.transfer.name,version:s.transfer.version};if(e.authorization)return e.authorization;throw Error(`EVM authorization requires token name and version.`)}function Wn(e,t){let n=e.currencies??e.assets,r=o(t.currency),i=Ln(t.methodDetails.chainId),a=n?.find(e=>Ie(e,r,i)),s=a?Fe(a,i):void 0;return s?.decimals===void 0?e.decimals:s.decimals}function Gn(e){return[Gn.charge(e)]}(function(e){e.charge=Bn,e.assets=Be,e.chains=Ve})(Gn||={});var Kn=class extends Error{name=`Incur.BaseError`;shortMessage;details;constructor(e,t={}){let n=t.cause instanceof Error?t.cause.message:void 0,r=n?`${e}\n\nDetails: ${n}`:e;super(r,t.cause?{cause:t.cause}:void 0),this.shortMessage=e,this.details=n}walk(e){return Jn(this,e)}},qn=class extends Kn{name=`Incur.IncurError`;code;hint;retryable;exitCode;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.code=e.code,this.hint=e.hint,this.retryable=e.retryable??!1,this.exitCode=e.exitCode}};function Jn(e,t){if(t){let n=e?.cause;for(;n;){if(t(n))return n;n=n?.cause}return}let n=e;for(;n?.cause;)n=n.cause;return n}const X={mainnet:4217,testnet:42431},Yn={ousd:re(X.mainnet).address,usdc:o(ae(X.mainnet).address),pathUsd:ie(X.mainnet).address},Xn={[X.mainnet]:Yn.usdc,[X.testnet]:Yn.pathUsd},Zn=Object.freeze({[X.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[X.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})});X.mainnet,X.testnet;const Qn={[X.mainnet]:`https://rpc.tempo.xyz`,[X.testnet]:`https://rpc.moderato.tempo.xyz`},Z=(()=>{let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes(`--no-color`))&&(!!n.FORCE_COLOR||t.includes(`--color`)||(e.stdout||{}).isTTY&&n.TERM!==`dumb`||!!n.CI),i=(e,t,n,r)=>{let i=``,a=0,o=r;do i+=e.substring(a,o)+n,a=o+t.length,o=e.indexOf(t,a);while(~o);return i+e.substring(a)},a=r?(e,t,n=e)=>r=>{let a=`${r}`,o=a.indexOf(t,e.length);return~o?e+i(a,t,n,o)+t:e+a+t}:()=>String;return{isColorSupported:r,reset:a(`\x1B[0m`,`\x1B[0m`),bold:a(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:a(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:a(`\x1B[3m`,`\x1B[23m`),underline:a(`\x1B[4m`,`\x1B[24m`),inverse:a(`\x1B[7m`,`\x1B[27m`),hidden:a(`\x1B[8m`,`\x1B[28m`),strikethrough:a(`\x1B[9m`,`\x1B[29m`),black:a(`\x1B[30m`,`\x1B[39m`),red:a(`\x1B[31m`,`\x1B[39m`),green:a(`\x1B[32m`,`\x1B[39m`),yellow:a(`\x1B[33m`,`\x1B[39m`),blue:a(`\x1B[34m`,`\x1B[39m`),magenta:a(`\x1B[35m`,`\x1B[39m`),cyan:a(`\x1B[36m`,`\x1B[39m`),white:a(`\x1B[37m`,`\x1B[39m`),gray:a(`\x1B[90m`,`\x1B[39m`),bgBlack:a(`\x1B[40m`,`\x1B[49m`),bgRed:a(`\x1B[41m`,`\x1B[49m`),bgGreen:a(`\x1B[42m`,`\x1B[49m`),bgYellow:a(`\x1B[43m`,`\x1B[49m`),bgBlue:a(`\x1B[44m`,`\x1B[49m`),bgMagenta:a(`\x1B[45m`,`\x1B[49m`),bgCyan:a(`\x1B[46m`,`\x1B[49m`),bgWhite:a(`\x1B[47m`,`\x1B[49m`),blackBright:a(`\x1B[90m`,`\x1B[39m`),redBright:a(`\x1B[91m`,`\x1B[39m`),greenBright:a(`\x1B[92m`,`\x1B[39m`),yellowBright:a(`\x1B[93m`,`\x1B[39m`),blueBright:a(`\x1B[94m`,`\x1B[39m`),magentaBright:a(`\x1B[95m`,`\x1B[39m`),cyanBright:a(`\x1B[96m`,`\x1B[39m`),whiteBright:a(`\x1B[97m`,`\x1B[39m`),bgBlackBright:a(`\x1B[100m`,`\x1B[49m`),bgRedBright:a(`\x1B[101m`,`\x1B[49m`),bgGreenBright:a(`\x1B[102m`,`\x1B[49m`),bgYellowBright:a(`\x1B[103m`,`\x1B[49m`),bgBlueBright:a(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:a(`\x1B[105m`,`\x1B[49m`),bgCyanBright:a(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:a(`\x1B[107m`,`\x1B[49m`),link(e,t,n){return r?`\x1b]8;;${e}\x07${n?t:Z.underline(t)}\x1b]8;;\x07`:t}}})();function $n(e,t){return Z.link(e,t)}function er(e){return e.startsWith(`tempo:`)}function tr(e,t,n=6,r){let[i,a]=(Number(e)/10**n).toString().split(`.`),o=i.replace(/\B(?=(\d{3})+(?!\d))/g,`_`),s=r?.explorerUrl&&r.token?Z.dim(Z.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):Z.dim(t);return`${a?`${o}.${a}`:o} ${s}`}const nr={mainnet:Qn[X.mainnet],testnet:Qn[X.testnet]};function rr(e,t={}){return e??(t.network?nr[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}async function ir(t={}){let n=rr(t.rpcUrl,{network:t.network});if(!n)return R;let{getChainId:r}=await import(`viem/actions`),i=await r(e({transport:c(n)})),a=Object.values(await import(`viem/tempo/chains`)).filter(e=>typeof e==`object`&&!!e&&`id`in e&&e.id===i),o=a.find(e=>`serializers`in e&&e.serializers)??a[0];if(!o)throw Error(`Unknown chain ID ${i} from RPC ${n}`);return o}function ar(e){return typeof e==`bigint`?e:e.amount}function or(e){return e.id!==R.id}async function sr(e,t,n,r={}){let{Actions:i}=await import(`viem/tempo`),[a,o]=await Promise.all([i.token.getBalance(e,{account:n,token:t}).then(ar).catch(()=>0n),i.token.getMetadata(e,{token:t}).catch(e=>{if(r.requireDecimals)throw e;return{symbol:t}})]),s={"0x20c0000000000000000000000000000000000000":`PathUSD`,"0x20C000000000000000000000b9537d11c60E8b50":`USDC`}[t]??o.symbol,c=`decimals`in o&&typeof o.decimals==`number`?o.decimals:6;if(r.requireDecimals&&!(`decimals`in o&&typeof o.decimals==`number`))throw Error(`Token decimals are unavailable.`);return{balance:a,symbol:s,decimals:c,token:t}}function cr(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:1e4}function lr(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function ur(e){return new qn({code:`KEYCHAIN_UNAVAILABLE`,message:`Linux keyring requires secret-tool. Install libsecret-tools.`,hint:`On Debian/Ubuntu, run: sudo apt install libsecret-tools gnome-keyring dbus-x11`,exitCode:69,cause:e})}function dr(e){if(e&&lr(e,`secret-tool`))throw ur(e)}function fr(e,t){return new Promise(n=>{N.execFile(e,t,{timeout:cr()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function pr(){let e=I.join(process.env.XDG_CONFIG_HOME||I.join(F.homedir(),`.config`),`mppx`,`default`);return{get(){try{return P.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(t){P.mkdirSync(I.dirname(e),{recursive:!0}),P.writeFileSync(e,t,`utf-8`)},clear(){try{P.unlinkSync(e)}catch{}}}}function mr(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:pr().get())}function hr(e=`main`){let t=`mppx`;return{async list(){let e=F.platform();if(e===`darwin`){let{stdout:e,error:n}=await fr(`security`,[`dump-keychain`]);if(n)return[];let r=[],i=e.split(`keychain:`);for(let e of i){let n=e.match(/"svce"<blob>="([^"]*)"/),i=e.match(/"acct"<blob>="([^"]*)"/);n?.[1]===t&&i?.[1]&&r.push(i[1])}return r}if(e===`linux`){let{stdout:e,stderr:n,error:r}=await fr(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(dr(r),r)return[];let i=`${e}\n${n}`,a=[],o=i.matchAll(/\baccount = (.+)/g);for(let e of o)e[1]&&a.push(e[1]);return a}throw Error(`Unsupported platform: ${e}`)},async get(){let n=F.platform();if(n===`darwin`){let{stdout:n,error:r}=await fr(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await fr(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return dr(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=F.platform();if(r===`darwin`){await fr(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await fr(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=N.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),cr());return r.stdin?.write(n),r.stdin?.end(),new Promise((e,t)=>{r.on(`close`,n=>{clearTimeout(i),n===0?e():t(Error(`secret-tool exited with code ${n}`))}),r.on(`error`,e=>{clearTimeout(i),t(lr(e,`secret-tool`)?ur(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=F.platform();if(n===`darwin`){await fr(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await fr(`secret-tool`,[`clear`,`service`,t,`account`,e]);dr(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function gr(e){let{privateKeyToAccount:t}=await import(`viem/accounts`),n=process.env.MPPX_PRIVATE_KEY?.trim();if(n)return{account:t(n),source:`environment`};let r=mr(e),i=await hr(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function _r(e){return(await gr(e)).account}function vr(e){return e}function yr(){return vr({method:`evm`,supports:e=>e.method===`evm`&&!On(e),async setup({challenge:t,options:n}){let r=t.request,a=r.methodDetails,o=a?.chainId,s=o?br(o):void 0,l=r.currency,u=await _r(n.account),d=[...Object.values(Oe),...Object.values(ke),...Object.values(Ae),...Object.values(je)],f=l??``;if(s&&l)try{let t=e({chain:s,transport:c()}),n=await y(t,{address:l,abi:i,functionName:`symbol`});n&&(f=n)}catch{}return{tokenSymbol:f,tokenDecimals:a?.decimals??6,explorerUrl:s?.blockExplorers?.default?.url,methods:[...Gn({account:u,currencies:d})]}}})}function br(e){return Object.values(T).find(t=>t.id===e)}function xr(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`Decimals must be a non-negative integer.`);if(!/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))throw TypeError(`Value \`${e}\` is not a valid decimal number.`);let n=e.startsWith(`-`),[r=`0`,i=``]=(n?e.slice(1):e).split(`.`),a=i.slice(0,t).padEnd(t,`0`),o=BigInt(`${r||`0`}${a}`);return i.length>t&&i[t]>=`5`&&(o+=1n),n?-o:o}const Sr=U.object({customer:U.optional(U.string().check(U.minLength(1))),hooks:U.optional(U.object({inputs:U.object({tax:U.object({calculation:U.string().check(U.minLength(1))})})})),metadata:U.optional(U.record(U.string(),U.string())),receipt_email:U.optional(U.string().check(U.minLength(1)))}),Cr=U.custom(e=>typeof e==`function`),wr=U.union([Sr,Cr]),Tr=zt({name:`stripe`,intent:`charge`,schema:{credential:{payload:U.object({externalId:U.optional(U.string()),spt:U.string()})},request:U.pipe(U.object({amount:W(),currency:U.string(),decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),metadata:U.optional(U.record(U.string(),U.string())),networkId:U.string(),paymentIntentOptions:U.optional(wr),paymentMethodTypes:U.array(U.string()).check(U.minLength(1)),recipient:U.optional(U.string())}),U.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:xr(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});function Er(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return Bt(Tr,{context:U.object({paymentMethod:U.optional(U.string())}),async createCredential({challenge:e,context:a}){let o=a?.paymentMethod??i;if(!o)throw Error(`paymentMethod is required (pass via context or parameters)`);let s=e.request.amount,c=e.request.currency,l=typeof e.request.externalId==`string`?e.request.externalId:void 0,u=e.request.methodDetails?.networkId;if(!u)throw Error(`networkId is required in challenge.methodDetails`);let d=e.request.methodDetails?.metadata;if(d?.externalId)throw Error(`methodDetails.metadata.externalId is reserved; use credential externalId instead`);let f=e.expires?Math.floor(new Date(e.expires).getTime()/1e3):Math.floor(Date.now()/1e3)+3600,p=await n({amount:s,challenge:e,client:t,currency:c,expiresAt:f,metadata:d,networkId:u,paymentMethod:o}),m=l??r;return jt({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function Dr(e){return[Er(e)]}(function(e){e.charge=Er})(Dr||={});function Or(){return vr({method:`stripe`,supports(e){return e.method===`stripe`&&e.intent===`charge`},async setup({challenge:e,methodOpts:t}){let n=e.request,r=n.currency,i=Ar(L.object({paymentMethod:L.string(),secretKey:L.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new qn({code:`MISSING_ENV`,message:`MPPX_STRIPE_SECRET_KEY environment variable is required for Stripe payments.`,exitCode:2});return{tokenSymbol:r?.toUpperCase()??``,tokenDecimals:n.decimals??2,methods:[Dr.charge({paymentMethod:i.paymentMethod,createToken:async({paymentMethod:e,amount:t,currency:n,networkId:r,expiresAt:i,metadata:o})=>{let s=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()}),c=kr(a),l=process.env.MPPX_STRIPE_SPT_URL?process.env.MPPX_STRIPE_SPT_URL:c?`https://api.stripe.com/v1/test_helpers/shared_payment/granted_tokens`:`https://api.stripe.com/v1/shared_payment/issued_tokens`;if(r){let e=c?`seller_details[network_id]`:`seller_details[network_business_profile]`;s.set(e,r)}if(o)for(let[e,t]of Object.entries(o))s.set(`metadata[${e}]`,t);let u={Authorization:`Basic ${btoa(`${a}:`)}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":`2026-07-29.preview`},d=await globalThis.fetch(l,{method:`POST`,headers:u,body:s});if(!d.ok){let a=await d.json();if(c&&(o||r)&&a.error.message.includes(`Received unknown parameter`)){let r=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()});if(d=await globalThis.fetch(l,{method:`POST`,headers:u,body:r}),!d.ok)throw new qn({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${(await d.json()).error.message}`,exitCode:77})}else throw new qn({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${a.error.message}`,exitCode:77})}let{id:f}=await d.json();return f}})]}},formatReceiptField(e,t){if(e===`reference`&&typeof t==`string`&&t.startsWith(`pi_`)){let e=process.env.MPPX_STRIPE_SECRET_KEY,n=`https://dashboard.stripe.com${e!==void 0&&kr(e)?`/test`:``}/payments/${t}`;return Z.link(n,t,!0)}}})}function kr(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function Ar(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}const jr=Symbol.for(`mppx.fetch.skipPayment`);function Mr(e,t,n){return async(r,i)=>{let a=new Request(r,i),o=Pr(a.headers)??n?.challenge,{response:s}=await t.send((t,n)=>e(t,{...n,...i?.[jr]?{[jr]:!0}:{}}),a,{...n,challenge:o});if(s.status===402&&o)for(let e of Nr(s))e.method===o.method&&e.intent===o.intent&&await t.challenge(s,{...n,challenge:e},a.url);return s}}function Nr(e){try{return _t(e)}catch{return[]}}function Pr(e){for(let[,t]of e){let e=Mt(t);if(e)try{return Dt(e).challenge}catch{}}}const Fr=Symbol(`mppx.deferredContext`);function Ir(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=Vr(n)}return t}function Lr(e,t){let n=Ir(e),r=Jr(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[Vr(e)]??1,index:t}));return{definition:r,entries:i,header:zr(i),keys:n}}function Rr(e){let t=e.split(/\s*,\s*/).map(e=>e.trim()).filter(Boolean);if(t.length===0)throw Error(`Accept-Payment header is empty.`);return t.map((e,t)=>Kr(e,t))}function zr(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${Qr(n)}`}).join(`, `)}function Br(e,t,n,r){let i=new Map;for(let e of t){let t=Vr(e),n=i.get(t);n?n.push(e):i.set(t,[e])}return e.flatMap((e,t)=>{let a=i.get(Vr(e));if(!a)return[];let o=Hr(e,n);return!o||o.q<=0?[]:a.filter(t=>t.canHandleChallenge?.(r===void 0?{challenge:e}:{challenge:e,context:r})??!0).map(n=>({challenge:e,index:t,match:o,method:n}))}).sort((e,t)=>Gr(e.challenge)-Gr(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function Vr(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function Hr(e,t){let n;for(let r of t){if(!Ur(e,r))continue;let t={...r,specificity:Wr(r)};(!n||t.specificity>n.specificity||t.specificity===n.specificity&&t.q>n.q||t.specificity===n.specificity&&t.q===n.q&&t.index<n.index)&&(n=t)}return n}function Ur(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function Wr(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function Gr(e){return+!!On(e)}function Kr(e,t){let n=/^(?<method>[^/;\s]+|\*)\s*\/\s*(?<intent>[^/;\s]+|\*)(?<params>(?:\s*;\s*.+)?)$/u.exec(e),r=n?.groups?.method,i=n?.groups?.intent;if(!r||!i)throw Error(`Invalid Accept-Payment entry: ${e}`);$r(r,`method`),$r(i,`intent`);let a=1;for(let t of qr(n.groups?.params)){if(!t)continue;let n=/^(?<name>[A-Za-z0-9_-]+)\s*=\s*(?<value>\S+)$/u.exec(t),r=n?.groups?.name,i=n?.groups?.value;if(!r||!i)throw Error(`Invalid Accept-Payment parameter: ${t}`);r===`q`&&(a=Xr(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function qr(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function Jr(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>Vr(e))),a={};for(let[e,t]of Object.entries(r??{})){if(!i.has(e))throw Error(`Unknown payment preference "${e}". Available: ${[...i].join(`, `)}`);a[e]=Yr(t,`payment preference "${e}"`)}return a}function Yr(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return Zr(e,t)}function Xr(e,t){if(!/^0(?:\.\d{0,3})?$|^1(?:\.0{0,3})?$/.test(e))throw Error(`Invalid q-value for ${t}. Expected an HTTP qvalue.`);return Zr(Number(e),t)}function Zr(e,t){if(e<0||e>1)throw Error(`Invalid q-value for ${t}. Expected a value between 0 and 1.`);let n=Math.round(e*1e3);if(Math.abs(e*1e3-n)>1e-9)throw Error(`Invalid q-value for ${t}. Expected at most 3 decimal places.`);return n/1e3}function Qr(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function $r(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}function ei(e){let t=``,n=!1,r=!1,i,a=``;function o(t){if(t===``){i!==void 0&&e({data:i,event:a||`message`}),i=void 0,a=``;return}let n=t.indexOf(`:`);if(n===0)return;let r=n===-1?t:t.slice(0,n);if(r!==`data`&&r!==`event`)return;let o=``;n!==-1&&(o=t.slice(t.charCodeAt(n+1)===32?n+2:n+1)),r===`event`?a=o:i=i===void 0?o:i+`
2
+ `+o}return{feed(e){if(!n&&e&&(n=!0,e.startsWith(``)&&(e=e.slice(1))),r&&e&&(r=!1,e.startsWith(`
3
+ `)&&(e=e.slice(1))),t+=e,e.indexOf(`
4
+ `)===-1&&e.indexOf(`\r`)===-1)return;let i=0,a=t.indexOf(`
5
+ `),s=t.indexOf(`\r`);for(;a!==-1||s!==-1;){let e=a===-1?s:s===-1?a:Math.min(a,s);o(t.slice(i,e)),i=e+1,e===s&&(i===t.length?r=!0:a===i&&i++,s=t.indexOf(`\r`,i)),a!==-1&&a<i&&(a=t.indexOf(`
6
+ `,i))}t=t.slice(i)}}}const ti=[V.authorization,Wt,`PAYMENT-RESPONSE`,Gt];function ni(e,t,n){let r=new Headers(e.headers);for(let e of ti)e===V.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}function ri(e){if(typeof e==`string`)try{let t=JSON.parse(e),n=t?.id;return t?.jsonrpc!==`2.0`||typeof t?.method!=`string`?void 0:typeof n==`string`||typeof n==`number`?n:void 0}catch{return}}function ii(e){if(typeof e?.body!=`string`)return!1;try{let t=JSON.parse(e.body);return t?.jsonrpc===`2.0`&&t?.method===`tools/call`&&t.params?._meta?.[`mppx/payment-client`]===!0}catch{return!1}}const ai=1048576,oi=new WeakMap;function si(e){let t=ri(e?.body);if(t===void 0)return;let n=new Headers(e?.headers);if(n.has(`mcp-method`))return t;let r=n.get(`accept`)?.toLowerCase()??``;return r.includes(`application/json`)&&r.includes(`text/event-stream`)?t:void 0}function ci(e){if(!e||typeof e!=`object`)return;let t=e,n=t.id;if(t.jsonrpc!==`2.0`||n!==void 0&&typeof n!=`string`&&typeof n!=`number`)return;let r=`error`in t;if(r!==`result`in t)return r?Number.isInteger(t.error?.code)&&typeof t.error?.message==`string`?e:void 0:n!==void 0&&typeof t.result==`object`?e:void 0}function li(e){if(!e||typeof e!=`object`)return;let t=e?.challenges;if(!Array.isArray(t)||t.length===0)return;let n=[];for(let e of t){let t=ot.safeParse(e);if(!t.success)return;n.push(t.data)}let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function ui(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:li(e.error.data):li(e.result?._meta?.[`org.paymentauth/payment-required`])}function di(e,t){return!e||e.id!==t?[]:ui(e)?.challenges??[]}async function fi(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=ei(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=ci(JSON.parse(e.data))}catch{}});try{for(;;){if(i)return a;let{done:e,value:s}=await t.read();if(e)return o.feed(n.decode()),a;if(r+=s.byteLength,r>ai)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function pi(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=``;try{for(;;){let{done:e,value:a}=await t.read();if(e)return ci(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>ai)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function mi(e){let t=oi.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>ai)){if(t.includes(`application/json`))return pi(e);if(t.includes(`text/event-stream`))return fi(e)}})();return oi.set(e,n),n}function hi(){return{getChallenges(e,t){let n=si(t);return e.status===402||n===void 0?[]:mi(e).then(e=>di(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=Dt(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}function gi(){return{getChallenges(e){let t=e.headers.get(V.wwwAuthenticate);return e.status!==402||!t||!ht(t)?[]:_t(e)},setCredential(e,t,n){return ni(e,n?.challenge?xt(n.challenge):V.authorization,t)}}}function _i(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(Wt);if(!t)return[];let n=fn(t);return n.accepts.flatMap((e,t)=>{let r=Qt.safeParse(e);if(!r.success)return[];let i=r.data;return Dn(st({id:`x402:${t}`,intent:`charge`,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return ni(e,Gt,t)}}}function vi(e){return e}function yi(){let e=[gi(),_i(),hi()],t=new WeakMap,n=(e,n)=>{for(let r of n)t.set(r,e);return n},r=(t,r)=>{let i=(a,o)=>{for(let s=a;s<e.length;s++){let a=e[s],c=a.getChallenges(t,r);if(c instanceof Promise)return c.then(e=>i(s+1,[...o,...n(a,e)]));o.push(...n(a,c))}return o};return i(0,[])};return vi({name:`http`,isPaymentRequired(e,t){if(e.status===402)return!0;let n=r(e,t);return n instanceof Promise?n.then(e=>e.length>0):n.length>0},getChallenges(e,t){return r(e,t)},setCredential(n,r,i){let a=i?.challenge?t.get(i.challenge):void 0,o=e[0];if(!a&&!o)throw Error(`No protocol to attach the credential.`);return(a??o).setCredential(n,r,i)}})}const bi=new WeakMap;function xi(e,t){return bi.set(e,t),e}function Si(e){return bi.has(e)}function Ci(e,t){return Promise.resolve(bi.get(e)?.(t))}function wi(e){return bi.get(e)}const Ti=new WeakMap,Ei=new WeakMap,Di=new WeakMap,Oi=new WeakMap;function ki(e,t){return Ti.set(e,t),e}function Ai(e){Ti.delete(e)}function ji(e,t,n){Ti.has(e)&&Ei.set(t,n)}function Mi(e){return Ei.get(e)}function Ni(e,t){return Promise.resolve(Ti.get(e)?.(t)??t.response)}function Pi(e,t){return Oi.set(e,t),e}function Fi(e,t){try{return Oi.get(e)?.(t)}catch{return}}function Ii(e,t){Di.set(e,t)}function Li(e){return Di.get(e)??Ei.get(e)?.origin}function Ri(e,t,n){if(!zi(e)&&(e.method!==`tempo`||e.intent!==`session`))return;t=typeof t==`function`?t():t;let{realm:r}=e;if(r.toLowerCase()===t.hostname.toLowerCase())return;let i=t.origin.toLowerCase();for(let[e,t]of Object.entries(n??{}))if(t===r&&Bi(e)===i)return;throw Error(`Refusing to sign Tempo proof for realm ${JSON.stringify(r)} from ${t.origin}. Pin the realm to this origin with \`trustedTempoProofRealms\` if this server is expected to issue it.`)}function zi(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Bi(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}const Vi=Symbol.for(`mppx.fetch.wrapper`),Hi=Symbol.for(`mppx.fetch.identity`),Ui=Symbol.for(`mppx.fetch.skipPayment`),Wi=65536,Gi=new WeakMap;async function Ki(e){if(!e.body)return e;let t=e.clone().body.getReader(),n=[],r=0,i=!1,a=setTimeout(()=>{i=!0,t.cancel().catch(()=>{})},2e3);try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(n.push(a),r+=a.byteLength,r>Wi){i=!0;break}}}finally{clearTimeout(a),t.cancel().catch(()=>{})}if(!i)return e;e.body.cancel().catch(()=>{});let o=new Headers(e.headers);o.delete(`content-length`),o.set(`Mppx-Body-Truncated`,`true`);let s=new Response(new Blob(n).slice(0,Wi),{headers:o,status:e.status,statusText:e.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{value:e[t]});return s}async function qi(e,t){let n=e?.attempt.settle;if(!n)return t.status!==`pending`;e.attempt.settle=void 0;let r=await n(t);return r||(e.attempt.settle=n),r}function Ji(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=yi(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&_a(e.fetch)),d=e.eventDispatcher??Xi(),f=t??Lr(a),p=va(r),m=async(e,t,n)=>u?(await u.send(p,new Request(e,t),n)).response:p(e,t),h=async(e,t,r)=>{let g=ga(e,t?.headers),_=g.has(V.acceptPayment),v=Ca(g,f),y=ma(e,t,g),b=pa(e,t,g,v.header,_,n),x=await m(ya(b.input),b.init),S=ha(b.init,await y);if(t?.[Ui]||ii(S)||!await c.isPaymentRequired(x,S))return x;let C=t?.context,{context:w,orderChallenges:ee,...T}=S??{},te,E,D,O,k;try{for(let n=0;n<i;n++){E=await c.getChallenges(x,S);let i=(await wa(Br(E,a,v.entries,C),ee??s))[0];if(!i){if(await qi(O,{challenges:E,response:x,status:`rejected`}),n>0)return x;throw Error(`No method found for challenges: ${E.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let f=i.challenge;te=f,D=i.method,te.expires&&Rt(te.expires,te.id),await u?.challenge(x,{challenge:f},Oa(b.input).href);let g=await Aa(x,b.input,b.input,T);Ri(f,()=>Oa(g),l);let _=O,y=ct(f),w=_?.method===i.method&&_?.key===y,A=!1;if(_){let e=await qi(_,{challenges:E,response:x,status:w?`pending`:`rejected`});A=w&&!e}O=A?_:void 0;let j=ta(async n=>{if(n===void 0&&A&&_)return _.promise;A&&_&&(await qi(_,{status:`rejected`}),O=void 0),ba(e,t)?.throwIfAborted();let r=n??C;if(!Si(i.method))return Sa(f,i.method,r);let a={origin:Oa(g).origin,prepare:()=>Ci(i.method,{challenge:f,context:r,fetch:u?Mr(p,u,{challenge:f}):p,input:g,signal:ba(e,t)})},o=a.prepare().then(()=>Sa(f,i.method,r,a));return O={context:r,attempt:a,key:n===void 0?y:void 0,method:i.method,promise:o},o}),M=await d.emit(`challenge.received`,na({challenge:f,challenges:E,createCredential:j,init:t,input:e,method:i.method,response:x}))??(o?await o(te,{createCredential:j}):void 0)??await j(),N=O;N&&await N.promise.catch(()=>void 0)!==M&&(await qi(N,{status:`rejected`}),O=void 0);let P=O?O.context:C;xa(M),await d.emit(`credential.created`,ra({challenge:f,credential:M,init:t,input:e,method:i.method,response:x}));let F=e=>new It({cause:e,challenge:f,credential:M,transactionHash:Fi(i.method,M)});try{x=await m(g,{...c.setCredential({...T,headers:b.headers},M,{challenge:f}),redirect:`manual`},{challenge:f})}catch(e){throw k=F(e),e}let I=await c.isPaymentRequired(x,S);if(I||(await qi(N,{response:x,status:x.status>=300&&x.status<400?`pending`:x.ok?`accepted`:`rejected`}),O=void 0),x.ok&&Zi(d,`payment.response`)&&await d.emit(`payment.response`,ia({challenge:f,credential:M,init:t,input:e,method:i.method,response:x})),!I){if(x.status>=500&&Zi(d,`payment.failed`)){try{x=await Ki(x)}catch(e){throw k=F(e),x=new Response(null,{headers:x.headers,status:x.status,statusText:x.statusText}),e}await d.emit(`payment.failed`,aa({challenge:f,challenges:E,error:F(),init:t,input:e,method:i.method,response:x}))}return x.ok?Ni(i.method,{context:P,challenge:f,credential:M,fetch:p,headers:b.headers,input:g,...r?{refetch:()=>h(ya(b.input),t,!1)}:{},response:x,signal:ba(e,t)}):x}}E=void 0;try{E=await c.getChallenges(x,S)}catch{}return await qi(O,{challenges:E,response:x,status:`rejected`}),x}catch(n){throw await qi(O,{challenges:E,response:x,status:`rejected`}),await d.emit(`payment.failed`,aa({challenge:te,challenges:E,error:k??n,init:t,input:e,method:D,response:x})),n}},g=(e,t)=>h(e,t,!0);return g[Vi]=p,u&&(g[Hi]=u),g}function Yi(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return Array.isArray(e)?Object.fromEntries(e):e}function Xi(){let e={"*":new Set,"challenge.received":new Set,"credential.created":new Set,"payment.failed":new Set,"payment.response":new Set},t={async emit(t,n){switch(t){case`challenge.received`:{let r;for(let t of e[`challenge.received`]){let e=await Qi(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await ea(e[`*`],t,n),r}case`credential.created`:await $i(e[`credential.created`],n),await ea(e[`*`],t,n);return;case`payment.failed`:await $i(e[`payment.failed`],n),await ea(e[`*`],t,n);return;case`payment.response`:await $i(e[`payment.response`],n),await ea(e[`*`],t,n);return}},on:(t,n)=>{switch(t){case`*`:case`challenge.received`:case`credential.created`:case`payment.failed`:case`payment.response`:return e[t].add(n),()=>e[t].delete(n);default:throw Error(`Unknown client event "${String(t)}".`)}}};return Gi.set(t,t=>e[t].size>0||e[`*`].size>0),t}function Zi(e,t){return Gi.get(e)?.(t)??!0}async function Qi(e,t){try{return await e(t)}catch{return}}async function $i(e,t){for(let n of e)try{await n(t)}catch{}}async function ea(e,t,n){await $i(e,Object.freeze({name:t,payload:n}))}function ta(e){let t;return n=>(t??=e(n),t)}function na(e){return Object.freeze({challenge:ua(e.challenge),challenges:e.challenges.map(e=>ua(e)),createCredential:e.createCredential,init:oa(e.init),input:sa(e.input),method:ca(e.method),response:la(e.response)})}function ra(e){return Object.freeze({challenge:ua(e.challenge),credential:e.credential,init:oa(e.init),input:sa(e.input),method:ca(e.method),...e.response===void 0?{}:{response:la(e.response)}})}function ia(e){return Object.freeze({challenge:ua(e.challenge),credential:e.credential,init:oa(e.init),input:sa(e.input),method:ca(e.method),response:la(e.response)})}function aa(e){return Object.freeze({...e.challenge?{challenge:ua(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>ua(e))}:{},error:e.error,init:oa(e.init),input:sa(e.input),...e.method?{method:ca(e.method)}:{},...e.response===void 0?{}:{response:la(e.response)}})}function oa(e){if(e)return fa({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function sa(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function ca(e){return fa(Object.assign({},e))}function la(e){if(e instanceof Response)try{return e.clone()}catch{let t=new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText});for(let n of[`redirected`,`type`,`url`])Object.defineProperty(t,n,{value:e[n]});return t}return ua(e)}function ua(e){try{return da(structuredClone(e))}catch{return fa(e)}}function da(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))da(t);return e}function fa(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function pa(e,t,n,r,i,a){let o=!!r&&!i&&Ta(e,a);if(!o)return{headers:n,init:t,input:e};let s=new Headers(e instanceof Request?e.headers:void 0);return n.forEach((e,t)=>{s.set(t,e)}),s.set(V.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function ma(e,t,n){if(!(!(e instanceof Request)||t?.body!==void 0||!e.body||e.bodyUsed)){if(!n.has(`mcp-method`)){let e=n.get(`accept`)?.toLowerCase()??``;if(!e.includes(`application/json`)||!e.includes(`text/event-stream`))return}try{return e.clone().text().catch(()=>void 0)}catch{return}}}function ha(e,t){return t===void 0?e:{...e,body:t}}function ga(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function _a(e){return e[Hi]}function va(e){let t=e;for(;t[Vi];)t=t[Vi];return t}function ya(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function ba(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function xa(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
7
+ `))throw Error(`Credential header value contains illegal newline characters`)}async function Sa(e,t,n,r){let i=t.context&&n!==void 0?t.context.parse(n):void 0,a=i===void 0?{challenge:e}:{challenge:e,context:i};return r?.origin&&Ii(a,r.origin),r&&ji(t,a,r),t.createCredential(a)}function Ca(e,t){let n=e.get(V.acceptPayment);if(!n)return t;try{return{...t,entries:Rr(n),header:n}}catch{return t}}async function wa(e,t){return t?t(e):e}function Ta(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=Oa(e);return t===`same-origin`?!Da()||n.origin===globalThis.location.origin:t.origins.some(e=>Ea(n,e))}function Ea(e,t){if(t.startsWith(`*.`)){let n=t.slice(1);return e.hostname.endsWith(n)||e.hostname===t.slice(2)}return e.origin===new URL(t).origin}function Da(){return globalThis.location!==void 0}function Oa(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,Da()?globalThis.location.href:void 0)}function ka(e,t){let n=e instanceof Request?e:void 0;if((t.mode??n?.mode)===`no-cors`)throw Error(`Cannot automatically pay a no-cors request: it cannot carry a credential.`);if((t.cache??n?.cache)===`only-if-cached`)throw Error(`Cannot automatically pay an only-if-cached request: its retry cannot reach the server.`)}async function Aa(e,t,n,r){if(ka(t,r),!e.url)return t;let i=new URL(e.url),a=Oa(n);if(i.origin!==a.origin)throw Error(`Refusing to send payment credential across redirect from ${a.origin} to ${i.origin}`);let o=(r.method??(t instanceof Request?t.method:`GET`)).toUpperCase();if(e.redirected&&o!==`GET`&&o!==`HEAD`)throw Error(`Cannot automatically pay a redirected ${o} request. Use prepareRequest() to preserve redirect semantics.`);if(t instanceof Request){let n=r.body==null?t.clone():t,i=new Request(n,t.mode===`navigate`&&r.mode===void 0?{...r,mode:`same-origin`}:r);return i.url.split(`#`)[0]===e.url?i:i.body?new Request(e.url,{body:await i.arrayBuffer(),cache:i.cache,credentials:i.credentials,headers:i.headers,integrity:i.integrity,keepalive:i.keepalive,method:i.method,mode:i.mode,redirect:i.redirect,referrer:i.referrer,referrerPolicy:i.referrerPolicy,signal:i.signal}):new Request(e.url,i)}return e.url}function ja(e={}){let{account:t}=e;return(e,{account:n}={})=>{let r=n??t;if(!r){if(!e.account)throw Error("No `account` provided. Pass `account` to parameters or context.");return e.account}return fe(r)}}function Ma(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}const Na={[R.id]:R,[ne.id]:ne};function Pa(e,t={}){return c(e.url,{fetchFn:e.fetch,fetchOptions:{headers:Ma(e)},...t})}function Fa(r){let{chain:i,getClient:a,remoteFeePayer:o,rpcUrl:s}=r;return a?!i?.serializers&&!o?a:async e=>{let r=await a(e),s=r;if(o&&r.transport.key!==`feePayer`){let e=r.request.bind(r),i=de(n({request:t=>e(t)},{retryCount:0}),Pa(o,{retryCount:r.transport.retryCount}))({account:r.account,chain:r.chain,pollingInterval:r.pollingInterval,retryCount:0}),a=t({...i.config,retryCount:0},i.value);s=Object.assign({},r,{request:a.request,transport:{...a.config,...a.value}})}return!i?.serializers||s.chain?.serializers?.transaction?s:Object.assign({},s,{chain:{...i,...e.chainId===void 0?{}:{id:e.chainId},...s.chain,formatters:s.chain?.formatters??i.formatters,prepareTransactionRequest:s.chain?.prepareTransactionRequest??i.prepareTransactionRequest,serializers:s.chain?.serializers?.transaction?s.chain.serializers:i.serializers}})}:({chainId:t})=>{if(!s)throw Error("No `rpcUrl` provided.");let n=t||Number(Object.keys(s)[0]),r=s[n];if(!r)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let a=o?de(c(r),Pa(o)):c(r);return e({chain:Na[n]??{...i,id:n},transport:a})}}function Ia(e,t){if(t!==void 0&&e.chain?.id!==void 0&&e.chain.id!==t)throw Error(`Chain ID mismatch: expected ${t}, got ${e.chain.id}.`)}function La(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}const Ra=A.slice(k.keccak256(O.fromString(`mpp`),{as:`Hex`}),0,4);function za(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,10))}function Ba(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(A.toBytes(Ra),0),i[4]=1,i.set(za(t),5),n&&i.set(za(n),15),i.set(Va(r),25),A.fromBytes(i)}function Va(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,7))}function Ha(e,t){return ge.resolve(e).toLowerCase()===ge.resolve(t).toLowerCase()}const Ua=10000n,Wa=[Yn.pathUsd,Yn.usdc,Yn.ousd];async function Ga(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t;if(!Number.isFinite(o)||o<0||o>50)throw Error(`Auto-swap slippage must be between 0 and 50 percent.`);if(t.maxAmountIn!==void 0&&t.maxAmountIn<=0n)throw Error(`Auto-swap maxAmountIn must be positive.`);let s=a.filter(e=>!Ha(e,i)),c=await Promise.allSettled([y(e,{...z.token.getBalance.call(e,{account:n,token:i}),account:null}),...s.map(t=>y(e,{...z.token.getBalance.call(e,{account:n,token:t}),account:null}))]),l=c[0];if(l.status!==`fulfilled`)throw l.reason;let u=l.value;if(u>=r)return;let d=r-u,f=BigInt(Math.round(o*100)),p=t.maxAmountIn??d+d*f/Ua;for(let t=0;t<s.length;t++){let n=c[t+1];if(n.status!==`fulfilled`)continue;let r=n.value;if(r<=0n)continue;let a=s[t];try{let t=await z.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:d});if(t<=0n||t>p)continue;let n=t+t*f/Ua,o=n<p?n:p;if(r>=o)return[z.token.approve.call(e,{amount:o,spender:ce.stablecoinDex,token:a}),z.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:d,maxAmountIn:o})]}catch{}}throw new qa({currency:i})}function Ka(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...e.fallback===!1?[]:t.filter(t=>!e.tokenIn.some(e=>Ha(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var qa=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}};function Ja(e){let t=BigInt(e.amount),n=e.methodDetails?.splits??[],r=n.reduce((e,t)=>e+BigInt(t.amount),0n);if(r>=t)throw Error(`Invalid charge request: split total must be less than total amount.`);let i=t-r;if(i<=0n)throw Error(`Invalid charge request: primary transfer amount must be positive.`);return[{amount:i.toString(),memo:e.methodDetails?.memo,recipient:e.recipient},...n.map(e=>({amount:BigInt(e.amount).toString(),memo:e.memo,recipient:e.recipient}))]}function Ya(e,t,n){t&&(n&&!n.some(e=>Ha(e,t))||e.some(e=>Ha(e,t))||e.push(t))}async function Xa(e,t,n){try{return(await z.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function Za(e){let t=e.chain?.feeToken;if(t)return le.toAddress(t);let n=e.chain?.id;return n?Xn[n]:void 0}function Qa(e){let t=[];return Ya(t,Yn.pathUsd),Ya(t,Xn[e]),t}async function $a(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])Ya(o,e,n);if(Ya(o,await z.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),Ya(o,Za(i),n),!a)for(let e of r??[])Ya(o,e,n);for(let e of o)if(await Xa(i,t,e))return e;return o[0]}const eo=f([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]);function to(e){if(e!==void 0)return Zn[e]}function no(e){let t=to(e.chainId);return!!t&&l(e.currency,{strict:!1})&&u(e.currency,t.token)}function ro(e){let t=to(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let i=BigInt(n.amount),a=n.memo;return{calls:[{data:r({abi:oe.tip20,functionName:`approve`,args:[t.swap,i]}),to:t.token},{data:r({abi:eo,functionName:`swapTo`,args:[t.token,i,e.currency,n.recipient,a]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:i,memo:a,recipient:n.recipient}]}}async function io(e,t){let n=ro(t);if(n)try{return await y(e,z.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await h(e,{account:t.account,calls:n.calls}),n)}catch{return}}const ao={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]};function oo(e){return{name:`MPP`,version:`3`,chainId:e}}function so(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function co(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:oo(n),types:ao,primaryType:`Proof`,message:so({account:t,challengeId:r,realm:i})}}function lo(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const uo=7200n,fo=a({abi:oe.zonePortal,name:`WithdrawalProcessed`});function po(e){return Number.isInteger(e)&&e>0&&e<4217e5}function mo(e,t){return po(t)?e===!0||(e?.includes(t)??!1):!1}function ho(e){return ce.zonePortal(e)}function go(e){if(e>=2**32)return e%2**32;if(e>142431e4&&e<142432e4)return e-142431e4;if(e>4217e5&&e<42171e4)return e-4217e5;throw Error(`Cannot derive a Zone ID from chain ID ${e}. Pass \`zoneId\`.`)}function _o(e){if(e>=2**32)return Math.floor(e/2**32);if(e>142431e4&&e<142432e4)return 42431;if(e>4217e5&&e<42171e4)return 4217}function vo(e){return k.keccak256(E.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function yo(e,t){let{timeoutMs:n=6e4}=t;if(!Number.isFinite(n)||n<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);let r=await g(e,{cacheTime:0}),i=r>uo?r-uo:0n,a=Date.now()+n;for(;;){if(i<=r){let n=(await _(e,{address:t.portal,event:fo,args:{senderTag:t.senderTag,...t.to?{to:t.to}:{}},fromBlock:i,toBlock:r}))[0]?.transactionHash;if(n)return n;i=r+1n}if(Date.now()+500>a)throw Error(`Zone withdrawal ${t.senderTag} did not settle on Tempo within ${n}ms.`);await new Promise(e=>setTimeout(e,500)),r=await g(e,{cacheTime:0})}}const bo=[`push`,`pull`],xo=U.object({amount:W(),memo:U.optional(K()),recipient:U.pipe(U.string(),U.transform(e=>e))}),So=(1n<<64n)-1n,Co={dev_second:1n,day:86400n,week:604800n},wo=U.pipe(G(),U.transform(e=>e.toLowerCase())),To=U.object({accessKeyAddress:wo,keyType:U.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:U.optional(U.pipe(U.string().check(U.regex(/^0x[0-9a-fA-F]{120}$/)),U.transform(e=>e)))}),Eo=U.object({accessKey:U.optional(To),chainId:U.optional(U.number())}),Do=tt(`subscriptionExpires must be a valid date`).check(U.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),Oo=U.enum([`dev_second`,`day`,`week`]),ko=U.pipe(U.union([U.string(),U.bigint(),U.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),U.transform(e=>e.toString())).check(U.regex(/^[1-9]\d*$/,`Invalid periodCount`),U.refine(e=>{try{return BigInt(e)<=So}catch{return!1}},`periodCount exceeds uint64`));function Ao(e){return U.refine(e=>{let{amount:t,decimals:n}=e;return m(t,n)>0n},e)}function jo(e){let{periodCount:t,periodUnit:n}=e;try{let e=Co[n];return e!==void 0&&BigInt(t)*e<=So}catch{return!1}}const Mo=zt({name:`tempo`,intent:`charge`,schema:{credential:{payload:U.discriminatedUnion(`type`,[U.object({hash:K(),type:U.literal(`hash`)}),U.object({signature:q(),type:U.literal(`transaction`)}),U.object({signature:q(),type:U.literal(`proof`)}),U.object({hash:K(),senderTag:K(),type:U.literal(`zone`),zoneId:U.number().check(U.refine(po,`Invalid Zone ID`))})])},request:U.pipe(U.object({machineTokenEnabled:U.optional(U.boolean()),amount:W(),chainId:U.optional(U.number()),currency:U.string(),decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),feePayer:U.optional(U.pipe(U.union([U.boolean(),U.custom()]),U.transform(e=>typeof e==`object`||e))),memo:U.optional(U.never()),recipient:U.optional(U.string()),splits:U.optional(U.array(xo).check(U.minLength(1),U.maxLength(10))),supportedModes:U.optional(U.array(U.enum(bo)).check(U.minLength(1))),zones:U.optional(U.union([U.literal(!0),U.array(U.number().check(U.refine(po,`Invalid Zone ID`))).check(U.minLength(1))]))}).check(U.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=m(e,t),i=n.reduce((e,n)=>e+m(n.amount,t),0n);return n.every(e=>m(e.amount,t)>0n)&&i<r},`Invalid splits`)),U.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,zones:c,...l})=>({...l,amount:m(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0||c!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:m(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),No=zt({name:`tempo`,intent:`session`,schema:{credential:{payload:U.discriminatedUnion(`action`,[U.object({action:U.literal(`open`),authorizedSigner:U.optional(U.string()),channelId:K(),cumulativeAmount:W(),descriptor:U.optional(U.custom()),signature:q(),transaction:q(),type:U.literal(`transaction`)}),U.object({action:U.literal(`topUp`),additionalDeposit:W(),channelId:K(),descriptor:U.optional(U.custom()),transaction:q(),type:U.literal(`transaction`)}),U.object({action:U.literal(`voucher`),channelId:K(),cumulativeAmount:W(),descriptor:U.optional(U.custom()),signature:q()}),U.object({action:U.literal(`close`),channelId:K(),closeSignature:q(),cumulativeAmount:W(),descriptor:U.optional(U.custom()),signature:q()})])},request:U.pipe(U.object({amount:W(),chainId:U.optional(U.number()),channelId:U.optional(K()),currency:U.string(),decimals:U.number(),escrowContract:U.optional(U.string()),feePayer:U.optional(U.pipe(U.union([U.boolean(),U.custom()]),U.transform(e=>typeof e==`object`||e))),feeToken:U.optional(G()),minVoucherDelta:U.optional(W()),operator:U.optional(G()),recipient:U.optional(U.string()),sessionProtocol:U.optional(U.enum([Xe.v2,Xe.v1])),sessionSnapshot:U.optional(U.custom()),suggestedDeposit:U.optional(W()),unitType:U.string()}).check(U.refine(({amount:e,decimals:t})=>m(e,t)>0n,`Session amount must be greater than 0`)),U.transform(({amount:e,chainId:t,channelId:n,decimals:r,escrowContract:i,feePayer:a,feeToken:o,minVoucherDelta:s,operator:c,sessionProtocol:l,sessionSnapshot:u,suggestedDeposit:d,...f})=>({...f,amount:m(e,r).toString(),...d?{suggestedDeposit:m(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:m(s,r).toString()},...t!==void 0&&{chainId:t},...a!==void 0&&{feePayer:a},...o!==void 0&&{feeToken:o},...c!==void 0&&{operator:c},...l!==void 0&&{[Ye.sessionProtocol]:l},...u!==void 0&&{[Ye.sessionSnapshot]:u}}})))}}),Po=zt({name:`tempo`,intent:`subscription`,schema:{credential:{payload:U.object({signature:q(),type:U.literal(`keyAuthorization`)})},request:U.pipe(U.object({amount:W(),accessKey:U.optional(To),chainId:U.optional(U.number()),currency:wo,decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),methodDetails:U.optional(Eo),periodCount:ko,periodUnit:Oo,recipient:wo,subscriptionExpires:Do}).check(Ao(`Subscription amount must be greater than 0`),U.refine(jo,`Subscription period exceeds uint64`)),U.transform(({accessKey:e,amount:t,chainId:n,decimals:r,methodDetails:i,subscriptionExpires:a,...o})=>{let s={...i,...e!==void 0&&{accessKey:e},...n!==void 0&&{chainId:n}};return{...o,amount:m(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}}),Fo=U.object({account:U.optional(U.custom()),autoSwap:U.optional(U.custom()),feeToken:U.optional(U.custom()),mode:U.optional(U.enum(bo))});function Io(e={}){let{clientId:t}=e;if((e.maxAmount!==void 0||e.maxAtomicAmount!==void 0)&&e.currencies===void 0)throw Error(`Tempo charge maxAmount and maxAtomicAmount require currencies.`);let n={maxAmount:Wo(e.maxAmount,e.decimals),maxAtomicAmount:e.maxAtomicAmount===void 0?void 0:BigInt(e.maxAtomicAmount)},r=Fa({chain:R,getClient:e.getClient,rpcUrl:Qn}),i=ja({account:e.account});zo(e.zone);let a=new Map,o=Bt(Mo,{canHandleChallenge({challenge:t}){try{return Go(e,n,t.request),!0}catch{return!1}},context:Fo,async createCredential({challenge:o,context:s}){Go(e,n,o.request);let c=o.request.methodDetails?.chainId??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),l=await r({chainId:c});Ia(l,c);let u=c??l.chain?.id;if(La(e.allowedChainIds,u),u===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");let{request:d}=o,{amount:f,methodDetails:p}=d,m=p?.supportedModes??[`pull`,`push`],h=e.zone?.client.chain,g=e.zone?e.zone.zoneId??go(h?.id??0):void 0,_=h?.sourceId??(h?_o(h.id):void 0),y=s?.mode??e.mode;if(BigInt(f)>0n&&e.zone&&g!==void 0&&_===u&&m.includes(`push`)&&(y===void 0||y===`push`)&&mo(p?.zones,g)&&!p?.splits&&(a.has(Ho(o))||Bo(o.expires,e.zone.settlementTimeoutMs)))return Ro({challenge:o,clientId:t,client:l,pending:a,zone:e.zone,zoneId:g});let x=i(l,s),ee=async t=>await e.resolveAccount?.({account:x,chainId:u,operation:t})??x;if(BigInt(f)===0n){let e=await ee({kind:`signPaymentProof`});return jt({challenge:o,payload:{signature:await w(l,{account:e,...co({account:e.address,chainId:u,challengeId:o.id,realm:o.realm})}),type:`proof`},source:lo({address:e.address,chainId:u})})}let T=d.currency,te=no({chainId:u,currency:T}),E=Ba({challengeId:o.id,clientId:t,serverId:o.realm}),D=Ja({amount:f,methodDetails:{...p,memo:E},recipient:d.recipient}),O=D.map(e=>z.token.transfer.call(l,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:T})),k=Ka(s?.autoSwap??e.autoSwap,Wa),A=p?.machineTokenEnabled===!0?ro({chainId:u,currency:T,transfers:D}):void 0,j=x,M;if(A){let e=await(async()=>{try{return await ee({calls:A.calls,kind:`executeCalls`})}catch{return}})();e&&(M=await io(l,{account:e.address,chainId:u,currency:T,transfers:D}),M&&(j=e))}let N;M||(j=await ee({kind:`executeCalls`,...k?{}:{calls:O}}),N=k?await Ga(l,{account:j.address,amountOut:BigInt(f),tokenOut:T,tokenIn:k.tokenIn,slippage:k.slippage,maxAmountIn:k.maxAmountIn}):void 0);let P=M?.calls??[...N??[],...O],F=Qa(u),I=(s?.feeToken??e.feeToken)||(M||te?await $a({account:j.address,allowedTokens:F,candidateTokens:F,client:l,prioritizeCandidates:!0}):void 0),L=(()=>{let t=s?.mode??e.mode;if(t){if(!m.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=j.type===`json-rpc`?`push`:`pull`;return m.includes(n)?n:m[0]})(),R=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!o.expires)return e;let t=Math.floor(new Date(o.expires).getTime()/1e3)+1;return Math.min(e,t)})();if(L===`push`){let{receipts:e}=j.type===`local`?{receipts:[await S(l,{account:j,calls:P,...I?{feeToken:I}:{},nonceKey:`expiring`,validBefore:R})]}:await b(l,{account:j,...I?{capabilities:{feeToken:I}}:{},calls:P,experimental_fallback:P.length===1,forceAtomic:P.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return jt({challenge:o,payload:{hash:t,type:`hash`},source:lo({address:j.address,chainId:u})})}let ne=()=>{if(p?.feePayer!==!0)return;let e=15e3,t=o.expires?new Date(o.expires).getTime():1/0,n=Date.now();if(!(t-n>=e))throw Error(`Sponsored challenge expires in less than 15 seconds; the fee payer would reject the transaction. Request a new challenge.`);if(!(R*1e3-n>=e))throw Error(`Sponsored transaction preparation took too long: less than 15 seconds of its validity window remain, so the fee payer would reject it.`)};ne();let re=await v(l,{account:j,calls:P,...I?{feeToken:I}:{},nonceKey:`expiring`,validBefore:R});if(re.gas=(re.gas??0n)+5000n,p?.feePayer){let e=re;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return ne(),jt({challenge:o,payload:{signature:await C(l,re),type:`transaction`},source:lo({address:j.address,chainId:u})})}}),s=new Map,c=async t=>{Go(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,a=s.get(i);return a||(a=o.createCredential(t).finally(()=>s.delete(i)),s.set(i,a)),a};return Pi({...o,createCredential:c},Lo)}function Lo(e){let t=Mo.schema.credential.payload.safeParse(Dt(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`||n.type===`zone`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(_e.serializedType))return;let i=_e.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&_e.serialize(i)===r)return d(r)}async function Ro(e){let{challenge:t,client:n,pending:r,zone:i,zoneId:a}=e,o=t.request.recipient,s=Ho(t),c=r.get(s);if(!c){let t={sent:!1};c=Uo(e,t),r.set(s,c),c.catch(()=>{t.sent||r.delete(s)})}let l=await c,u;try{u=await yo(n,{portal:ho(a),senderTag:l,timeoutMs:Vo(t.expires,i.settlementTimeoutMs),to:o})}catch(e){throw new Lt({cause:e,challengeId:t.id,senderTag:l,zoneId:a})}return r.delete(s),jt({challenge:t,payload:{hash:u,senderTag:l,type:`zone`,zoneId:a}})}function zo(e){let t=e?.settlementTimeoutMs;if(t!==void 0&&(!Number.isFinite(t)||t<0))throw Error("`zone.settlementTimeoutMs` must be a finite, non-negative number.");let n=e?.client.chain?.id;if(e?.zoneId===void 0||n===void 0||_o(n)===void 0)return;let r=go(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function Bo(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+15e3}function Vo(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function Ho(e){return JSON.stringify(e)}async function Uo(e,t){let{challenge:n,clientId:r,zone:i}=e,a=n.request,o=i.client.account;if(!o)throw Error("`zone.client` requires an account.");let s=BigInt(a.amount),c=a.currency,l=a.recipient,u=Ba({challengeId:n.id,clientId:r,serverId:n.realm}),f=await z.zone.getWithdrawalFee(i.client),[,m]=z.zone.requestWithdrawal.calls({amount:s,fallbackRecipient:o.address,memo:u,to:l,token:c}),h=await v(i.client,{account:o,calls:[z.token.approve.call({amount:s+f,spender:ce.zoneOutbox,token:c}),m]}),g=await C(i.client,h);t.sent=!0;let _=d(g),y=await x(i.client,{serializedTransaction:g}).catch(e=>ee(i.client,{hash:_,timeout:15e3}).catch(()=>{let t=Error(`Zone withdrawal outcome is unknown: transaction ${_} may have been sent. Retrying this challenge does not withdraw again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),t}));if(y.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${y.transactionHash} reverted.`);let[b]=p({abi:oe.zoneOutbox,eventName:`WithdrawalRequested`,logs:y.logs});if(!b)throw Error("Zone withdrawal request did not emit `WithdrawalRequested`.");return vo({fallbackNonce:b.args.fallbackNonce,sender:b.args.sender,transactionHash:y.transactionHash})}function Wo(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo charge maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo charge maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return m(e,t)}}function Go(e,t,n){let{amount:r,methodDetails:i,recipient:a}=n,o=i?.chainId;if(e.expectedChainId!==void 0&&o!==void 0&&o!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${o}.`);if((o!==void 0||e.allowedChainIds?.length===0)&&La(e.allowedChainIds,o),e.currencies&&!e.currencies.some(e=>e.toLowerCase()===n.currency.toLowerCase()))throw Error(`Tempo charge currency is not allowed: ${n.currency}.`);if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!a||!t.has(a.toLowerCase()))throw Error(`Unexpected primary recipient: ${a}`);let n=i?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}if(t.maxAtomicAmount!==void 0&&BigInt(r)>t.maxAtomicAmount)throw Error(`Tempo charge amount exceeds maxAtomicAmount.`);if(t.maxAmount!==void 0&&BigInt(r)>t.maxAmount)throw Error(`Tempo charge amount exceeds maxAmount.`)}const Ko=(1n<<96n)-1n;function qo(e){return e>=0n&&e<=Ko}function Jo(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return qo(t)?t:void 0}function Yo(e){return Xo(e),e}function Xo(e){if(!qo(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const Zo=new Set([`open`,`topUp`,`voucher`,`close`]);function Qo(e){return typeof e==`object`&&!!e}function $o(e){return typeof e==`string`&&Zo.has(e)}function es(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!$o(t.action))}function ts(e,t=`No session credential context available.`){if(!es(e))throw Error(t);return e}function ns(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function rs(e){return Qo(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function is(e){return Qo(e)?e.method===`tempo`&&e.intent===`session`&&e.status===`success`&&typeof e.timestamp==`string`&&typeof e.reference==`string`&&typeof e.challengeId==`string`&&typeof e.channelId==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.spent==`string`&&(e.units===void 0||typeof e.units==`number`)&&(e.txHash===void 0||typeof e.txHash==`string`):!1}function as(e){let t=D.toString(e),n=JSON.parse(t);if(!is(n))throw Error(`Invalid session receipt.`);return n}function os(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function ss(e){let t=`message`,n=[];for(let r of e.split(`
4
8
  `))r.startsWith(`event: `)?t=r.slice(7).trim():r.startsWith(`data: `)?n.push(r.slice(6)):r===`data:`&&n.push(``);if(n.length===0)return null;let r=n.join(`
5
- `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=Bo(r);return Fo(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=Bo(r);return Io(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function Bo(e){try{return JSON.parse(e)}catch{return null}}function Vo(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function Ho(){return JSON.stringify({mpp:`payment-close-request`})}function Uo(e){let t=Wo(e);return t?t.mpp===`authorization`&&typeof t.authorization==`string`?{mpp:`authorization`,authorization:t.authorization}:t.mpp===`message`&&typeof t.data==`string`?{mpp:`message`,data:t.data}:t.mpp===`payment-close-request`?{mpp:`payment-close-request`}:t.mpp===`payment-close-ready`&&Io(t.data)?{mpp:`payment-close-ready`,data:t.data}:t.mpp===`payment-error`&&typeof t.status==`number`&&typeof t.message==`string`?{mpp:`payment-error`,status:t.status,message:t.message}:t.mpp===`payment-need-voucher`&&Fo(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&Io(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function Wo(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}const Go=`0x4d50500000000000000000000000000000000000`;function Ko(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function qo(e){let t=S.encode(S.from([`address payer`,`address payee`,`address operator`,`address token`,`bytes32 salt`,`address authorizedSigner`,`bytes32 expiringNonceHash`,`address escrow`,`uint256 chainId`]),[e.payer,e.payee,e.operator,e.token,e.salt,e.authorizedSigner,e.expiringNonceHash,e.escrow??`0x4d50500000000000000000000000000000000000`,BigInt(e.chainId)]);return T.keccak256(t)}function Jo(e){return fe.encodeForSigning(e)}function Yo(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function Xo(e,t){return T.keccak256(E.concat(Jo(e),t.sender))}const Zo=[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],Qo=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],$o={name:`descriptor`,type:`tuple`,components:Zo},es=[{type:`function`,name:`CLOSE_GRACE_PERIOD`,stateMutability:`view`,inputs:[],outputs:[{type:`uint64`}]},{type:`function`,name:`VOUCHER_TYPEHASH`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`function`,name:`open`,stateMutability:`nonpayable`,inputs:[{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`deposit`,type:`uint96`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`}],outputs:[{name:`channelId`,type:`bytes32`}]},{type:`function`,name:`settle`,stateMutability:`nonpayable`,inputs:[$o,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[$o,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[$o,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[$o],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[$o],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[$o],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:Zo},{name:`state`,type:`tuple`,components:Qo}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:Qo}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:Qo}]},{type:`function`,name:`computeChannelId`,stateMutability:`view`,inputs:[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`getVoucherDigest`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`domainSeparator`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`event`,name:`ChannelOpened`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`authorizedSigner`,type:`address`},{name:`salt`,type:`bytes32`},{name:`expiringNonceHash`,type:`bytes32`},{name:`deposit`,type:`uint96`}]},{type:`event`,name:`Settled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`cumulativeAmount`,type:`uint96`},{name:`deltaPaid`,type:`uint96`},{name:`newSettled`,type:`uint96`}]},{type:`event`,name:`TopUp`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`additionalDeposit`,type:`uint96`},{name:`newDeposit`,type:`uint96`}]},{type:`event`,name:`CloseRequested`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`closeGraceEnd`,type:`uint256`}]},{type:`event`,name:`ChannelClosed`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`settledToPayee`,type:`uint96`},{name:`refundedToPayer`,type:`uint96`}]},{type:`event`,name:`CloseRequestCancelled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0}]}];function ts(e,t){return{name:`TIP20 Channel Reserve`,version:`1`,chainId:t,verifyingContract:e}}const ns={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},rs={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]};function is(e,t,n){return o({domain:ts(e,t),types:rs,primaryType:`CloseAuthorization`,message:n})}function as(e,t){return ue.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function os(e,t,n){return e.toLowerCase()===ue.address.toLowerCase()?as(t,n):o({domain:ts(e,t),types:ns,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function ss(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function cs(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function ls(e,t){return re.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function us(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===ue.address.toLowerCase())try{return await ls(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return y(e,{account:t,domain:ts(r,i),types:ns,primaryType:`Voucher`,message:n})})(),o=z.from(a);if(!ss(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return z.serialize(o)}async function ds(e,t,n,r,i){let a=cs(t)?await t.sign({hash:is(r,i,n),raw:!0}):await y(e,{account:t,domain:ts(r,i),types:rs,primaryType:`CloseAuthorization`,message:n}),o=z.from(a);if(!ss(o.type))throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive signature; received "${o.type}".`);return z.serialize(o)}function fs(e,t,n,r){try{let i=z.from(n.signature);if(!ss(i.type)||z.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=os(e,t,n),o=z.extractAddress({payload:a,signature:i});return z.verify(i,{address:o,payload:a})&&Fa(o,r)}catch{return!1}}function ps(e){return typeof e==`object`&&!!e}function ms(e){return typeof e==`string`&&c(e,{strict:!1})?e:void 0}function hs(e){return ms(e.accessKeyAddress)}function gs(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(E.random(8))%e)}function _s(e){return hs(e)??e.address}async function vs(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return m(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}})}async function ys(e,t){return await v(e,t)}function bs(e,t,n=!1){let r=e.request.methodDetails,i=ps(r)?ms(r.escrowContract)??ms(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!Ss(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!Ss(i,a)?i:a}function xs(e,t,n,r){return Tt({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function Ss(e,t){return e.toLowerCase()===t.toLowerCase()}async function Cs(e,t,n,r,i,a=Go){let o=qo({...n,chainId:i,escrow:a}),s=Do(r),c=await us(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function ws(e,t,n,r,i,a=Go){let o=await Cs(e,t,n,r,i,a),s=await ds(e,t,{channelId:o.channelId,cumulativeAmount:Do(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function Ts(e,t,n){let i=_s(t),a=n.escrow??`0x4d50500000000000000000000000000000000000`,o=n.operator??`0x0000000000000000000000000000000000000000`,s=E.random(32),c=Do(n.deposit),l=Do(n.initialAmount),u=r({abi:es,functionName:`open`,args:[n.payee,o,n.token,c,s,i]}),d=await ys(e,await vs(e,{account:t,calls:[...n.prefixCalls??[],{to:a,data:u}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),f=oe.deserialize(d),p={authorizedSigner:i,expiringNonceHash:Xo(Yo({...n.feePayer?{feePayer:!0}:{},transaction:f}),{sender:t.address}),operator:o,payee:n.payee,payer:t.address,salt:s,token:n.token},m=qo({...p,chainId:n.chainId,escrow:a});return{action:`open`,type:`transaction`,channelId:m,transaction:d,signature:await us(e,t,{channelId:m,cumulativeAmount:l},a,n.chainId),descriptor:p,cumulativeAmount:l.toString(),authorizedSigner:p.authorizedSigner}}async function Es(e,t,n,i,a,o,s=Go,c=[],l=n.token){let u=qo({...n,chainId:a,escrow:s}),d=Do(i);return{action:`topUp`,type:`transaction`,channelId:u,transaction:await ys(e,await vs(e,{account:t,calls:[...c,{to:s,data:r({abi:es,functionName:`topUp`,args:[n,d]})}],feePayer:o,feeToken:l,validAfter:gs()})),descriptor:n,additionalDeposit:d.toString()}}function Ds(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Q(e){return Ds({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function Os(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Q(t),t)},delete(t){e.delete(t)}}}const ks=new WeakMap,As=new WeakMap;function js(e,t){As.set(e,As.get(t)??t)}async function Ms(e,t,n){let r=ks.get(e);r||(r=new Map,ks.set(e,r));let i=(r.get(t)??Promise.resolve()).catch(()=>{}).then(n);r.set(t,i);try{return await i}finally{r.get(t)===i&&r.delete(t)}}function Ns(e,t,n){return Ms(As.get(e)??e,`funding:${t}`,n)}async function Ps(e,t){await Ms(e,`write:${Q(t)}`,async()=>{let n=await e.get(Q(t));if(n?.origin!==void 0){if(t.origin!==void 0&&t.origin!==n.origin)throw Error(`SessionManager: stored channel origin mismatch`);t.origin=n.origin}if(n?.uncertainTopUp){if(n.channelId!==t.channelId)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);t.uncertainTopUp=!0}await e.set(t)})}async function Fs(e,t){await Ms(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}const Is=2n**96n-1n;function Ls(e){if(e<0n||e>Is)throw new Y({reason:`amount exceeds uint96 range`})}async function Rs(e,t,n=Go,r){return zs(await h(e,{address:n,abi:es,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function zs(e){return Ls(e.settled),Ls(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}const Bs=U.custom(e=>typeof e==`string`&&c(e,{strict:!1})),Vs=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),Hs=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),Us=U.object({authorizedSigner:Bs,expiringNonceHash:Vs,operator:Bs,payee:Bs,payer:Bs,salt:Vs,token:Bs}),Ws=Pt(U.object({acceptedCumulative:U.string(),chainId:U.number(),channelId:Vs,closeRequestedAt:U.optional(U.string()),deposit:U.string(),descriptor:Us,escrow:Bs,highestVoucher:U.optional(U.object({channelId:Vs,cumulativeAmount:U.string(),signature:Hs})),requiredCumulative:U.string(),settled:U.string(),spent:U.string(),units:U.optional(U.number())}));function Gs(e){return Ws.encode(e)}function Ks(e){return Ws.decode(e)}const qs={status:`idle`};function Js(e){return{status:`active`,...e}}function Ys(e,t){switch(t.type){case`challengeReceived`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:{status:`challenged`,challengeId:t.challengeId},effects:[]};case`challenge`:return e.status!==`idle`&&e.status!==`active`?$(e,t):t.snapshot?{state:{status:`hydrating`,challengeId:t.challengeId,snapshot:t.snapshot},effects:[{type:`hydrate`,snapshot:t.snapshot}]}:{state:{status:`opening`,challengeId:t.challengeId},effects:[{type:`open`}]};case`hydrated`:return e.status===`hydrating`?{state:Qs(e.challengeId,t.snapshot),effects:[]}:$(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:dc({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:$s(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:$(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:mc(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?Zs({challengeId:e.challengeId,descriptor:t.descriptor,event:t.event}):$(e,t);case`topUpStarted`:return e.status===`voucherNeeded`?{state:{status:`toppingUp`,challengeId:e.challengeId,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[]}:$(e,t);case`voucherAccepted`:return e.status!==`voucherNeeded`&&e.status!==`toppingUp`?$(e,t):{state:$s(e.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]};case`settleStarted`:return e.status===`active`?{state:{status:`settling`,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[{type:`settle`,channelId:e.channelId}]}:$(e,t);case`settled`:return e.status===`settling`?{state:$s(t.receipt.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]}:$(e,t);case`closeRequested`:return e.status===`active`?{state:{status:`closeRequested`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`requestClose`,channelId:e.channelId}]}:$(e,t);case`withdrawable`:return e.status===`closeRequested`?{state:{status:`withdrawable`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`withdraw`,channelId:e.channelId}]}:$(e,t);case`closeStarted`:return e.status!==`active`&&e.status!==`withdrawable`&&e.status!==`closeRequested`?$(e,t):{state:{status:`closing`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`close`,channelId:e.channelId}]};case`closed`:return e.status!==`closing`&&e.status!==`withdrawable`?$(e,t):{state:{status:`closed`,channelId:e.channelId,descriptor:e.descriptor},effects:[]}}}function Xs(e,t){let n=Ys(e.state,t);return e.state=n.state,n}function Zs(e){let{challengeId:t,descriptor:n,event:r}=e,i=BigInt(r.requiredCumulative),a=BigInt(r.deposit);return i>a?{state:{status:`toppingUp`,challengeId:t,channelId:r.channelId,descriptor:n,deposit:r.deposit},effects:[{type:`topUp`,channelId:r.channelId,amount:(i-a).toString()}]}:{state:{status:`voucherNeeded`,challengeId:t,channelId:r.channelId,descriptor:n,requiredCumulative:r.requiredCumulative,deposit:r.deposit},effects:[{type:`voucher`}]}}function Qs(e,t){return Js({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function $s(e,t,n,r){return Js({challengeId:e,channelId:t.channelId,descriptor:n,acceptedCumulative:t.acceptedCumulative,deposit:r,spent:t.spent,units:t.units??0})}function $(e,t){throw Error(`Invalid session transition: ${e.status} + ${t.type}`)}function ec(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function tc(e){let{channel:t,maxVoucherCumulative:n,receipt:r}=e;if(!t||r.channelId!==t.channelId)return;let i=BigInt(r.acceptedCumulative),a=BigInt(r.spent);if(a>i)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(i>t.cumulativeAmount)throw Error(`receipt accepted cumulative exceeds local voucher state`);if(a>t.cumulativeAmount)throw Error(`receipt spent exceeds local voucher state`);ec({cumulativeAmount:i,maxVoucherCumulative:n}),ec({cumulativeAmount:a,maxVoucherCumulative:n})}function nc(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;tc({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function rc(e,t){return typeof e==`bigint`?e:f(e,t)}function ic(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(oc(r,n),t!==void 0){let e=BigInt(t);if(e<r)throw Error(`opening deposit ${e} below request amount ${r}`);return e}let a=i===void 0?void 0:BigInt(i),o=a!==void 0&&a>r?a:r;return n===void 0||o<n?o:n}function ac(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;ec({cumulativeAmount:r,maxVoucherCumulative:n??null});let o=r-t,s=a??i??o,c=s>o?s:o;if(n==null)return c;let l=n-t;return c<l?c:l}function oc(e,t){ec({cumulativeAmount:e,maxVoucherCumulative:t??null})}function sc(e){let{channel:t,currentSocket:n,lastChallenge:r}=e;if(!t?.opened)return;let i=n?.challenge??r,a=n?.channelId??t.channelId;if(!i)throw Error(`Cannot close session: no challenge available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or make a request first to receive a fresh 402 challenge.`);if(!a)throw Error(`Cannot close session: no channel ID available. The session may not have been fully opened.`);return{challenge:i,channel:t,channelId:a}}function cc(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function lc(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!To(n))throw Error(`close-ready spent is not a uint96 amount`);if(n<r)throw Error(`close-ready spent is below locally confirmed spend`);if(n>cc({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function uc(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=Eo(r),s=Eo(a.spent);return o===void 0||s===void 0||!To(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function dc(e){return Js({challengeId:e.challengeId,channelId:e.entry.channelId,descriptor:e.entry.descriptor,acceptedCumulative:e.entry.cumulativeAmount.toString(),deposit:e.entry.deposit.toString(),spent:e.spent,units:e.units})}function fc(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:qs}}function pc(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=nc({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&Xs(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function mc(e,t){return Js({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function hc(e){let{challengeId:t,channelId:n,closeReadyReceipt:r,cumulativeAmount:i,deliveredChunks:a=0n,socketChallengeId:o,socketChannelId:s,spent:c,tickCost:l=0n}=e;if(c>i)throw Error(`locally confirmed spend exceeds local voucher state`);if(r&&r.challengeId===t&&r.channelId===n){let e=Eo(r.spent);if(e===void 0)throw Error(`close-ready spent is not a uint96 amount`);return e>c?e:c}if(o===t&&s===n&&l>0n){let e=a*l,t=c>e?c:e;return t>i?i:t}return i}function gc(e){let{channel:t,channelId:n,challengeId:r,cumulativeAmount:i,spent:a,state:o}=e;if(!(!t||t.channelId!==n)&&(t.cumulativeAmount=i,r))return Ys(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function _c(e){return{channel:e.channel===null?null:{entry:e.channel,cumulativeAmount:e.channel.cumulativeAmount,deposit:e.channel.deposit,opened:e.channel.opened},spent:e.spent,state:e.state}}function vc(e,t){return e.channel?(e.channel.entry.cumulativeAmount=e.channel.cumulativeAmount,e.channel.entry.deposit=e.channel.deposit,e.channel.entry.opened=e.channel.opened,{channel:e.channel.entry,spent:e.spent,state:e.state}):(t&&(t.opened=!1),{channel:null,spent:e.spent,state:e.state})}async function yc(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(Ho()),e.waitForCloseReady()))(),a=BigInt(i.spent);lc({cumulativeAmount:r.channel.cumulativeAmount,readySpent:a,spent:e.spent});let o=await e.createSessionCredential(r.challenge,{action:`close`,channelId:r.channelId,descriptor:r.channel.descriptor,cumulativeAmountRaw:a.toString()}),s=a.toString();n.expectedCloseAmount=s;try{let i=e.waitForReceipt(e=>uc({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(Vo(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}function bc(e){return`cumulativeAmount`in e}function xc(e){if(bc(e))return BigInt(e.cumulativeAmount)}async function Sc(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await Ps(e.store,t):await Fs(e.store,Q(t)),e.notifyUpdate(t)}async function Cc(e,t,n){let r=xc(n);if(r===void 0)return;let i=await e.store.get(t);i&&i.channelId.toLowerCase()===n.channelId.toLowerCase()&&(i.cumulativeAmount=i.cumulativeAmount>r?i.cumulativeAmount:r,n.action===`close`&&(i.opened=!1),await Sc(e,i))}const wc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),Tc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),Ec=U.object({account:U.optional(U.custom()),autoSwap:U.optional(U.custom()),action:U.optional(U.enum([`open`,`topUp`,`voucher`,`close`])),channelId:U.optional(Tc),cumulativeAmount:U.optional(W()),cumulativeAmountRaw:U.optional(U.string()),transaction:U.optional(wc),descriptor:U.optional(U.custom()),additionalDeposit:U.optional(W()),additionalDepositRaw:U.optional(U.string()),depositRaw:U.optional(U.string())});function Dc(e){return e?.action!==void 0}function Oc(e){return Dc(e)&&e.descriptor!==void 0}function kc(e,t,n){let r=n===`additionalDeposit`?e.additionalDepositRaw:e.cumulativeAmountRaw,i=n===`additionalDeposit`?e.additionalDeposit:e.cumulativeAmount;if(r)return BigInt(r);if(i)return f(i,t)}function Ac(e,t,n,r){let i=kc(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function jc(e){return typeof e==`object`&&!!e}function Mc(e){return typeof e==`string`&&c(e,{strict:!1})?e:void 0}function Nc(e){let t=e.request.methodDetails;return jc(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:Mc(t.escrowContract),escrow:Mc(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:Mc(t.feeToken),operator:Mc(t.operator),sessionSnapshot:Ge(t,Ue.sessionSnapshot)}:{}}function Pc(e,t){if(typeof e==`string`&&c(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function Fc(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function Ic(e){return typeof e==`string`?e:void 0}async function Lc(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=Nc(n);(o.chainId!==void 0||i?.length===0)&&Aa(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});ka(c,s);let l=s??c.chain?.id;if(Aa(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=bs(n,r,t),d=Pc(n.request.recipient,`recipient`),f=Pc(n.request.currency,`currency`);return{amount:Fc(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:Ds({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:Ic(n.request.suggestedDeposit),token:f}}async function Rc(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=Rs}=e,o=qo({...r,chainId:i.chainId,escrow:i.escrow});zc({channelId:t,descriptor:r,expectedChannelId:o,payee:i.payee,payer:i.payer,authorizedSigner:i.authorizedSigner,token:i.token});let s=await a(n,o,i.escrow);if(s.deposit===0n)throw Error(`Channel ${o} cannot be reused (closed or not found on-chain).`);if(s.closeRequestedAt!==0)throw Error(`Channel ${o} cannot be reused (pending close request).`);return{channelId:o,state:s}}function zc(e){let{authorizedSigner:t,channelId:n,descriptor:r,expectedChannelId:i,payee:a,payer:o,token:s}=e;if(n&&n.toLowerCase()!==i.toLowerCase())throw Error(`context channelId does not match descriptor`);if(!Ss(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!Ss(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!Ss(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!Ss(Ko(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function Bc(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function Vc(e){let{context:t,decimals:n,requestAmount:r,snapshot:i,settled:a}=e;if(i)return[BigInt(i.acceptedCumulative),BigInt(i.requiredCumulative),BigInt(i.spent)+r,a].reduce((e,t)=>t>e?t:e,0n);let o=kc(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function Hc(e){let{account:t,client:n,readChannelState:r,snapshot:i}=e,a=i.highestVoucher;if(!a)throw Error(`session snapshot is missing its highest signed voucher`);if(a.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let o=BigInt(i.acceptedCumulative),s=BigInt(a.cumulativeAmount),c=BigInt(i.requiredCumulative),l=BigInt(i.deposit),u=BigInt(i.settled),d=BigInt(i.spent);if(s!==o)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(d>o)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(u>l)throw Error(`session snapshot settled amount exceeds deposit`);if(!fs(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},Ko(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await Rc({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:_s(t),token:i.descriptor.token},readChannelState:r}),p=[o,c,f.state.settled].reduce((e,t)=>t>e?t:e,0n);if(p>f.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:f.channelId,cumulativeAmount:p,deposit:f.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:d}}function Uc(e,t){return Ss(e.address,t.payer)?Ss(_s(e),Ko(t)):!1}function Wc(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(Dc(r)){if(!Oc(r))throw Error(`descriptor required for TIP-1034 session action`);return{type:`manual`,account:t,context:r,decimals:i,resolved:o}}if(!n&&r?.channelId&&!r.descriptor)throw Error(`descriptor required to reuse TIP-1034 channel`);let s=Bc({context:r,snapshot:o.snapshot});return!n&&s&&Uc(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&Uc(t,n.descriptor)?{type:`voucher`,account:t,entry:n,maxDeposit:a,resolved:o}:{type:`open`,account:t,context:r,maxDeposit:a,resolved:o}}async function Gc(e,t,n=!1){switch(e.type){case`open`:return qc(e,t,n);case`recover`:return Jc(e,t);case`voucher`:return Yc(e,t);case`manual`:return Xc(e,t,n)}}async function Kc(e,t){if(e)return await Ra(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function qc(e,t,n){let{account:r,resolved:i}=e,a=ic({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw}),o=await Ts(i.client,r,{chainId:i.chainId,deposit:a,escrow:i.escrow,feePayer:i.feePayer,feeToken:i.feeToken,initialAmount:i.amount,operator:i.operator,payee:i.payee,prefixCalls:await Kc(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await Sc(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function Jc(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await Rc({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:_s(n),token:o.token}}),l=Vc({context:r,decimals:i,requestAmount:o.amount,settled:c.state.settled,snapshot:o.snapshot});if(l>c.state.deposit)throw Error(`recovered voucher amount exceeds on-chain channel deposit`);oc(l,a);let u=await Cs(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await Sc(t,{...d?.channelId===c.channelId&&d.uncertainTopUp?{uncertainTopUp:!0}:{},channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function Yc(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;oc(a,e.maxDeposit);let o=await Cs(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await Sc(t,r),o}async function Xc(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=qo({...s,chainId:o.chainId,escrow:o.escrow});zc({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:_s(r),token:o.token});let l=await Zc({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await Cc(t,o.key,l),l}async function Zc(e,t){switch(e.context.action){case`open`:return Qc(e);case`topUp`:return $c(e,t);case`voucher`:return el(e);case`close`:return tl(e)}}async function Qc(e){let{account:t,channelId:n,context:r,decimals:i,descriptor:a,resolved:o}=e;if(!r.transaction)throw Error(`transaction required for open action`);let s=Ac(r,i,`cumulativeAmount`,`open`),c=await Cs(o.client,t,a,s,o.chainId,o.escrow);return{action:`open`,type:`transaction`,channelId:n,transaction:r.transaction,signature:c.signature,descriptor:a,cumulativeAmount:s.toString(),authorizedSigner:a.authorizedSigner}}async function $c(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=Ac(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:Es(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await Kc(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken)}function el(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Cs(a.client,t,i,Ac(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function tl(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return ws(a.client,t,i,Ac(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}const nl={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function rl(e){let t=new Map,n=!1,r=[],i=e.readyState,a=(e,n,i)=>{let a=t.get(e);if(a||(a=new Set,t.set(e,a)),a.add({once:typeof i==`object`&&i.once===!0,value:n}),e===`message`&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},o=(e,n)=>{let r=t.get(e);if(r)for(let e of r)e.value===n&&r.delete(e)};function s(e,a){if(a.type===`close`){if(n)return;n=!0,i=nl.CLOSED,r=null}if(a.type===`open`&&(i=nl.OPEN),a.type===`message`&&r){r.push(a);return}switch(a.type){case`close`:l.onclose?.(a);break;case`error`:l.onerror?.(a);break;case`message`:l.onmessage?.(a);break;case`open`:l.onopen?.(a)}let o=t.get(e);if(o)for(let e of Array.from(o))typeof e.value==`function`?e.value(a):e.value.handleEvent(a),e.once&&o.delete(e)}let c=null,l={addEventListener:a,close(t,n){e.close(t,n)},get bufferedAmount(){return e.bufferedAmount},get extensions(){return e.extensions},on(e,t){a(e,t)},onclose:null,onerror:null,get onmessage(){return c},set onmessage(e){if(c=e,e&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},onopen:null,off(e,t){o(e,t)},get protocol(){return e.protocol},get readyState(){return i},removeEventListener:o,send(t){e.send(t)},get url(){return e.url}};return{emit:s,socket:l}}function il(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function al(e){let{amount:t,assertVoucherWithinLocalLimit:n,channel:r,decimals:i,lastChallenge:a,lastUrl:o}=e;if(!r?.opened)throw Error(`Cannot top up session: no open channel.`);if(!a)throw Error(`Cannot top up session: no challenge available. Make a request first.`);if(!o)throw Error(`Cannot top up session: no URL available. Call fetch(), sse(), or ws() first.`);let s=rc(t,i);if(s<=0n)throw Error(`Top-up amount must be greater than zero.`);return n(r.cumulativeAmount+s),{additionalDeposit:s,challenge:a,channelId:r.channelId,input:o}}function ol(e){let{additionalDeposit:t,channel:n,channelId:r,challengeId:i,currentState:a,knownDeposit:o,receipt:s,spent:c}=e;if(n?.channelId!==r)return;let l=o!==void 0&&o>n.deposit?o:n.deposit,u={...n,deposit:l+t};return s?{channel:u,state:mc(s,u)}:i?{channel:u,state:dc({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function sl(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=il(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,headers:e.headers,channelId:e.expectedChannelId,deposit:t.deposit,requiredCumulative:t.requiredCumulative,...e.signal?{signal:e.signal}:{}});let n=e.getChannel();if(!n||n.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`missing-channel`};let r=n.cumulativeAmount>t.requiredCumulative?n.cumulativeAmount:Do(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function cl(e){return e.method===Ve.tempo&&e.intent===He.session}function ll(e){return cl(e)&&Ge(e.request.methodDetails,Ue.sessionProtocol)===We.v2}function ul(e){return Ge(e.request.methodDetails,Ue.sessionSnapshot)}function dl(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return Yr({...t,redirect:`manual`,headers:{...Hi(i),...Hi(t?.headers)}},ht(r),n)}function fl(e){return e instanceof Request||typeof e==`object`&&!!e&&!(e instanceof URL)&&typeof e.url==`string`&&typeof e.method==`string`&&typeof e.clone==`function`}function pl(e){try{let t=typeof location>`u`?void 0:location.href,n=fl(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function ml(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function hl(e){let t=await e.text().catch(()=>``);if(!t)return``;if(!e.headers.get(`Content-Type`)?.includes(`application/problem+json`))return t;try{return JSON.parse(t).detail??t}catch{return t}}var gl=class extends Error{constructor(e){let t=e instanceof Error||e instanceof DOMException?e.message:String(e);super(`${t}; payment outcome unknown`),this.name=`UncertainFundingError`}};async function _l(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);if(t.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let r=await vl({challenge:e.challenge,context:{action:`topUp`,...e.autoSwap===void 0?{}:{autoSwap:e.autoSwap},channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,headers:e.headers,input:e.input,signal:e.signal}).catch(async n=>{throw n instanceof gl&&(t.uncertainTopUp=!0,await e.onUncertainFunding?.(t)),n});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(B.paymentReceipt);return i?Lo(i):void 0}async function vl(e){let t=async t=>{e.signal?.throwIfAborted();let n=await e.createSessionCredential(t,e.context);e.signal?.throwIfAborted();let r=new AbortController,i=()=>r.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,i,{once:!0});let a=setTimeout(()=>r.abort(new DOMException(`Session management request timed out; payment outcome unknown`,`TimeoutError`)),3e4),o,s=new Promise((e,t)=>{o=()=>t(r.signal.reason),r.signal.addEventListener(`abort`,o,{once:!0})});try{return await Promise.race([e.fetch(pl(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:Hl(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new gl(t):t}finally{clearTimeout(a),e.signal?.removeEventListener(`abort`,i),r.signal.removeEventListener(`abort`,o)}},n=await t(e.challenge);if(n.status!==402)return n;let r=dt(n).find(ll);return r?t(r):n}async function yl(e){let t=bl({channel:e.getChannel(),response:e.response});if(!t)return;let{channel:n,challenge:r,snapshot:i}=t;e.setChallenge(r);let a=BigInt(i.requiredCumulative),o=n.cumulativeAmount;await e.topUpIfNeeded({challenge:r,input:e.input,headers:e.init?.headers,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a,signal:e.init?.signal??(e.input instanceof Request?e.input.signal:void 0)});let s=e.getChannel();if(!s?.descriptor||s.channelId!==i.channelId)return;let c=s.cumulativeAmount>a?s.cumulativeAmount:a,l=()=>e.restoreCumulative(i.channelId,o),u;try{let t=await e.createSessionCredential(r,{action:`voucher`,channelId:i.channelId,descriptor:s.descriptor,cumulativeAmountRaw:c.toString()});u=await e.fetch(e.input,dl(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(B.paymentReceipt)&&await l(),u}function bl(e){let t=dt(e.response).find(ll);if(!t)return;let n=ul(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function xl(e){if(!e.lastUrl)throw Error(`Cannot close session: no URL available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or call fetch()/sse() before close().`);let t=e.target.challenge,n=e.signedCloseAmount,r=fl(e.lastUrl)?e.lastUrl:void 0,i=r?{cache:r.cache,credentials:r.credentials,integrity:r.integrity,keepalive:r.keepalive,mode:r.mode===`navigate`?`same-origin`:r.mode,referrer:r.referrer,referrerPolicy:r.referrerPolicy}:void 0,a=async(a,o=!1)=>{t=a,n=(o?e.resolveSignedCloseAmount?.(a):void 0)??e.signedCloseAmount;let s=await e.createSessionCredential(a,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(r?pl(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:Hl(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=dt(o).find(ll);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await hl(o),t=o.headers.get(B.wwwAuthenticate)??``;throw Error(`Close request failed with status ${o.status}${e?`: ${e}`:``}${t?` [${B.wwwAuthenticate}: ${t}]`:``}`)}let s=o.headers.get(B.paymentReceipt);if(!s)return;let c=Lo(s);if(!c.txHash||!E.validate(c.txHash,{strict:!0})||E.size(c.txHash)!==32||!uc({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:0n,receipt:c}))throw Error(`Session close response included a mismatched payment receipt.`);return c}async function Sl(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...Hi(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!Ro(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),Cl(e,c,{onReceipt:r,signal:o},n,s.headers)}function Cl(e,t,n,r,i){if(!Ro(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return wl({onNeedVoucher:t=>kl({challenge:a,driver:r,headers:i,input:e,signal:n?.signal},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*wl(e){for await(let t of Tl(e))t.data!==void 0&&(yield t.data)}async function*Tl(e){if(!e.response.body)throw Error(`Response has no body.`);let t=e.response.body.getReader(),n=new TextDecoder,r=``,i=!1,a=()=>{t.cancel(e.signal?.reason).catch(()=>void 0)};e.signal?.addEventListener(`abort`,a,{once:!0}),e.signal?.aborted&&a();try{for(;!e.signal?.aborted;){let{done:a,value:o}=await t.read();for(a?(i=!0,r+=n.decode()):r+=n.decode(o,{stream:!0});;){let t=El(r,a);if(!t)break;let n=t.index+t.length,i=r.slice(0,t.index),o=r.slice(0,n);if(r=r.slice(n),!i.trim())continue;let s=zo(i.replace(/\r\n|\r/g,`
6
- `));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,e.signal);break;case`payment-receipt`:e.onReceipt(s.data)}}if(a)break}}finally{e.signal?.removeEventListener(`abort`,a),i||await t.cancel().catch(()=>void 0),t.releaseLock()}}function El(e,t){for(let n=0;n<e.length;n++){let r=Dl(e,n,t);if(!r)continue;let i=Dl(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function Dl(e,t,n){return e[t]===`
9
+ `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=cs(r);return rs(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=cs(r);return is(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function cs(e){try{return JSON.parse(e)}catch{return null}}function ls(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function us(){return JSON.stringify({mpp:`payment-close-request`})}function ds(e){let t=fs(e);return t?t.mpp===`authorization`&&typeof t.authorization==`string`?{mpp:`authorization`,authorization:t.authorization}:t.mpp===`message`&&typeof t.data==`string`?{mpp:`message`,data:t.data}:t.mpp===`payment-close-request`?{mpp:`payment-close-request`}:t.mpp===`payment-close-ready`&&is(t.data)?{mpp:`payment-close-ready`,data:t.data}:t.mpp===`payment-error`&&typeof t.status==`number`&&typeof t.message==`string`?{mpp:`payment-error`,status:t.status,message:t.message}:t.mpp===`payment-need-voucher`&&rs(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&is(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function fs(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}const ps=`0x4d50500000000000000000000000000000000000`;function ms(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function hs(e){let t=E.encode(E.from([`address payer`,`address payee`,`address operator`,`address token`,`bytes32 salt`,`address authorizedSigner`,`bytes32 expiringNonceHash`,`address escrow`,`uint256 chainId`]),[e.payer,e.payee,e.operator,e.token,e.salt,e.authorizedSigner,e.expiringNonceHash,e.escrow??`0x4d50500000000000000000000000000000000000`,BigInt(e.chainId)]);return k.keccak256(t)}function gs(e){return _e.encodeForSigning(e)}function _s(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function vs(e,t){return k.keccak256(A.concat(gs(e),t.sender))}const ys=[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],bs=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],xs={name:`descriptor`,type:`tuple`,components:ys},Ss=[{type:`function`,name:`CLOSE_GRACE_PERIOD`,stateMutability:`view`,inputs:[],outputs:[{type:`uint64`}]},{type:`function`,name:`VOUCHER_TYPEHASH`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`function`,name:`open`,stateMutability:`nonpayable`,inputs:[{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`deposit`,type:`uint96`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`}],outputs:[{name:`channelId`,type:`bytes32`}]},{type:`function`,name:`settle`,stateMutability:`nonpayable`,inputs:[xs,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[xs,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[xs,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[xs],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[xs],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[xs],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:ys},{name:`state`,type:`tuple`,components:bs}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:bs}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:bs}]},{type:`function`,name:`computeChannelId`,stateMutability:`view`,inputs:[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`getVoucherDigest`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`domainSeparator`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`event`,name:`ChannelOpened`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`authorizedSigner`,type:`address`},{name:`salt`,type:`bytes32`},{name:`expiringNonceHash`,type:`bytes32`},{name:`deposit`,type:`uint96`}]},{type:`event`,name:`Settled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`cumulativeAmount`,type:`uint96`},{name:`deltaPaid`,type:`uint96`},{name:`newSettled`,type:`uint96`}]},{type:`event`,name:`TopUp`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`additionalDeposit`,type:`uint96`},{name:`newDeposit`,type:`uint96`}]},{type:`event`,name:`CloseRequested`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`closeGraceEnd`,type:`uint256`}]},{type:`event`,name:`ChannelClosed`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`settledToPayee`,type:`uint96`},{name:`refundedToPayer`,type:`uint96`}]},{type:`event`,name:`CloseRequestCancelled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0}]}];function Cs(e,t){return{name:`TIP20 Channel Reserve`,version:`1`,chainId:t,verifyingContract:e}}const ws={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},Ts={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]};function Es(e,t,n){return s({domain:Cs(e,t),types:Ts,primaryType:`CloseAuthorization`,message:n})}function Ds(e,t){return me.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function Os(e,t,n){return e.toLowerCase()===me.address.toLowerCase()?Ds(t,n):s({domain:Cs(e,t),types:ws,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function ks(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function As(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function js(e,t){return se.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function Ms(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===me.address.toLowerCase())try{return await js(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return w(e,{account:t,domain:Cs(r,i),types:ws,primaryType:`Voucher`,message:n})})(),o=B.from(a);if(!ks(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return B.serialize(o)}async function Ns(e,t,n,r,i){let a=As(t)?await t.sign({hash:Es(r,i,n),raw:!0}):await w(e,{account:t,domain:Cs(r,i),types:Ts,primaryType:`CloseAuthorization`,message:n}),o=B.from(a);if(!ks(o.type))throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive signature; received "${o.type}".`);return B.serialize(o)}function Ps(e,t,n,r){try{let i=B.from(n.signature);if(!ks(i.type)||B.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=Os(e,t,n),o=B.extractAddress({payload:a,signature:i});return B.verify(i,{address:o,payload:a})&&Ha(o,r)}catch{return!1}}function Fs(e){return typeof e==`object`&&!!e}function Is(e){return typeof e==`string`&&l(e,{strict:!1})?e:void 0}function Ls(e){return Is(e.accessKeyAddress)}function Rs(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(A.random(8))%e)}function zs(e){return Ls(e)??e.address}async function Bs(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return v(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}})}async function Vs(e,t){return await C(e,t)}function Hs(e,t,n=!1){let r=e.request.methodDetails,i=Fs(r)?Is(r.escrowContract)??Is(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!Ws(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!Ws(i,a)?i:a}function Us(e,t,n,r){return jt({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function Ws(e,t){return e.toLowerCase()===t.toLowerCase()}async function Gs(e,t,n,r,i,a=ps){let o=hs({...n,chainId:i,escrow:a}),s=Yo(r),c=await Ms(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function Ks(e,t,n,r,i,a=ps){let o=await Gs(e,t,n,r,i,a),s=await Ns(e,t,{channelId:o.channelId,cumulativeAmount:Yo(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function qs(e,t,n){let i=zs(t),a=n.escrow??`0x4d50500000000000000000000000000000000000`,o=n.operator??`0x0000000000000000000000000000000000000000`,s=A.random(32),c=Yo(n.deposit),l=Yo(n.initialAmount),u=r({abi:Ss,functionName:`open`,args:[n.payee,o,n.token,c,s,i]}),d=await Vs(e,await Bs(e,{account:t,calls:[...n.prefixCalls??[],{to:a,data:u}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),f=ue.deserialize(d),p={authorizedSigner:i,expiringNonceHash:vs(_s({...n.feePayer?{feePayer:!0}:{},transaction:f}),{sender:t.address}),operator:o,payee:n.payee,payer:t.address,salt:s,token:n.token},m=hs({...p,chainId:n.chainId,escrow:a});return{action:`open`,type:`transaction`,channelId:m,transaction:d,signature:await Ms(e,t,{channelId:m,cumulativeAmount:l},a,n.chainId),descriptor:p,cumulativeAmount:l.toString(),authorizedSigner:p.authorizedSigner}}async function Js(e,t,n,i,a,o,s=ps,c=[],l=n.token){let u=hs({...n,chainId:a,escrow:s}),d=Yo(i);return{action:`topUp`,type:`transaction`,channelId:u,transaction:await Vs(e,await Bs(e,{account:t,calls:[...c,{to:s,data:r({abi:Ss,functionName:`topUp`,args:[n,d]})}],feePayer:o,feeToken:l,validAfter:Rs()})),descriptor:n,additionalDeposit:d.toString()}}function Ys(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Q(e){return Ys({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function Xs(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Q(t),t)},delete(t){e.delete(t)}}}const Zs=new WeakMap,Qs=new WeakMap;function $s(e,t){Qs.set(e,Qs.get(t)??t)}async function ec(e,t,n){let r=Zs.get(e);r||(r=new Map,Zs.set(e,r));let i=(r.get(t)??Promise.resolve()).catch(()=>{}).then(n);r.set(t,i);try{return await i}finally{r.get(t)===i&&r.delete(t)}}function tc(e,t,n){return ec(Qs.get(e)??e,`funding:${t}`,n)}async function nc(e,t){await ec(e,`write:${Q(t)}`,async()=>{let n=await e.get(Q(t));if(n?.origin!==void 0){if(t.origin!==void 0&&t.origin!==n.origin)throw Error(`SessionManager: stored channel origin mismatch`);t.origin=n.origin}if(n?.uncertainTopUp){if(n.channelId!==t.channelId)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);t.uncertainTopUp=!0}await e.set(t)})}async function rc(e,t){await ec(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}const ic=2n**96n-1n;function ac(e){if(e<0n||e>ic)throw new Y({reason:`amount exceeds uint96 range`})}async function oc(e,t,n=ps,r){return sc(await y(e,{address:n,abi:Ss,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function sc(e){return ac(e.settled),ac(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}const cc=U.custom(e=>typeof e==`string`&&l(e,{strict:!1})),lc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),uc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),dc=U.object({authorizedSigner:cc,expiringNonceHash:lc,operator:cc,payee:cc,payer:cc,salt:lc,token:cc}),fc=Vt(U.object({acceptedCumulative:U.string(),chainId:U.number(),channelId:lc,closeRequestedAt:U.optional(U.string()),deposit:U.string(),descriptor:dc,escrow:cc,highestVoucher:U.optional(U.object({channelId:lc,cumulativeAmount:U.string(),signature:uc})),requiredCumulative:U.string(),settled:U.string(),spent:U.string(),units:U.optional(U.number())}));function pc(e){return fc.encode(e)}function mc(e){return fc.decode(e)}const hc={status:`idle`};function gc(e){return{status:`active`,...e}}function _c(e,t){switch(t.type){case`challengeReceived`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:{status:`challenged`,challengeId:t.challengeId},effects:[]};case`challenge`:return e.status!==`idle`&&e.status!==`active`?$(e,t):t.snapshot?{state:{status:`hydrating`,challengeId:t.challengeId,snapshot:t.snapshot},effects:[{type:`hydrate`,snapshot:t.snapshot}]}:{state:{status:`opening`,challengeId:t.challengeId},effects:[{type:`open`}]};case`hydrated`:return e.status===`hydrating`?{state:bc(e.challengeId,t.snapshot),effects:[]}:$(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Nc({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:xc(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:$(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Ic(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?yc({challengeId:e.challengeId,descriptor:t.descriptor,event:t.event}):$(e,t);case`topUpStarted`:return e.status===`voucherNeeded`?{state:{status:`toppingUp`,challengeId:e.challengeId,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[]}:$(e,t);case`voucherAccepted`:return e.status!==`voucherNeeded`&&e.status!==`toppingUp`?$(e,t):{state:xc(e.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]};case`settleStarted`:return e.status===`active`?{state:{status:`settling`,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[{type:`settle`,channelId:e.channelId}]}:$(e,t);case`settled`:return e.status===`settling`?{state:xc(t.receipt.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]}:$(e,t);case`closeRequested`:return e.status===`active`?{state:{status:`closeRequested`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`requestClose`,channelId:e.channelId}]}:$(e,t);case`withdrawable`:return e.status===`closeRequested`?{state:{status:`withdrawable`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`withdraw`,channelId:e.channelId}]}:$(e,t);case`closeStarted`:return e.status!==`active`&&e.status!==`withdrawable`&&e.status!==`closeRequested`?$(e,t):{state:{status:`closing`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`close`,channelId:e.channelId}]};case`closed`:return e.status!==`closing`&&e.status!==`withdrawable`?$(e,t):{state:{status:`closed`,channelId:e.channelId,descriptor:e.descriptor},effects:[]}}}function vc(e,t){let n=_c(e.state,t);return e.state=n.state,n}function yc(e){let{challengeId:t,descriptor:n,event:r}=e,i=BigInt(r.requiredCumulative),a=BigInt(r.deposit);return i>a?{state:{status:`toppingUp`,challengeId:t,channelId:r.channelId,descriptor:n,deposit:r.deposit},effects:[{type:`topUp`,channelId:r.channelId,amount:(i-a).toString()}]}:{state:{status:`voucherNeeded`,challengeId:t,channelId:r.channelId,descriptor:n,requiredCumulative:r.requiredCumulative,deposit:r.deposit},effects:[{type:`voucher`}]}}function bc(e,t){return gc({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function xc(e,t,n,r){return gc({challengeId:e,channelId:t.channelId,descriptor:n,acceptedCumulative:t.acceptedCumulative,deposit:r,spent:t.spent,units:t.units??0})}function $(e,t){throw Error(`Invalid session transition: ${e.status} + ${t.type}`)}function Sc(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function Cc(e){let{channel:t,maxVoucherCumulative:n,receipt:r}=e;if(!t||r.channelId!==t.channelId)return;let i=BigInt(r.acceptedCumulative),a=BigInt(r.spent);if(a>i)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(i>t.cumulativeAmount)throw Error(`receipt accepted cumulative exceeds local voucher state`);if(a>t.cumulativeAmount)throw Error(`receipt spent exceeds local voucher state`);Sc({cumulativeAmount:i,maxVoucherCumulative:n}),Sc({cumulativeAmount:a,maxVoucherCumulative:n})}function wc(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;Cc({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function Tc(e,t){return typeof e==`bigint`?e:m(e,t)}function Ec(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(Oc(r,n),t!==void 0){let e=BigInt(t);if(e<r)throw Error(`opening deposit ${e} below request amount ${r}`);return e}let a=i===void 0?void 0:BigInt(i),o=a!==void 0&&a>r?a:r;return n===void 0||o<n?o:n}function Dc(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;Sc({cumulativeAmount:r,maxVoucherCumulative:n??null});let o=r-t,s=a??i??o,c=s>o?s:o;if(n==null)return c;let l=n-t;return c<l?c:l}function Oc(e,t){Sc({cumulativeAmount:e,maxVoucherCumulative:t??null})}function kc(e){let{channel:t,currentSocket:n,lastChallenge:r}=e;if(!t?.opened)return;let i=n?.challenge??r,a=n?.channelId??t.channelId;if(!i)throw Error(`Cannot close session: no challenge available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or make a request first to receive a fresh 402 challenge.`);if(!a)throw Error(`Cannot close session: no channel ID available. The session may not have been fully opened.`);return{challenge:i,channel:t,channelId:a}}function Ac(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function jc(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!qo(n))throw Error(`close-ready spent is not a uint96 amount`);if(n<r)throw Error(`close-ready spent is below locally confirmed spend`);if(n>Ac({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function Mc(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=Jo(r),s=Jo(a.spent);return o===void 0||s===void 0||!qo(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function Nc(e){return gc({challengeId:e.challengeId,channelId:e.entry.channelId,descriptor:e.entry.descriptor,acceptedCumulative:e.entry.cumulativeAmount.toString(),deposit:e.entry.deposit.toString(),spent:e.spent,units:e.units})}function Pc(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:hc}}function Fc(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=wc({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&vc(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function Ic(e,t){return gc({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function Lc(e){let{challengeId:t,channelId:n,closeReadyReceipt:r,cumulativeAmount:i,deliveredChunks:a=0n,socketChallengeId:o,socketChannelId:s,spent:c,tickCost:l=0n}=e;if(c>i)throw Error(`locally confirmed spend exceeds local voucher state`);if(r&&r.challengeId===t&&r.channelId===n){let e=Jo(r.spent);if(e===void 0)throw Error(`close-ready spent is not a uint96 amount`);return e>c?e:c}if(o===t&&s===n&&l>0n){let e=a*l,t=c>e?c:e;return t>i?i:t}return i}function Rc(e){let{channel:t,channelId:n,challengeId:r,cumulativeAmount:i,spent:a,state:o}=e;if(!(!t||t.channelId!==n)&&(t.cumulativeAmount=i,r))return _c(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function zc(e){return{channel:e.channel===null?null:{entry:e.channel,cumulativeAmount:e.channel.cumulativeAmount,deposit:e.channel.deposit,opened:e.channel.opened},spent:e.spent,state:e.state}}function Bc(e,t){return e.channel?(e.channel.entry.cumulativeAmount=e.channel.cumulativeAmount,e.channel.entry.deposit=e.channel.deposit,e.channel.entry.opened=e.channel.opened,{channel:e.channel.entry,spent:e.spent,state:e.state}):(t&&(t.opened=!1),{channel:null,spent:e.spent,state:e.state})}async function Vc(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(us()),e.waitForCloseReady()))(),a=BigInt(i.spent);jc({cumulativeAmount:r.channel.cumulativeAmount,readySpent:a,spent:e.spent});let o=await e.createSessionCredential(r.challenge,{action:`close`,channelId:r.channelId,descriptor:r.channel.descriptor,cumulativeAmountRaw:a.toString()}),s=a.toString();n.expectedCloseAmount=s;try{let i=e.waitForReceipt(e=>Mc({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(ls(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}function Hc(e){return`cumulativeAmount`in e}function Uc(e){if(Hc(e))return BigInt(e.cumulativeAmount)}async function Wc(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await nc(e.store,t):await rc(e.store,Q(t)),e.notifyUpdate(t)}async function Gc(e,t,n){let r=Uc(n);if(r===void 0)return;let i=await e.store.get(t);i&&i.channelId.toLowerCase()===n.channelId.toLowerCase()&&(i.cumulativeAmount=i.cumulativeAmount>r?i.cumulativeAmount:r,n.action===`close`&&(i.opened=!1),await Wc(e,i))}const Kc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),qc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),Jc=U.object({account:U.optional(U.custom()),autoSwap:U.optional(U.custom()),action:U.optional(U.enum([`open`,`topUp`,`voucher`,`close`])),channelId:U.optional(qc),cumulativeAmount:U.optional(W()),cumulativeAmountRaw:U.optional(U.string()),transaction:U.optional(Kc),descriptor:U.optional(U.custom()),additionalDeposit:U.optional(W()),additionalDepositRaw:U.optional(U.string()),depositRaw:U.optional(U.string())});function Yc(e){return e?.action!==void 0}function Xc(e){return Yc(e)&&e.descriptor!==void 0}function Zc(e,t,n){let r=n===`additionalDeposit`?e.additionalDepositRaw:e.cumulativeAmountRaw,i=n===`additionalDeposit`?e.additionalDeposit:e.cumulativeAmount;if(r)return BigInt(r);if(i)return m(i,t)}function Qc(e,t,n,r){let i=Zc(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function $c(e){return typeof e==`object`&&!!e}function el(e){return typeof e==`string`&&l(e,{strict:!1})?e:void 0}function tl(e){let t=e.request.methodDetails;return $c(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:el(t.escrowContract),escrow:el(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:el(t.feeToken),operator:el(t.operator),sessionSnapshot:Ze(t,Ye.sessionSnapshot)}:{}}function nl(e,t){if(typeof e==`string`&&l(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function rl(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function il(e){return typeof e==`string`?e:void 0}async function al(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=tl(n);(o.chainId!==void 0||i?.length===0)&&La(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});Ia(c,s);let l=s??c.chain?.id;if(La(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=Hs(n,r,t),d=nl(n.request.recipient,`recipient`),f=nl(n.request.currency,`currency`);return{amount:rl(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:Ys({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:il(n.request.suggestedDeposit),token:f}}async function ol(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=oc}=e,o=hs({...r,chainId:i.chainId,escrow:i.escrow});sl({channelId:t,descriptor:r,expectedChannelId:o,payee:i.payee,payer:i.payer,authorizedSigner:i.authorizedSigner,token:i.token});let s=await a(n,o,i.escrow);if(s.deposit===0n)throw Error(`Channel ${o} cannot be reused (closed or not found on-chain).`);if(s.closeRequestedAt!==0)throw Error(`Channel ${o} cannot be reused (pending close request).`);return{channelId:o,state:s}}function sl(e){let{authorizedSigner:t,channelId:n,descriptor:r,expectedChannelId:i,payee:a,payer:o,token:s}=e;if(n&&n.toLowerCase()!==i.toLowerCase())throw Error(`context channelId does not match descriptor`);if(!Ws(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!Ws(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!Ws(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!Ws(ms(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function cl(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function ll(e){let{context:t,decimals:n,requestAmount:r,snapshot:i,settled:a}=e;if(i)return[BigInt(i.acceptedCumulative),BigInt(i.requiredCumulative),BigInt(i.spent)+r,a].reduce((e,t)=>t>e?t:e,0n);let o=Zc(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function ul(e){let{account:t,client:n,readChannelState:r,snapshot:i}=e,a=i.highestVoucher;if(!a)throw Error(`session snapshot is missing its highest signed voucher`);if(a.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let o=BigInt(i.acceptedCumulative),s=BigInt(a.cumulativeAmount),c=BigInt(i.requiredCumulative),l=BigInt(i.deposit),u=BigInt(i.settled),d=BigInt(i.spent);if(s!==o)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(d>o)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(u>l)throw Error(`session snapshot settled amount exceeds deposit`);if(!Ps(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},ms(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await ol({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:zs(t),token:i.descriptor.token},readChannelState:r}),p=[o,c,f.state.settled].reduce((e,t)=>t>e?t:e,0n);if(p>f.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:f.channelId,cumulativeAmount:p,deposit:f.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:d}}function dl(e,t){return Ws(e.address,t.payer)?Ws(zs(e),ms(t)):!1}function fl(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(Yc(r)){if(!Xc(r))throw Error(`descriptor required for TIP-1034 session action`);return{type:`manual`,account:t,context:r,decimals:i,resolved:o}}if(!n&&r?.channelId&&!r.descriptor)throw Error(`descriptor required to reuse TIP-1034 channel`);let s=cl({context:r,snapshot:o.snapshot});return!n&&s&&dl(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&dl(t,n.descriptor)?{type:`voucher`,account:t,entry:n,maxDeposit:a,resolved:o}:{type:`open`,account:t,context:r,maxDeposit:a,resolved:o}}async function pl(e,t,n=!1){switch(e.type){case`open`:return hl(e,t,n);case`recover`:return gl(e,t);case`voucher`:return _l(e,t);case`manual`:return vl(e,t,n)}}async function ml(e,t){if(e)return await Ga(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function hl(e,t,n){let{account:r,resolved:i}=e,a=Ec({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw}),o=await qs(i.client,r,{chainId:i.chainId,deposit:a,escrow:i.escrow,feePayer:i.feePayer,feeToken:i.feeToken,initialAmount:i.amount,operator:i.operator,payee:i.payee,prefixCalls:await ml(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await Wc(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function gl(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await ol({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:zs(n),token:o.token}}),l=ll({context:r,decimals:i,requestAmount:o.amount,settled:c.state.settled,snapshot:o.snapshot});if(l>c.state.deposit)throw Error(`recovered voucher amount exceeds on-chain channel deposit`);Oc(l,a);let u=await Gs(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await Wc(t,{...d?.channelId===c.channelId&&d.uncertainTopUp?{uncertainTopUp:!0}:{},channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function _l(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;Oc(a,e.maxDeposit);let o=await Gs(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await Wc(t,r),o}async function vl(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=hs({...s,chainId:o.chainId,escrow:o.escrow});sl({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:zs(r),token:o.token});let l=await yl({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await Gc(t,o.key,l),l}async function yl(e,t){switch(e.context.action){case`open`:return bl(e);case`topUp`:return xl(e,t);case`voucher`:return Sl(e);case`close`:return Cl(e)}}async function bl(e){let{account:t,channelId:n,context:r,decimals:i,descriptor:a,resolved:o}=e;if(!r.transaction)throw Error(`transaction required for open action`);let s=Qc(r,i,`cumulativeAmount`,`open`),c=await Gs(o.client,t,a,s,o.chainId,o.escrow);return{action:`open`,type:`transaction`,channelId:n,transaction:r.transaction,signature:c.signature,descriptor:a,cumulativeAmount:s.toString(),authorizedSigner:a.authorizedSigner}}async function xl(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=Qc(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:Js(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await ml(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken)}function Sl(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Gs(a.client,t,i,Qc(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function Cl(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Ks(a.client,t,i,Qc(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}const wl={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function Tl(e){let t=new Map,n=!1,r=[],i=e.readyState,a=(e,n,i)=>{let a=t.get(e);if(a||(a=new Set,t.set(e,a)),a.add({once:typeof i==`object`&&i.once===!0,value:n}),e===`message`&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},o=(e,n)=>{let r=t.get(e);if(r)for(let e of r)e.value===n&&r.delete(e)};function s(e,a){if(a.type===`close`){if(n)return;n=!0,i=wl.CLOSED,r=null}if(a.type===`open`&&(i=wl.OPEN),a.type===`message`&&r){r.push(a);return}switch(a.type){case`close`:l.onclose?.(a);break;case`error`:l.onerror?.(a);break;case`message`:l.onmessage?.(a);break;case`open`:l.onopen?.(a)}let o=t.get(e);if(o)for(let e of Array.from(o))typeof e.value==`function`?e.value(a):e.value.handleEvent(a),e.once&&o.delete(e)}let c=null,l={addEventListener:a,close(t,n){e.close(t,n)},get bufferedAmount(){return e.bufferedAmount},get extensions(){return e.extensions},on(e,t){a(e,t)},onclose:null,onerror:null,get onmessage(){return c},set onmessage(e){if(c=e,e&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},onopen:null,off(e,t){o(e,t)},get protocol(){return e.protocol},get readyState(){return i},removeEventListener:o,send(t){e.send(t)},get url(){return e.url}};return{emit:s,socket:l}}function El(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function Dl(e){let{amount:t,assertVoucherWithinLocalLimit:n,channel:r,decimals:i,lastChallenge:a,lastUrl:o}=e;if(!r?.opened)throw Error(`Cannot top up session: no open channel.`);if(!a)throw Error(`Cannot top up session: no challenge available. Make a request first.`);if(!o)throw Error(`Cannot top up session: no URL available. Call fetch(), sse(), or ws() first.`);let s=Tc(t,i);if(s<=0n)throw Error(`Top-up amount must be greater than zero.`);return n(r.cumulativeAmount+s),{additionalDeposit:s,challenge:a,channelId:r.channelId,input:o}}function Ol(e){let{additionalDeposit:t,channel:n,channelId:r,challengeId:i,currentState:a,knownDeposit:o,receipt:s,spent:c}=e;if(n?.channelId!==r)return;let l=o!==void 0&&o>n.deposit?o:n.deposit,u={...n,deposit:l+t};return s?{channel:u,state:Ic(s,u)}:i?{channel:u,state:Nc({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function kl(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=El(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,headers:e.headers,channelId:e.expectedChannelId,deposit:t.deposit,requiredCumulative:t.requiredCumulative,...e.signal?{signal:e.signal}:{}});let n=e.getChannel();if(!n||n.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`missing-channel`};let r=n.cumulativeAmount>t.requiredCumulative?n.cumulativeAmount:Yo(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function Al(e){return e.method===qe.tempo&&e.intent===Je.session}function jl(e){return Al(e)&&Ze(e.request.methodDetails,Ye.sessionProtocol)===Xe.v2}function Ml(e){return Ze(e.request.methodDetails,Ye.sessionSnapshot)}function Nl(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return ni({...t,redirect:`manual`,headers:{...Yi(i),...Yi(t?.headers)}},xt(r),n)}function Pl(e){return e instanceof Request||typeof e==`object`&&!!e&&!(e instanceof URL)&&typeof e.url==`string`&&typeof e.method==`string`&&typeof e.clone==`function`}function Fl(e){try{let t=typeof location>`u`?void 0:location.href,n=Pl(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function Il(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function Ll(e){let t=await e.text().catch(()=>``);if(!t)return``;if(!e.headers.get(`Content-Type`)?.includes(`application/problem+json`))return t;try{return JSON.parse(t).detail??t}catch{return t}}var Rl=class extends Error{constructor(e){let t=e instanceof Error||e instanceof DOMException?e.message:String(e);super(`${t}; payment outcome unknown`),this.name=`UncertainFundingError`}};async function zl(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);if(t.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let r=await Bl({challenge:e.challenge,context:{action:`topUp`,...e.autoSwap===void 0?{}:{autoSwap:e.autoSwap},channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,headers:e.headers,input:e.input,signal:e.signal}).catch(async n=>{throw n instanceof Rl&&(t.uncertainTopUp=!0,await e.onUncertainFunding?.(t)),n});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(V.paymentReceipt);return i?as(i):void 0}async function Bl(e){let t=async t=>{e.signal?.throwIfAborted();let n=await e.createSessionCredential(t,e.context);e.signal?.throwIfAborted();let r=new AbortController,i=()=>r.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,i,{once:!0});let a=setTimeout(()=>r.abort(new DOMException(`Session management request timed out; payment outcome unknown`,`TimeoutError`)),3e4),o,s=new Promise((e,t)=>{o=()=>t(r.signal.reason),r.signal.addEventListener(`abort`,o,{once:!0})});try{return await Promise.race([e.fetch(Fl(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:uu(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new Rl(t):t}finally{clearTimeout(a),e.signal?.removeEventListener(`abort`,i),r.signal.removeEventListener(`abort`,o)}},n=await t(e.challenge);if(n.status!==402)return n;let r=_t(n).find(jl);return r?t(r):n}async function Vl(e){let t=Hl({channel:e.getChannel(),response:e.response});if(!t)return;let{channel:n,challenge:r,snapshot:i}=t;e.setChallenge(r);let a=BigInt(i.requiredCumulative),o=n.cumulativeAmount;await e.topUpIfNeeded({challenge:r,input:e.input,headers:e.init?.headers,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a,signal:e.init?.signal??(e.input instanceof Request?e.input.signal:void 0)});let s=e.getChannel();if(!s?.descriptor||s.channelId!==i.channelId)return;let c=s.cumulativeAmount>a?s.cumulativeAmount:a,l=()=>e.restoreCumulative(i.channelId,o),u;try{let t=await e.createSessionCredential(r,{action:`voucher`,channelId:i.channelId,descriptor:s.descriptor,cumulativeAmountRaw:c.toString()});u=await e.fetch(e.input,Nl(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(V.paymentReceipt)&&await l(),u}function Hl(e){let t=_t(e.response).find(jl);if(!t)return;let n=Ml(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function Ul(e){if(!e.lastUrl)throw Error(`Cannot close session: no URL available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or call fetch()/sse() before close().`);let t=e.target.challenge,n=e.signedCloseAmount,r=Pl(e.lastUrl)?e.lastUrl:void 0,i=r?{cache:r.cache,credentials:r.credentials,integrity:r.integrity,keepalive:r.keepalive,mode:r.mode===`navigate`?`same-origin`:r.mode,referrer:r.referrer,referrerPolicy:r.referrerPolicy}:void 0,a=async(a,o=!1)=>{t=a,n=(o?e.resolveSignedCloseAmount?.(a):void 0)??e.signedCloseAmount;let s=await e.createSessionCredential(a,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(r?Fl(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:uu(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=_t(o).find(jl);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await Ll(o),t=o.headers.get(V.wwwAuthenticate)??``;throw Error(`Close request failed with status ${o.status}${e?`: ${e}`:``}${t?` [${V.wwwAuthenticate}: ${t}]`:``}`)}let s=o.headers.get(V.paymentReceipt);if(!s)return;let c=as(s);if(!c.txHash||!A.validate(c.txHash,{strict:!0})||A.size(c.txHash)!==32||!Mc({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:0n,receipt:c}))throw Error(`Session close response included a mismatched payment receipt.`);return c}async function Wl(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...Yi(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!os(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),Gl(e,c,{onReceipt:r,signal:o},n,s.headers)}function Gl(e,t,n,r,i){if(!os(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return Kl({onNeedVoucher:t=>Zl({challenge:a,driver:r,headers:i,input:e,signal:n?.signal},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*Kl(e){for await(let t of ql(e))t.data!==void 0&&(yield t.data)}async function*ql(e){if(!e.response.body)throw Error(`Response has no body.`);let t=e.response.body.getReader(),n=new TextDecoder,r=``,i=!1,a=()=>{t.cancel(e.signal?.reason).catch(()=>void 0)};e.signal?.addEventListener(`abort`,a,{once:!0}),e.signal?.aborted&&a();try{for(;!e.signal?.aborted;){let{done:a,value:o}=await t.read();for(a?(i=!0,r+=n.decode()):r+=n.decode(o,{stream:!0});;){let t=Jl(r,a);if(!t)break;let n=t.index+t.length,i=r.slice(0,t.index),o=r.slice(0,n);if(r=r.slice(n),!i.trim())continue;let s=ss(i.replace(/\r\n|\r/g,`
10
+ `));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,e.signal);break;case`payment-receipt`:e.onReceipt(s.data)}}if(a)break}}finally{e.signal?.removeEventListener(`abort`,a),i||await t.cancel().catch(()=>void 0),t.releaseLock()}}function Jl(e,t){for(let n=0;n<e.length;n++){let r=Yl(e,n,t);if(!r)continue;let i=Yl(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function Yl(e,t,n){return e[t]===`
7
11
  `?1:e[t]===`\r`?e[t+1]===`
8
- `?2:t+1===e.length&&!n?0:1:0}function Ol(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=Tl({...e,signal:t.signal}),i=new TextEncoder,a=new Headers(e.response.headers);a.delete(`content-length`);let o=()=>e.signal?.removeEventListener(`abort`,n),s=new Response(new ReadableStream({async pull(e){try{let t=await r.next();if(t.done)return o(),e.close();e.enqueue(i.encode(t.value.raw))}catch(e){throw o(),e}},async cancel(){o(),t.abort(),await r.return(void 0)}}),{headers:a,status:e.response.status,statusText:e.response.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{configurable:!0,get:()=>e.response[t]});return s}async function kl(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await sl({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,headers:e.headers,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await vl({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,headers:e.headers,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function Al(e){let t=new URL(e.input.toString()),n=ml(t);e.onProbeUrl?.(n);let r=await e.fetch(n,{...e.probeInit,...e.signal?{signal:e.signal}:{}});if(r.status!==402)throw Error(`Expected a 402 payment challenge from ${n}, received ${r.status} instead.`);let i=dt(r).find(ll);if(!i)throw Error(`No payment challenge received from HTTP endpoint for this WebSocket URL. The server may not require payment or did not advertise a challenge.`);return{challenge:i,httpUrl:n,wsUrl:t}}async function jl(e){e.signal?.throwIfAborted();let t=await Al(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function Ml(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:xt(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:Po(t)}}function Nl(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function Pl(e){if(!Nl(e))return`received mismatched payment-close-ready frame`;let t=Eo(e.receipt.spent);if(t===void 0)return`received invalid payment-close-ready spend`;if(t>e.cumulativeAmount)return`received payment-close-ready beyond local voucher state`}function Fl(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!Nl(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!uc({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function Il(e){let{challenge:t,credential:n,options:r,WebSocket:i,wsUrl:a}=e,o=r?.signal;o?.throwIfAborted();let s=new i(a,r?.protocols),c=Ml({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=rl(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===nl.CONNECTING||s.readyState===nl.OPEN)&&s.close(3008,t)},d=()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),s.close()};s.addEventListener(`close`,t=>{o?.removeEventListener(`abort`,d),c.socket=null,c.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),l.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),s.addEventListener(`error`,()=>{l.emit(`error`,{type:`error`})}),s.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await Rl({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await Ll(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(Vo(n)),await e.waitForReceipt(),l.socket}function Ll(e,t,n,r){return new Promise((i,a)=>{let o=()=>{e.removeEventListener(`open`,s),e.removeEventListener(`error`,c),e.removeEventListener(`close`,c),r?.removeEventListener(`abort`,l)},s=()=>{o(),t(`open`,{type:`open`}),i()},c=()=>{o(),a(Error(`WebSocket connection to ${n} failed to open.`))},l=()=>{o(),a(r?.reason)};e.addEventListener(`open`,s,{once:!0}),e.addEventListener(`error`,c,{once:!0}),e.addEventListener(`close`,c,{once:!0}),r?.addEventListener(`abort`,l,{once:!0}),r?.aborted&&l()})}async function Rl(e){let t=Uo(e.message);if(!t){e.managedEmit(`message`,{data:e.message,type:`message`});return}switch(t.mpp){case`authorization`:return;case`message`:e.socketState.deliveredChunks+=1n,e.managedEmit(`message`,{data:t.data,type:`message`});return;case`payment-close-ready`:zl(e,t.data);return;case`payment-error`:e.driver.rejectReceipt(Error(t.message)),e.driver.rejectCloseReady(Error(t.message));return;case`payment-need-voucher`:await Bl(e,t.data);return;case`payment-receipt`:Vl(e,t.data);return}}function zl(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=Pl({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,cumulativeAmount:n,receipt:t});if(r){e.failSocketFlow(r);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleCloseReady(t),e.managedEmit(`close`,{code:1e3,reason:`stream complete`,type:`close`,wasClean:!0})}async function Bl(e,t){try{let n=e.driver.challenge;n.expires&&new Date(n.expires).getTime()<=Date.now()+5e3&&(n=await e.driver.refreshChallenge(),e.driver.challenge=n,e.socketState.challenge=n);let r=await sl({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:n,event:t,expectedChannelId:e.socketState.channelId,getChannel:e.driver.getChannel,input:e.driver.httpUrl,signal:e.driver.options?.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status===`ignored`){e.failSocketFlow(r.reason===`channel-mismatch`?`received mismatched payment-need-voucher frame`:`cannot create voucher: no active channel`);return}let i=await e.driver.createSessionCredential(n,r.context);e.rawSocket.send(Vo(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function Vl(e,t){let n=Fl({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,expectedCloseAmount:e.socketState.expectedCloseAmount,receipt:t});if(n){e.failSocketFlow(n);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleReceipt(t)}function Hl(e,t,n,r){let i=ht(e),a=new Headers;if(i.toLowerCase()!==B.authorization.toLowerCase()){let e=new Headers(r).get(B.authorization)??(n instanceof Request?n.headers.get(B.authorization):null);e&&!e.startsWith(`${V.payment} `)&&a.set(B.authorization,e)}return a.set(i,t),a}const Ul=new WeakMap;async function Wl(e,t){let n=Ul.get(e)??new Map;Ul.set(e,n);let r=n.get(t),i,a=new Promise(e=>{i=e});return n.set(t,a),await r,()=>{i(),n.get(t)===a&&n.delete(t)}}function Gl(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function Kl(e,t,n){try{let r=e.response?.headers.get(B.paymentReceipt);if(r){let e=Lo(r);if(e.challengeId===t.id&&Gl(n,e))return!0}}catch{}return e.challenges?.some(e=>ll(e)?Gl(n,ul(e)):!1)??!1}function ql(e){let{currencies:t,decimals:n,expectedRecipients:r,maxAmount:i,maxAtomicAmount:a}=e;if((i!==void 0||a!==void 0)&&t===void 0)throw Error(`Tempo session maxAmount and maxAtomicAmount require currencies.`);return{currencies:t?.map(e=>e.toLowerCase()),expectedRecipients:r?new Set(r.map(e=>e.toLowerCase())):void 0,maxAmount:Jl(i,n),maxAtomicAmount:a===void 0?void 0:BigInt(a)}}function Jl(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo session maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo session maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return f(e,t)}}function Yl(e,t){if(e.currencies&&!e.currencies.includes(t.currency.toLowerCase()))throw Error(`Tempo session currency is not allowed: ${t.currency}.`);if(e.expectedRecipients&&(!t.recipient||!e.expectedRecipients.has(t.recipient.toLowerCase())))throw Error(`Unexpected session recipient: ${t.recipient}`);let n=BigInt(t.amount);if(e.maxAtomicAmount!==void 0&&n>e.maxAtomicAmount)throw Error(`Tempo session amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0&&n>e.maxAmount)throw Error(`Tempo session amount exceeds maxAmount.`)}function Xl(e,t){try{return Yl(e,t),!0}catch{return!1}}function Zl(e){return typeof e==`object`&&!!e&&e.action===`close`}function Ql(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a=6,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:p}=e,m=ql(e),h=Oa({chain:x,getClient:c,rpcUrl:Gn}),g=wa({account:t}),_=l===void 0?void 0:f(l,a),v=u===void 0?void 0:f(u,a),y=e.origin===void 0?void 0:new URL(e.origin);if(y&&![`http:`,`https:`].includes(y.protocol))throw Error(`Session origins require HTTP or HTTPS`);let b=i??Os(),S={store:b,notifyUpdate:e=>d?.(e)},C=async(e,t,n)=>{let r=g(e.client,t),i=t?.action?t.descriptor:n?.descriptor??Bc({context:t,snapshot:e.snapshot})?.descriptor;return await p?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:Ko(i)}:{}}})??r},w=async(e,t,n)=>Wc({account:await C(e,t,n),entry:n,context:t,decimals:a,maxDeposit:_,resolved:e}),T=Nt(_o,{canHandleChallenge:({challenge:e,context:t})=>ll(e)&&(Zl(t)||t===Or||Xl(m,e.request)),context:Ec,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&Yl(m,t.request);let a=await Lc({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:h}),c=Ti(e),l=Ai(e)??y?.origin;if(l!==void 0&&(l===`null`||![`http:`,`https:`].includes(new URL(l).protocol)))throw Error(`Session payments require an HTTP or HTTPS origin`);if(y&&l!==y.origin)throw Error(`Session channel origin mismatch`);let u={...S,origin:l},d=()=>{};try{let e=!Dc(i)&&i?.descriptor===void 0;e&&(d=await Wl(b,a.key),c&&(await b.get(a.key))?.opened&&await c.prepare());let n=await b.get(a.key);if(n&&n.origin!==l)throw Error(`Session channel origin mismatch`);if(l&&!n&&a.snapshot&&!i?.descriptor&&!y)throw Error(`Session snapshot recovery requires an explicitly configured origin or descriptor`);let o=await w(a,i,n);if(!e&&c&&o.type===`open`){d=await Wl(b,a.key);let e=await b.get(a.key);if(e&&e.origin!==l)throw Error(`Session channel origin mismatch`);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await b.get(a.key)),o=await w(a,i,n))}let s,f=c&&o.type===`open`?{store:{get:e=>b.get(e),async set(e){s=l?{...e,origin:l}:e},delete:e=>b.delete(e)},notifyUpdate(){}}:u,p=await xs(t,await Gc(o,f,za(i?.autoSwap??r,La)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||Kl(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await b.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await Ps(b,e),S.notifyUpdate(e))}return!0}finally{d()}}}else d();return p}catch(e){throw d(),e}}});function E(e,t,n){let r={challenge:e,context:t};return ki(r,$l(n)),T.createCredential(r)}let D=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>Ns(b,Q(n),async()=>{s?.throwIfAborted();let c=await b.get(Q(n));if(c?.channelId===n.channelId&&(n=c),n.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let l=n.deposit>r?n.deposit:r,u=ac({deposit:l,maxDeposit:_,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:v});u>0n&&await _l({autoSwap:e,additionalDeposit:u,challenge:t,channel:n,channelId:n.channelId,createSessionCredential:(e,t)=>E(e,t,a),onUncertainFunding:async e=>{let t=await b.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await Ps(b,n),S.notifyUpdate(n)},fetch:i,input:a,signal:s});let d=l+u;if(d===n.deposit)return;let f=await b.get(Q(n)),p=f?.channelId.toLowerCase()===n.channelId.toLowerCase()?f:n,m={...p,deposit:p.deposit>d?p.deposit:d};await Ps(b,m),S.notifyUpdate(m)});return mi(T,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!ll(e))return;let c=t===void 0?void 0:Ec.parse(t);if(Dc(c))return;Yl(m,e.request);let l=await Lc({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:h}),u=await b.get(l.key);if(!u?.opened)return;let d=$l(i);if(u.origin!==d)throw Error(`Session channel origin mismatch`);let f=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,p=u.cumulativeAmount+Po(e),g=f?BigInt(f.requiredCumulative):p,_=g>p?g:p,v=f?BigInt(f.deposit):u.deposit,y=v>u.deposit?v:u.deposit;_<=y&&y===u.deposit||!Uc(await C(l,c,u),u.descriptor)||await D({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:y,fetch:r,input:i,requiredCumulative:_,signal:a})}),Si(T,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!ll(e))return u;if(!Ro(u))return No(xt(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await Lc({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:h})).key,p=await b.get(f),m={assertVoucherWithinLocalLimit:e=>oc(e,_),createSessionCredential:(e,t)=>E(e,t,c),fetch:i,getChannel:()=>p??null,async topUpIfNeeded({deposit:n,requiredCumulative:r,signal:a}){p&&await D({autoSwap:t===void 0?void 0:Ec.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return Ol({onNeedVoucher:(t,n)=>kl({challenge:e,driver:m,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function $l(e){let t=new URL(e instanceof Request?e.url:e,globalThis.location===void 0?void 0:globalThis.location.href);if(![`http:`,`https:`].includes(t.protocol))throw Error(`Session payments require an HTTP or HTTPS origin`);return t.origin}const eu=new WeakMap;function tu(e,t){eu.set(e,t)}function nu(e){let t=null;return{wait(n=()=>!0){if(t)throw Error(`${e} wait already in progress`);return new Promise((e,r)=>{t={predicate:n,resolve:e,reject:r}})},settle(e){if(!t||!t.predicate(e))return;let n=t;t=null,n.resolve(e)},reject(e){if(!t)return;let n=t;t=null,n.reject(e)}}}function ru(e){let t=nu(`close-ready`),n=nu(`receipt`);return{waitForReceipt(e){return n.wait(e)},waitForCloseReady(){let n=e.getSocketSession()?.closeReadyReceipt;return n?Promise.resolve(n):t.wait()},settleReceipt(e){n.settle(e)},settleCloseReady(n){let r=e.getSocketSession();r&&r.challenge.id===n.challengeId&&r.channelId===n.channelId&&(r.closeReadyReceipt=n),t.settle(n)},rejectReceipt(e){n.reject(e)},rejectCloseReady(e){t.reject(e)}}}function iu(e){return e.method===Ve.tempo&&e.intent===He.charge}function au(e){if(!iu(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function ou(e,t,n){if(!n)return t;let r={...Hi(fl(e)?e.headers:void 0),...Hi(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===B.paymentSession.toLowerCase())?t:{...t,headers:{...r,[B.paymentSession]:n}}}function su(e,t){return e===void 0?t:{...Ec.parse(e),...t}}function cu(e){let t=e.decimals??6,n=e.webSocket??globalThis.WebSocket;return{decimals:t,fetch:e.fetch??globalThis.fetch.bind(globalThis),maxVoucherCumulative:e.maxDeposit===void 0?null:f(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:f(e.topUpAmount,t),WebSocket:n}}function lu(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&Aa(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=cu(e),i;function a(e){let t=new URL(fl(e)?e.url:String(e),typeof location>`u`?void 0:location.href);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`SessionManager: session payments require an HTTP origin`);let n=t.origin;if(i!==void 0&&i!==n)throw Error(`SessionManager: session payment origin mismatch`);return i=n,n}let o=ua(r.fetch),s=da(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??(fl(e)?e.redirect:void 0))===`manual`?`manual`:`error`});if(r.url&&new URL(r.url).origin!==n)throw Error(`SessionManager: session response origin mismatch`);return r};let c=r.fetch;o&&(r.fetch=Tr(c,o));let l=Oa({chain:x,getClient:e.client?()=>e.client:e.getClient,rpcUrl:Gn}),u=wa({account:e.account}),d=fc(),f=e.credentialContext===void 0?void 0:su(e.credentialContext,{}),p=ru({getSocketSession:()=>d.socketSession}),m=e.channelStore??Os(),h=new Set,g;async function _(e){let t=await m.get(e);if(t?.opened&&!h.has(t.channelId)){if(t.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return t}}let v=e=>{if(e.origin!==void 0&&e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return e.origin=i,Ps(m,e)},y={async get(e){let t=await _(e);return t&&g&&(g.seenExisting.add(e),!g.committed&&!g.created.has(e)&&(g.resumed??=t)),t},async set(e){let t=Q(e);e.opened&&h.delete(e.channelId),g?.trackCreates&&!g.seenExisting.has(t)&&g.created.set(t,e),await v(e)},delete:e=>Fs(m,e)};js(y,m);async function b(e){let t=Q(e),n=await m.get(t);if(e.uncertainTopUp||n?.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);h.add(e.channelId),g?.seenExisting.delete(t),g?.resumed===e&&(g.resumed=void 0),await Promise.resolve(Fs(m,t)).catch(()=>void 0)}async function S(){let e=g;if(e?.created.size){for(let[t,n]of e.created){let e=await m.get(t);if(n.uncertainTopUp||e?.channelId===n.channelId&&e.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before discarding the channel.`);h.add(n.channelId),await Promise.resolve(Fs(m,t)).catch(()=>void 0)}e.created.clear(),await le(e.committed??e.previous)}}function C(e){let t=Ge(e.request.methodDetails,Ue.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=g;if(!n?.created.size||!d.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&d.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=_c({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function w(e){return Xs(d,e)}function T(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function E(e){let t=g,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit&&!e.uncertainTopUp||(t.resumed=void 0,t.committed=_c({channel:d.channel,spent:d.spent,state:d.state}))}let D=Ql({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:y,onChannelUpdate(e){e.channelId!==d.channel?.channelId&&(d.spent=0n),d.channel=e,d.lastChallenge&&w({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:T()}),E(e)}}),O=_i(D);O&&mi(D,e=>ae(()=>Promise.resolve(O(e)),e.signal)),Ci(D);let k=bo({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),A=Vi({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[D],onChallenge:async(e,t)=>{if(!cl(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&nt(e)===nt(d.lastChallenge);n&&n.challengesReceived++,!i&&(C(e)||(n?.created.size?await S():r&&await le(n.committed??n.previous)),d.lastChallenge=e,w({type:`challengeReceived`,challengeId:e.id}))}});function j(e,t){let n={challenge:e,context:su(f,t)};return i&&ki(n,i),D.createCredential(n)}function M(e){pc({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:d})}function N(e=d.state.status===`active`?d.state.units:0){!d.channel||!d.lastChallenge||d.state.status!==`active`&&d.state.status!==`withdrawable`&&d.state.status!==`closeRequested`&&w({type:`activated`,challengeId:d.lastChallenge.id,entry:d.channel,spent:d.spent.toString(),units:e})}async function P(t){let n=t.headers.get(B.paymentSessionSnapshot);if(!n)return;let r=Ks(n);Aa(e.allowedChainIds,r.chainId);let i=await l({chainId:r.chainId});ka(i,r.chainId);let a=u(i),{entry:o,spent:s}=await Hc({account:await e.resolveAccount?.({account:a,chainId:r.chainId,operation:{authority:Ko(r.descriptor),kind:`authorizePaymentChannel`}})??a,client:i,snapshot:r});return re(o.cumulativeAmount),await Promise.resolve(y.set(o)).catch(()=>void 0),d.channel=o,d.spent=s,o}async function F(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=fl(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=fl(t)?t.url:t,l={...s,method:`HEAD`,headers:{...Hi(i),...Hi(n?.headers),[B.acceptPayment]:`${Ve.tempo}/${He.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await P(t);let n=dt(t).find(iu);if(!n||!au(n))return;let i=new URL(String(c),typeof location<`u`?location.href:void 0);if(t.url&&new URL(t.url).origin!==i.origin)return;ji(n,i,e.trustedTempoProofRealms);let a=await k.createCredential({challenge:n,context:{}}),o=await r.fetch(c,Yr({...l,redirect:`manual`},ht(n),a));return o.ok?await P(o):void 0}catch{return}}function ee(e,t){let n=d.socketSession;return hc({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:d.channel?.channelId===t?d.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:d.spent,tickCost:n?.tickCost})}function I(e,t){let n=ul(t);if(!n)return;if(qo({...n.descriptor,chainId:n.chainId,escrow:n.escrow}).toLowerCase()!==n.channelId.toLowerCase())throw Error(`close snapshot descriptor does not match its channel ID`);if(n.channelId.toLowerCase()!==e.channelId.toLowerCase())throw Error(`close snapshot channel ID does not match local session`);if(n.chainId!==e.chainId||n.escrow.toLowerCase()!==e.escrow.toLowerCase())throw Error(`close snapshot payment scope does not match local session`);let r=BigInt(n.acceptedCumulative),i=BigInt(n.spent);if(r<0n||i<0n)throw Error(`close snapshot amounts must not be negative`);if(i>r)throw Error(`close snapshot spent exceeds accepted cumulative amount`);if(r>e.cumulativeAmount)throw Error(`close snapshot accepted cumulative exceeds local voucher state`);return{acceptedCumulative:r,spent:i}}function te(e,t){let n=I(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(d.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>d.spent&&(d.spent=i),n}function ne(e,t=e.challenge,n=!1){let r=(n?te(e,t):I(e.channel,t))?.acceptedCumulative??ee(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return re(r),r.toString()}function re(e){ec({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let L,ie;async function ae(e,t){if(ie)throw ie;for(;;){let e=L;if(!e)break;if(!t)await e;else{t.throwIfAborted();let n;try{await Promise.race([e,new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0})})])}finally{t.removeEventListener(`abort`,n)}}}if(t?.throwIfAborted(),ie)throw ie;let n=e();L=n;try{return await n}catch(e){throw e instanceof gl&&(ie=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{L===n&&(L=void 0)}}async function oe(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return Ns(m,Q(d.channel),async()=>{let{knownDeposit:t,...n}=e,i=d.channel?await y.get(Q(d.channel)):void 0;if(i?.channelId===e.channelId&&i.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let a=await _l({...n,channel:d.channel,createSessionCredential:j,fetch:r.fetch,onUncertainFunding:async e=>{let t=await y.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};d.channel?.channelId===e.channelId&&(d.channel=n),await y.set(n),E(n)}});M(a);let o=d.channel,s=ol({additionalDeposit:e.additionalDeposit,channel:d.channel,channelId:e.channelId,challengeId:d.lastChallenge?.id,currentState:d.state,knownDeposit:t,receipt:a,spent:d.spent});if(s?.channel&&d.lastChallenge){let e=s.channel;for(;;){await y.set(e);let t=d.channel;if(t===o)break;if(!t)return a;let n=s.channel;e=t.channelId===n.channelId?{...t,deposit:t.deposit>n.deposit?t.deposit:n.deposit,cumulativeAmount:t.cumulativeAmount>n.cumulativeAmount?t.cumulativeAmount:n.cumulativeAmount}:t,o=t}if(e.channelId!==s.channel.channelId)return a;d.channel=e,w({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:T()}),E(e)}return a})}async function se(e){return ae(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=ac({deposit:n,maxDeposit:r.maxVoucherCumulative,requiredCumulative:e.requiredCumulative,suggestedDeposit:e.challenge.request.suggestedDeposit===void 0?void 0:BigInt(e.challenge.request.suggestedDeposit),topUpAmount:r.topUpAmount});i!==0n&&await oe({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function ce(e,t){let n=gc({channel:d.channel,channelId:e,challengeId:d.lastChallenge?.id,cumulativeAmount:t,spent:d.spent,state:d.state});n&&d.channel&&(w({type:`activated`,challengeId:n.challengeId,entry:d.channel,spent:n.spent,units:n.units}),await v(d.channel))}async function le(e){let t=vc(e,d.channel);d.channel=t.channel,d.spent=t.spent,d.state=t.state,d.channel?.opened&&await v(d.channel)}function ue(e){let t=e.headers.get(B.paymentReceipt),n=t?Lo(t):null;return M(n),Object.assign(e,{receipt:n,challenge:d.lastChallenge,channelId:d.channel?.channelId??null,cumulative:d.channel?.cumulativeAmount??0n})}async function R(e,t){if(g)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);a(e),d.lastUrl=e,d.lastHeaders=t?.headers;let n=_c({channel:d.channel,spent:d.spent,state:d.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};g=i;try{await F(e,t),i.trackCreates=!0;let a=ou(e,t,d.channel?.opened?d.channel.channelId:void 0);f&&(a={...a,context:f});let o=!n.channel?.opened;async function s(){let n=i.resumed;return!o||!n?!1:(o=!1,await b(n),a=ou(e,t,void 0),!0)}for(;;){let t;try{t=await A(e,a)}catch(e){if(i.created.size?await S():await le(i.committed??n),await s())continue;throw e}let o=ue(t),c=!1;if(o.status===402){let t=await yl({input:e,init:a,response:o,createSessionCredential:j,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:ce,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:se});t&&(c=!0,o=ue(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await S():await le(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function z(e){let t=await xl({createSessionCredential:j,fetch:r.fetch,getMinimumSpent:()=>d.spent,headers:d.lastHeaders,lastUrl:d.lastUrl,resolveSignedCloseAmount:t=>ne(e,t,!0),signedCloseAmount:ne(e),setChallenge(e){d.lastChallenge=e},target:e});return t&&(N(),w({type:`closeStarted`}),w({type:`closed`,receipt:t})),t}let de={createSessionCredential:j,doFetch:R,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:re,acceptReceipt(e){M(e)},topUpIfNeeded:se},fe={get channelId(){return d.channel?.channelId},get cumulative(){return d.channel?.cumulativeAmount??0n},get opened(){return d.channel?.opened??!1},get state(){return d.state},fetch:R,async topUp(e){let t=al({amount:e,assertVoucherWithinLocalLimit:re,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return ae(async()=>{if(d.channel?.channelId!==t.channelId||d.lastChallenge!==t.challenge||d.lastUrl!==t.input)throw Error(`Session changed while waiting to top up`);let n=al({amount:e,assertVoucherWithinLocalLimit:re,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return oe({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){return Sl(e,t,de)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=ml(e);a(n);let i=t?.signal?{signal:t.signal}:void 0;await F(n,i);let o=d.channel?.opened?d.channel.channelId:void 0,{challenge:s,credential:c,httpUrl:l,wsUrl:u}=await jl({async createSessionCredential(e,i){return d.lastChallenge=e,await gi(D,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),j(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){d.lastUrl=e.toString()},probeInit:ou(n,i,o),signal:t?.signal});return d.lastChallenge=s,Il({challenge:s,credential:c,httpUrl:l,WebSocket:r.WebSocket,wsUrl:u,options:t,createSessionCredential:j,getChannel:()=>d.channel,setSocketSession(e){d.socketSession=e},async refreshChallenge(){let e=await Al({fetch:r.fetch,input:l,probeInit:ou(l,i,d.channel?.opened?d.channel.channelId:void 0),signal:t?.signal});return d.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:re,acceptReceipt:M,rejectCloseReady:p.rejectCloseReady,rejectReceipt:p.rejectReceipt,settleCloseReady:p.settleCloseReady,settleReceipt:p.settleReceipt,topUpIfNeeded:se,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=sc({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===nl.OPEN){let r=await yc({activeSocket:n,createSessionCredential:j,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return N(),w({type:`closeStarted`}),w({type:`closed`,receipt:r}),r}return z(t)}};return tu(fe,{consumeSseResponse(e,t,n){let r=a(e);if(t.url&&new URL(t.url).origin!==r)throw Error(`SessionManager: session response origin mismatch`);return Cl(e,t,n,de)},rehydrate({channel:e,challenge:t,input:n,spent:r}){let i=a(n);if(e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!cl(t))throw Error(`Cannot restore session: challenge is not tempo/session.`);if(r<0n)throw Error(`Cannot restore session: spent must not be negative.`);if(r>e.cumulativeAmount)throw Error(`Cannot restore session: spent exceeds local voucher state.`);re(e.cumulativeAmount);let o=I(e,t),s=o&&o.spent>r?o.spent:r;d.lastUrl=n,d.lastChallenge=t,d.channel=e,d.spent=s,w({type:`challengeReceived`,challengeId:t.id}),w({type:`activated`,challengeId:t.id,entry:e,spent:s.toString(),units:0})}}),fe}(function(e){e.serializeSnapshot=Gs,e.deserializeSnapshot=Ks})(lu||={});const uu=(1n<<64n)-1n,du={dev_second:1n,day:86400n,week:604800n};function fu(e){return e instanceof Date?e:new Date(e)}function pu(e){let t=e.getTime();if(!Number.isFinite(t))throw new Y({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new Y({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new Y({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function mu(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new Y({reason:`periodCount is invalid`});let t=du[e.periodUnit];if(t===void 0)throw new Y({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>uu)throw new Y({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new Y({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function hu(e){let{challengeExpires:t,request:n}=e;mu(n);let r=pu(fu(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new Y({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function gu(e){return[{address:ku(e.currency,`currency`),selector:`0x95777d59`,recipients:[ku(e.recipient,`recipient`)]}]}function _u(e){try{let t=E.fromBytes(C.toBytes(e));if(E.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new Y({reason:`challenge id must encode 32 bytes`})}}async function vu(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=bu({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:R.getSignPayload(o)}),c=z.from(s);if(c.type===`keychain`||c.type===`multisig`)throw new Y({reason:`keyAuthorization must use a primitive signature`});return R.from(o,{signature:s})}function yu(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new Y({reason:`invalid keyAuthorization payload`});let o=xu(i.signature),s=Su(o);if(Cu({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==_u(n))throw new Y({reason:`keyAuthorization challenge mismatch`});return wu(o,a),Eu(Tu(o),a),Du(o.scopes,a),{authorization:o,source:{address:Ou(o,s),chainId:r}}}function bu(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return R.from({address:ku(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:pu(fu(i.subscriptionExpires)),limits:[{token:ku(i.currency,`currency`),limit:BigInt(i.amount),period:mu(i)}],scopes:gu(i),type:t.keyType,witness:_u(n)})}function xu(e){try{return R.deserialize(e)}catch(e){throw e instanceof R.InvalidSignatureTypeError?new Y({reason:`keyAuthorization must use a primitive signature`}):new Y({reason:`invalid keyAuthorization payload`})}}function Su(e){let t=e.signature;if(!t)throw new Y({reason:`keyAuthorization must use a primitive signature`});return t}function Cu(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new Y({reason:`keyAuthorization chainId mismatch`});if(t){if(!l(n.address,ku(t.accessKeyAddress,`accessKeyAddress`)))throw new Y({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new Y({reason:`keyAuthorization key type mismatch`})}}function wu(e,t){if(hu({request:t}),e.expiry!==pu(fu(t.subscriptionExpires)))throw new Y({reason:`keyAuthorization expiry mismatch`})}function Tu(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new Y({reason:`keyAuthorization must contain exactly one token limit`});return t}function Eu(e,t){if(!l(e.token,ku(t.currency,`currency`)))throw new Y({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new Y({reason:`keyAuthorization amount mismatch`});if(e.period!==mu(t))throw new Y({reason:`keyAuthorization period mismatch`})}function Du(e,t){if(!e||e.length!==1)throw new Y({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=ku(t.currency,`currency`),r=ku(t.recipient,`recipient`),i=new Set;for(let t of e){if(!l(t.address,n))throw new Y({reason:`keyAuthorization call target mismatch`});let e=Au(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new Y({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new Y({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!l(t.recipients[0],r))throw new Y({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new Y({reason:`keyAuthorization must allow transferWithMemo`})}function Ou(e,t){let n=R.getSignPayload(e);try{let e=z.extractAddress({payload:n,signature:t});if(!z.verify(t,{address:e,payload:n}))throw new Y({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof Y?e:new Y({reason:`keyAuthorization signature is invalid`})}}function ku(e,t){if(!c(e))throw new Y({reason:`${t} must be an address`});return e.toLowerCase()}function Au(e){return typeof e==`string`?e.toLowerCase():``}const ju=U.object({accessKey:U.optional(U.custom()),account:U.optional(U.custom())});function Mu(e={}){let t=Oa({chain:P,getClient:e.getClient,rpcUrl:Gn}),n=wa({account:e.account});return Nt(vo,{context:ju,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??X.testnet,o=await t({chainId:a}),s=n(o,i),c=i?.accessKey??e.accessKey??r.request.methodDetails?.accessKey;if(!c)throw Error("No `accessKey` provided. The subscription challenge must include `accessKey`, or the client must pass one to parameters/context.");Pu(r.request),await e.validateRequest?.(r.request);let u=await Nu(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),d=yu({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:R.serialize(u),type:`keyAuthorization`},request:r.request});if(!l(d.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return Tt({challenge:r,payload:{signature:R.serialize(u),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function Nu(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await vu({accessKey:n,account:r,challengeId:i,chainId:a,request:o});if(s)return s;let c=await e.request({method:`wallet_authorizeAccessKey`,params:[{address:n.accessKeyAddress,expiry:pu(fu(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:E.fromNumber(BigInt(o.amount)),period:mu(o)}],scopes:gu(o),witness:_u(i)}]});return R.fromRpc(c.keyAuthorization)}function Pu(e){mu(e),pu(fu(e.subscriptionExpires))}const Fu=Object.assign(Ql,{manager:lu});function Iu(e={}){let t=e.expectedChainId!==void 0&&(e.allowedChainIds===void 0||e.allowedChainIds.includes(e.expectedChainId)),n=e.expectedChainId===void 0?e:{...e,allowedChainIds:t?[e.expectedChainId]:[]};return[bo(e),Fu(n)]}(function(e){e.charge=bo,e.common=Iu,e.session=Fu,e.subscription=Mu})(Iu||={});const Lu=N.union([N.boolean(),N.literal(`true`).transform(()=>!0),N.literal(`false`).transform(()=>!1)]);async function Ru(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}const zu=N.object({allowCustomEscrow:N.optional(Lu),autoSwap:N.optional(Lu),channel:N.optional(N.coerce.string()),deposit:N.optional(N.union([N.string(),N.number()])),payWith:N.optional(N.string()),slippage:N.optional(N.coerce.number()),tokenIn:N.optional(N.string())}),Bu=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`];function Vu(){let t;return dr({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:n,options:r,methodOpts:i}){let a=sr(r.account),o=n.request,c=o.currency,l=qu(i),u=Zu({autoSwap:l.autoSwap??r.autoSwap,payWith:l.payWith??r.payWith,slippage:l.slippage??r.slippage,tokenIn:l.tokenIn}),d=c??``,f=o.decimals??6,p,m,h,g=!1,_=process.env.MPPX_PRIVATE_KEY?.trim()||(qn(a)?void 0:await cr(a).get());if(!_&&qn(a)&&od()){g=!0;let t=id(a);if(t){let i=Xn(r.rpcUrl,{network:r.network});h=e({chain:await Zn({network:r.network,rpcUrl:i}),transport:s(i)}),Yu({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let a=c?await er(h,c,t.wallet_address).catch(()=>void 0):void 0;d=a?.symbol??c??``,f=a?.decimals??o.decimals??6}}else if(_)m=le(_);else{let e=cd();if(e){let t=await cr(e).get();t&&(m=le(t))}if(!m)throw r.account?new Bn({code:`ACCOUNT_NOT_FOUND`,message:`Account "${a}" not found.`,exitCode:69}):new Bn({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!g&&m){let t=Xn(r.rpcUrl,{network:r.network});h=e({chain:await Zn({network:r.network,rpcUrl:t}),transport:s(t)}),Yu({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let i=c?await er(h,c,m.address).catch(()=>void 0):void 0;d=i?.symbol??c??``,f=i?.decimals??o.decimals??6}if(g)return{tokenSymbol:d,tokenDecimals:f,explorerUrl:p,methods:[],async createCredential(e){let t=e.headers.get(`www-authenticate`);if(!t)throw Error(`No WWW-Authenticate header in 402 response.`);return sd(t)}};if(!m||!h)throw new Bn({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let v=Iu({account:m,...l.allowCustomEscrow===void 0?{}:{allowCustomEscrow:l.allowCustomEscrow},getClient:()=>h,...u===void 0?{}:{autoSwap:u},maxDeposit:(()=>{if(n.intent!==`session`)return;let e=n.request.suggestedDeposit,t=(l.deposit===void 0?void 0:String(l.deposit))??e??($n(h.chain)?`10`:void 0);if(!t)throw new Bn({code:`MISSING_DEPOSIT`,message:`Session payment requires a deposit. Use -M deposit=<amount> or connect to testnet.`,exitCode:2});return t})()}),y=(()=>{if(!l.channel)return;let e=l.channel,t=$u(e);return{channelId:e,...t!==void 0&&{cumulativeAmountRaw:t.toString()}}})();return t={descriptor:void 0,async signVoucher({channelId:e,cumulativeAmount:r,escrowContract:i,chainId:a,action:o=`voucher`}){let s=t?.descriptor;if(!s)throw Error(`session descriptor not available`);let c={channelId:e,cumulativeAmount:r},l=await us(h,m,c,i,a);return Tt({challenge:n,payload:{action:o,channelId:e,...o===`close`?{closeSignature:await ds(h,m,c,i,a)}:{},descriptor:s,cumulativeAmount:r.toString(),signature:l},source:`did:pkh:eip155:${a}:${m.address}`})},source:`did:pkh:eip155:${h.chain.id}:${m.address}`},{tokenSymbol:d,tokenDecimals:f,explorerUrl:p,methods:[...v],credentialContext:y}},prepareCredentialRequest({challenge:e,headers:t}){e.intent===`session`&&(t.Accept=`text/event-stream`)},async handleResponse(e){if(e.challenge.intent!==`session`||!t)return!1;let{challenge:n,credential:r,response:i,fetchUrl:a,fetchInit:o,verbose:s}=e,{silent:c,confirmEnabled:l,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,shownKeys:p}=e,m=c?e=>{}:e=>process.stderr.write(e),h=xt(r),g=n.request,_=g.methodDetails,v=h.payload.channelId,y=_?.escrowContract??_?.escrow??`0x4d50500000000000000000000000000000000000`,b=_?.chainId??0,x=BigInt(g.amount),S=`cumulativeAmount`in h.payload&&h.payload.cumulativeAmount?BigInt(h.payload.cumulativeAmount):0n;if(`descriptor`in h.payload&&(t.descriptor=h.payload.descriptor),s>=1){if(h.payload.action===`open`){let e=g.suggestedDeposit,t=e?` ${Z.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
12
+ `?2:t+1===e.length&&!n?0:1:0}function Xl(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=ql({...e,signal:t.signal}),i=new TextEncoder,a=new Headers(e.response.headers);a.delete(`content-length`);let o=()=>e.signal?.removeEventListener(`abort`,n),s=new Response(new ReadableStream({async pull(e){try{let t=await r.next();if(t.done)return o(),e.close();e.enqueue(i.encode(t.value.raw))}catch(e){throw o(),e}},async cancel(){o(),t.abort(),await r.return(void 0)}}),{headers:a,status:e.response.status,statusText:e.response.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{configurable:!0,get:()=>e.response[t]});return s}async function Zl(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await kl({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,headers:e.headers,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await Bl({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,headers:e.headers,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function Ql(e){let t=new URL(e.input.toString()),n=Il(t);e.onProbeUrl?.(n);let r=await e.fetch(n,{...e.probeInit,...e.signal?{signal:e.signal}:{}});if(r.status!==402)throw Error(`Expected a 402 payment challenge from ${n}, received ${r.status} instead.`);let i=_t(r).find(jl);if(!i)throw Error(`No payment challenge received from HTTP endpoint for this WebSocket URL. The server may not require payment or did not advertise a challenge.`);return{challenge:i,httpUrl:n,wsUrl:t}}async function $l(e){e.signal?.throwIfAborted();let t=await Ql(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function eu(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:Dt(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:ns(t)}}function tu(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function nu(e){if(!tu(e))return`received mismatched payment-close-ready frame`;let t=Jo(e.receipt.spent);if(t===void 0)return`received invalid payment-close-ready spend`;if(t>e.cumulativeAmount)return`received payment-close-ready beyond local voucher state`}function ru(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!tu(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!Mc({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function iu(e){let{challenge:t,credential:n,options:r,WebSocket:i,wsUrl:a}=e,o=r?.signal;o?.throwIfAborted();let s=new i(a,r?.protocols),c=eu({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=Tl(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===wl.CONNECTING||s.readyState===wl.OPEN)&&s.close(3008,t)},d=()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),s.close()};s.addEventListener(`close`,t=>{o?.removeEventListener(`abort`,d),c.socket=null,c.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),l.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),s.addEventListener(`error`,()=>{l.emit(`error`,{type:`error`})}),s.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await ou({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await au(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(ls(n)),await e.waitForReceipt(),l.socket}function au(e,t,n,r){return new Promise((i,a)=>{let o=()=>{e.removeEventListener(`open`,s),e.removeEventListener(`error`,c),e.removeEventListener(`close`,c),r?.removeEventListener(`abort`,l)},s=()=>{o(),t(`open`,{type:`open`}),i()},c=()=>{o(),a(Error(`WebSocket connection to ${n} failed to open.`))},l=()=>{o(),a(r?.reason)};e.addEventListener(`open`,s,{once:!0}),e.addEventListener(`error`,c,{once:!0}),e.addEventListener(`close`,c,{once:!0}),r?.addEventListener(`abort`,l,{once:!0}),r?.aborted&&l()})}async function ou(e){let t=ds(e.message);if(!t){e.managedEmit(`message`,{data:e.message,type:`message`});return}switch(t.mpp){case`authorization`:return;case`message`:e.socketState.deliveredChunks+=1n,e.managedEmit(`message`,{data:t.data,type:`message`});return;case`payment-close-ready`:su(e,t.data);return;case`payment-error`:e.driver.rejectReceipt(Error(t.message)),e.driver.rejectCloseReady(Error(t.message));return;case`payment-need-voucher`:await cu(e,t.data);return;case`payment-receipt`:lu(e,t.data);return}}function su(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=nu({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,cumulativeAmount:n,receipt:t});if(r){e.failSocketFlow(r);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleCloseReady(t),e.managedEmit(`close`,{code:1e3,reason:`stream complete`,type:`close`,wasClean:!0})}async function cu(e,t){try{let n=e.driver.challenge;n.expires&&new Date(n.expires).getTime()<=Date.now()+5e3&&(n=await e.driver.refreshChallenge(),e.driver.challenge=n,e.socketState.challenge=n);let r=await kl({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:n,event:t,expectedChannelId:e.socketState.channelId,getChannel:e.driver.getChannel,input:e.driver.httpUrl,signal:e.driver.options?.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status===`ignored`){e.failSocketFlow(r.reason===`channel-mismatch`?`received mismatched payment-need-voucher frame`:`cannot create voucher: no active channel`);return}let i=await e.driver.createSessionCredential(n,r.context);e.rawSocket.send(ls(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function lu(e,t){let n=ru({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,expectedCloseAmount:e.socketState.expectedCloseAmount,receipt:t});if(n){e.failSocketFlow(n);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleReceipt(t)}function uu(e,t,n,r){let i=xt(e),a=new Headers;if(i.toLowerCase()!==V.authorization.toLowerCase()){let e=new Headers(r).get(V.authorization)??(n instanceof Request?n.headers.get(V.authorization):null);e&&!e.startsWith(`${Ke.payment} `)&&a.set(V.authorization,e)}return a.set(i,t),a}const du=new WeakMap;async function fu(e,t){let n=du.get(e)??new Map;du.set(e,n);let r=n.get(t),i,a=new Promise(e=>{i=e});return n.set(t,a),await r,()=>{i(),n.get(t)===a&&n.delete(t)}}function pu(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function mu(e,t,n){try{let r=e.response?.headers.get(V.paymentReceipt);if(r){let e=as(r);if(e.challengeId===t.id&&pu(n,e))return!0}}catch{}return e.challenges?.some(e=>jl(e)?pu(n,Ml(e)):!1)??!1}function hu(e){let{currencies:t,decimals:n,expectedRecipients:r,maxAmount:i,maxAtomicAmount:a}=e;if((i!==void 0||a!==void 0)&&t===void 0)throw Error(`Tempo session maxAmount and maxAtomicAmount require currencies.`);return{currencies:t?.map(e=>e.toLowerCase()),expectedRecipients:r?new Set(r.map(e=>e.toLowerCase())):void 0,maxAmount:gu(i,n),maxAtomicAmount:a===void 0?void 0:BigInt(a)}}function gu(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo session maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo session maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return m(e,t)}}function _u(e,t){if(e.currencies&&!e.currencies.includes(t.currency.toLowerCase()))throw Error(`Tempo session currency is not allowed: ${t.currency}.`);if(e.expectedRecipients&&(!t.recipient||!e.expectedRecipients.has(t.recipient.toLowerCase())))throw Error(`Unexpected session recipient: ${t.recipient}`);let n=BigInt(t.amount);if(e.maxAtomicAmount!==void 0&&n>e.maxAtomicAmount)throw Error(`Tempo session amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0&&n>e.maxAmount)throw Error(`Tempo session amount exceeds maxAmount.`)}function vu(e,t){try{return _u(e,t),!0}catch{return!1}}function yu(e){return typeof e==`object`&&!!e&&e.action===`close`}function bu(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a=6,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:f}=e,p=hu(e),h=Fa({chain:te,getClient:c,rpcUrl:Qn}),g=ja({account:t}),_=l===void 0?void 0:m(l,a),v=u===void 0?void 0:m(u,a),y=e.origin===void 0?void 0:new URL(e.origin);if(y&&![`http:`,`https:`].includes(y.protocol))throw Error(`Session origins require HTTP or HTTPS`);let b=i??Xs(),x={store:b,notifyUpdate:e=>d?.(e)},S=async(e,t,n)=>{let r=g(e.client,t),i=t?.action?t.descriptor:n?.descriptor??cl({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:ms(i)}:{}}})??r},C=async(e,t,n)=>fl({account:await S(e,t,n),entry:n,context:t,decimals:a,maxDeposit:_,resolved:e}),w=Bt(No,{canHandleChallenge:({challenge:e,context:t})=>jl(e)&&(yu(t)||t===Fr||vu(p,e.request)),context:Jc,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&_u(p,t.request);let a=await al({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:h}),c=Mi(e),l=Li(e)??y?.origin;if(l!==void 0&&(l===`null`||![`http:`,`https:`].includes(new URL(l).protocol)))throw Error(`Session payments require an HTTP or HTTPS origin`);if(y&&l!==y.origin)throw Error(`Session channel origin mismatch`);let u={...x,origin:l},d=()=>{};try{let e=!Yc(i)&&i?.descriptor===void 0;e&&(d=await fu(b,a.key),c&&(await b.get(a.key))?.opened&&await c.prepare());let n=await b.get(a.key);if(n&&n.origin!==l)throw Error(`Session channel origin mismatch`);if(l&&!n&&a.snapshot&&!i?.descriptor&&!y)throw Error(`Session snapshot recovery requires an explicitly configured origin or descriptor`);let o=await C(a,i,n);if(!e&&c&&o.type===`open`){d=await fu(b,a.key);let e=await b.get(a.key);if(e&&e.origin!==l)throw Error(`Session channel origin mismatch`);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await b.get(a.key)),o=await C(a,i,n))}let s,f=c&&o.type===`open`?{store:{get:e=>b.get(e),async set(e){s=l?{...e,origin:l}:e},delete:e=>b.delete(e)},notifyUpdate(){}}:u,p=await Us(t,await pl(o,f,Ka(i?.autoSwap??r,Wa)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||mu(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await b.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await nc(b,e),x.notifyUpdate(e))}return!0}finally{d()}}}else d();return p}catch(e){throw d(),e}}});function ee(e,t,n){let r={challenge:e,context:t};return Ii(r,xu(n)),w.createCredential(r)}let T=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>tc(b,Q(n),async()=>{s?.throwIfAborted();let c=await b.get(Q(n));if(c?.channelId===n.channelId&&(n=c),n.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let l=n.deposit>r?n.deposit:r,u=Dc({deposit:l,maxDeposit:_,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:v});u>0n&&await zl({autoSwap:e,additionalDeposit:u,challenge:t,channel:n,channelId:n.channelId,createSessionCredential:(e,t)=>ee(e,t,a),onUncertainFunding:async e=>{let t=await b.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await nc(b,n),x.notifyUpdate(n)},fetch:i,input:a,signal:s});let d=l+u;if(d===n.deposit)return;let f=await b.get(Q(n)),p=f?.channelId.toLowerCase()===n.channelId.toLowerCase()?f:n,m={...p,deposit:p.deposit>d?p.deposit:d};await nc(b,m),x.notifyUpdate(m)});return xi(w,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!jl(e))return;let c=t===void 0?void 0:Jc.parse(t);if(Yc(c))return;_u(p,e.request);let l=await al({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:h}),u=await b.get(l.key);if(!u?.opened)return;let d=xu(i);if(u.origin!==d)throw Error(`Session channel origin mismatch`);let f=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,m=u.cumulativeAmount+ns(e),g=f?BigInt(f.requiredCumulative):m,_=g>m?g:m,v=f?BigInt(f.deposit):u.deposit,y=v>u.deposit?v:u.deposit;_<=y&&y===u.deposit||!dl(await S(l,c,u),u.descriptor)||await T({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:y,fetch:r,input:i,requiredCumulative:_,signal:a})}),ki(w,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!jl(e))return u;if(!os(u))return ts(Dt(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await al({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:h})).key,p=await b.get(f),m={assertVoucherWithinLocalLimit:e=>Oc(e,_),createSessionCredential:(e,t)=>ee(e,t,c),fetch:i,getChannel:()=>p??null,async topUpIfNeeded({deposit:n,requiredCumulative:r,signal:a}){p&&await T({autoSwap:t===void 0?void 0:Jc.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return Xl({onNeedVoucher:(t,n)=>Zl({challenge:e,driver:m,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function xu(e){let t=new URL(e instanceof Request?e.url:e,globalThis.location===void 0?void 0:globalThis.location.href);if(![`http:`,`https:`].includes(t.protocol))throw Error(`Session payments require an HTTP or HTTPS origin`);return t.origin}const Su=new WeakMap;function Cu(e,t){Su.set(e,t)}function wu(e){let t=null;return{wait(n=()=>!0){if(t)throw Error(`${e} wait already in progress`);return new Promise((e,r)=>{t={predicate:n,resolve:e,reject:r}})},settle(e){if(!t||!t.predicate(e))return;let n=t;t=null,n.resolve(e)},reject(e){if(!t)return;let n=t;t=null,n.reject(e)}}}function Tu(e){let t=wu(`close-ready`),n=wu(`receipt`);return{waitForReceipt(e){return n.wait(e)},waitForCloseReady(){let n=e.getSocketSession()?.closeReadyReceipt;return n?Promise.resolve(n):t.wait()},settleReceipt(e){n.settle(e)},settleCloseReady(n){let r=e.getSocketSession();r&&r.challenge.id===n.challengeId&&r.channelId===n.channelId&&(r.closeReadyReceipt=n),t.settle(n)},rejectReceipt(e){n.reject(e)},rejectCloseReady(e){t.reject(e)}}}function Eu(e){return e.method===qe.tempo&&e.intent===Je.charge}function Du(e){if(!Eu(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Ou(e,t,n){if(!n)return t;let r={...Yi(Pl(e)?e.headers:void 0),...Yi(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===V.paymentSession.toLowerCase())?t:{...t,headers:{...r,[V.paymentSession]:n}}}function ku(e,t){return e===void 0?t:{...Jc.parse(e),...t}}function Au(e){let t=e.decimals??6,n=e.webSocket??globalThis.WebSocket;return{decimals:t,fetch:e.fetch??globalThis.fetch.bind(globalThis),maxVoucherCumulative:e.maxDeposit===void 0?null:m(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:m(e.topUpAmount,t),WebSocket:n}}function ju(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&La(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=Au(e),i;function a(e){let t=new URL(Pl(e)?e.url:String(e),typeof location>`u`?void 0:location.href);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`SessionManager: session payments require an HTTP origin`);let n=t.origin;if(i!==void 0&&i!==n)throw Error(`SessionManager: session payment origin mismatch`);return i=n,n}let o=_a(r.fetch),s=va(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??(Pl(e)?e.redirect:void 0))===`manual`?`manual`:`error`});if(r.url&&new URL(r.url).origin!==n)throw Error(`SessionManager: session response origin mismatch`);return r};let c=r.fetch;o&&(r.fetch=Mr(c,o));let l=Fa({chain:te,getClient:e.client?()=>e.client:e.getClient,rpcUrl:Qn}),u=ja({account:e.account}),d=Pc(),f=e.credentialContext===void 0?void 0:ku(e.credentialContext,{}),p=Tu({getSocketSession:()=>d.socketSession}),m=e.channelStore??Xs(),h=new Set,g;async function _(e){let t=await m.get(e);if(t?.opened&&!h.has(t.channelId)){if(t.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return t}}let v=e=>{if(e.origin!==void 0&&e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return e.origin=i,nc(m,e)},y={async get(e){let t=await _(e);return t&&g&&(g.seenExisting.add(e),!g.committed&&!g.created.has(e)&&(g.resumed??=t)),t},async set(e){let t=Q(e);e.opened&&h.delete(e.channelId),g?.trackCreates&&!g.seenExisting.has(t)&&g.created.set(t,e),await v(e)},delete:e=>rc(m,e)};$s(y,m);async function b(e){let t=Q(e),n=await m.get(t);if(e.uncertainTopUp||n?.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);h.add(e.channelId),g?.seenExisting.delete(t),g?.resumed===e&&(g.resumed=void 0),await Promise.resolve(rc(m,t)).catch(()=>void 0)}async function x(){let e=g;if(e?.created.size){for(let[t,n]of e.created){let e=await m.get(t);if(n.uncertainTopUp||e?.channelId===n.channelId&&e.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before discarding the channel.`);h.add(n.channelId),await Promise.resolve(rc(m,t)).catch(()=>void 0)}e.created.clear(),await z(e.committed??e.previous)}}function S(e){let t=Ze(e.request.methodDetails,Ye.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=g;if(!n?.created.size||!d.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&d.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=zc({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function C(e){return vc(d,e)}function w(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function ee(e){let t=g,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit&&!e.uncertainTopUp||(t.resumed=void 0,t.committed=zc({channel:d.channel,spent:d.spent,state:d.state}))}let T=bu({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:y,onChannelUpdate(e){e.channelId!==d.channel?.channelId&&(d.spent=0n),d.channel=e,d.lastChallenge&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),ee(e)}}),E=wi(T);E&&xi(T,e=>ie(()=>Promise.resolve(E(e)),e.signal)),Ai(T);let D=Io({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),O=Ji({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[T],onChallenge:async(e,t)=>{if(!Al(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&ct(e)===ct(d.lastChallenge);n&&n.challengesReceived++,!i&&(S(e)||(n?.created.size?await x():r&&await z(n.committed??n.previous)),d.lastChallenge=e,C({type:`challengeReceived`,challengeId:e.id}))}});function k(e,t){let n={challenge:e,context:ku(f,t)};return i&&Ii(n,i),T.createCredential(n)}function A(e){Fc({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:d})}function j(e=d.state.status===`active`?d.state.units:0){!d.channel||!d.lastChallenge||d.state.status!==`active`&&d.state.status!==`withdrawable`&&d.state.status!==`closeRequested`&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:d.channel,spent:d.spent.toString(),units:e})}async function M(t){let n=t.headers.get(V.paymentSessionSnapshot);if(!n)return;let r=mc(n);La(e.allowedChainIds,r.chainId);let i=await l({chainId:r.chainId});Ia(i,r.chainId);let a=u(i),{entry:o,spent:s}=await ul({account:await e.resolveAccount?.({account:a,chainId:r.chainId,operation:{authority:ms(r.descriptor),kind:`authorizePaymentChannel`}})??a,client:i,snapshot:r});return R(o.cumulativeAmount),await Promise.resolve(y.set(o)).catch(()=>void 0),d.channel=o,d.spent=s,o}async function N(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=Pl(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=Pl(t)?t.url:t,l={...s,method:`HEAD`,headers:{...Yi(i),...Yi(n?.headers),[V.acceptPayment]:`${qe.tempo}/${Je.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await M(t);let n=_t(t).find(Eu);if(!n||!Du(n))return;let i=new URL(String(c),typeof location<`u`?location.href:void 0);if(t.url&&new URL(t.url).origin!==i.origin)return;Ri(n,i,e.trustedTempoProofRealms);let a=await D.createCredential({challenge:n,context:{}}),o=await r.fetch(c,ni({...l,redirect:`manual`},xt(n),a));return o.ok?await M(o):void 0}catch{return}}function P(e,t){let n=d.socketSession;return Lc({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:d.channel?.channelId===t?d.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:d.spent,tickCost:n?.tickCost})}function F(e,t){let n=Ml(t);if(!n)return;if(hs({...n.descriptor,chainId:n.chainId,escrow:n.escrow}).toLowerCase()!==n.channelId.toLowerCase())throw Error(`close snapshot descriptor does not match its channel ID`);if(n.channelId.toLowerCase()!==e.channelId.toLowerCase())throw Error(`close snapshot channel ID does not match local session`);if(n.chainId!==e.chainId||n.escrow.toLowerCase()!==e.escrow.toLowerCase())throw Error(`close snapshot payment scope does not match local session`);let r=BigInt(n.acceptedCumulative),i=BigInt(n.spent);if(r<0n||i<0n)throw Error(`close snapshot amounts must not be negative`);if(i>r)throw Error(`close snapshot spent exceeds accepted cumulative amount`);if(r>e.cumulativeAmount)throw Error(`close snapshot accepted cumulative exceeds local voucher state`);return{acceptedCumulative:r,spent:i}}function I(e,t){let n=F(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(d.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>d.spent&&(d.spent=i),n}function L(e,t=e.challenge,n=!1){let r=(n?I(e,t):F(e.channel,t))?.acceptedCumulative??P(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return R(r),r.toString()}function R(e){Sc({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let ne,re;async function ie(e,t){if(re)throw re;for(;;){let e=ne;if(!e)break;if(!t)await e;else{t.throwIfAborted();let n;try{await Promise.race([e,new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0})})])}finally{t.removeEventListener(`abort`,n)}}}if(t?.throwIfAborted(),re)throw re;let n=e();ne=n;try{return await n}catch(e){throw e instanceof Rl&&(re=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{ne===n&&(ne=void 0)}}async function ae(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return tc(m,Q(d.channel),async()=>{let{knownDeposit:t,...n}=e,i=d.channel?await y.get(Q(d.channel)):void 0;if(i?.channelId===e.channelId&&i.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let a=await zl({...n,channel:d.channel,createSessionCredential:k,fetch:r.fetch,onUncertainFunding:async e=>{let t=await y.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};d.channel?.channelId===e.channelId&&(d.channel=n),await y.set(n),ee(n)}});A(a);let o=d.channel,s=Ol({additionalDeposit:e.additionalDeposit,channel:d.channel,channelId:e.channelId,challengeId:d.lastChallenge?.id,currentState:d.state,knownDeposit:t,receipt:a,spent:d.spent});if(s?.channel&&d.lastChallenge){let e=s.channel;for(;;){await y.set(e);let t=d.channel;if(t===o)break;if(!t)return a;let n=s.channel;e=t.channelId===n.channelId?{...t,deposit:t.deposit>n.deposit?t.deposit:n.deposit,cumulativeAmount:t.cumulativeAmount>n.cumulativeAmount?t.cumulativeAmount:n.cumulativeAmount}:t,o=t}if(e.channelId!==s.channel.channelId)return a;d.channel=e,C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),ee(e)}return a})}async function oe(e){return ie(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=Dc({deposit:n,maxDeposit:r.maxVoucherCumulative,requiredCumulative:e.requiredCumulative,suggestedDeposit:e.challenge.request.suggestedDeposit===void 0?void 0:BigInt(e.challenge.request.suggestedDeposit),topUpAmount:r.topUpAmount});i!==0n&&await ae({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function se(e,t){let n=Rc({channel:d.channel,channelId:e,challengeId:d.lastChallenge?.id,cumulativeAmount:t,spent:d.spent,state:d.state});n&&d.channel&&(C({type:`activated`,challengeId:n.challengeId,entry:d.channel,spent:n.spent,units:n.units}),await v(d.channel))}async function z(e){let t=Bc(e,d.channel);d.channel=t.channel,d.spent=t.spent,d.state=t.state,d.channel?.opened&&await v(d.channel)}function ce(e){let t=e.headers.get(V.paymentReceipt),n=t?as(t):null;return A(n),Object.assign(e,{receipt:n,challenge:d.lastChallenge,channelId:d.channel?.channelId??null,cumulative:d.channel?.cumulativeAmount??0n})}async function le(e,t){if(g)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);a(e),d.lastUrl=e,d.lastHeaders=t?.headers;let n=zc({channel:d.channel,spent:d.spent,state:d.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};g=i;try{await N(e,t),i.trackCreates=!0;let a=Ou(e,t,d.channel?.opened?d.channel.channelId:void 0);f&&(a={...a,context:f});let o=!n.channel?.opened;async function s(){let n=i.resumed;return!o||!n?!1:(o=!1,await b(n),a=Ou(e,t,void 0),!0)}for(;;){let t;try{t=await O(e,a)}catch(e){if(i.created.size?await x():await z(i.committed??n),await s())continue;throw e}let o=ce(t),c=!1;if(o.status===402){let t=await Vl({input:e,init:a,response:o,createSessionCredential:k,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:se,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:oe});t&&(c=!0,o=ce(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await x():await z(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function ue(e){let t=await Ul({createSessionCredential:k,fetch:r.fetch,getMinimumSpent:()=>d.spent,headers:d.lastHeaders,lastUrl:d.lastUrl,resolveSignedCloseAmount:t=>L(e,t,!0),signedCloseAmount:L(e),setChallenge(e){d.lastChallenge=e},target:e});return t&&(j(),C({type:`closeStarted`}),C({type:`closed`,receipt:t})),t}let de={createSessionCredential:k,doFetch:le,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:R,acceptReceipt(e){A(e)},topUpIfNeeded:oe},fe={get channelId(){return d.channel?.channelId},get cumulative(){return d.channel?.cumulativeAmount??0n},get opened(){return d.channel?.opened??!1},get state(){return d.state},fetch:le,async topUp(e){let t=Dl({amount:e,assertVoucherWithinLocalLimit:R,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return ie(async()=>{if(d.channel?.channelId!==t.channelId||d.lastChallenge!==t.challenge||d.lastUrl!==t.input)throw Error(`Session changed while waiting to top up`);let n=Dl({amount:e,assertVoucherWithinLocalLimit:R,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return ae({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){return Wl(e,t,de)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=Il(e);a(n);let i=t?.signal?{signal:t.signal}:void 0;await N(n,i);let o=d.channel?.opened?d.channel.channelId:void 0,{challenge:s,credential:c,httpUrl:l,wsUrl:u}=await $l({async createSessionCredential(e,i){return d.lastChallenge=e,await Ci(T,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),k(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){d.lastUrl=e.toString()},probeInit:Ou(n,i,o),signal:t?.signal});return d.lastChallenge=s,iu({challenge:s,credential:c,httpUrl:l,WebSocket:r.WebSocket,wsUrl:u,options:t,createSessionCredential:k,getChannel:()=>d.channel,setSocketSession(e){d.socketSession=e},async refreshChallenge(){let e=await Ql({fetch:r.fetch,input:l,probeInit:Ou(l,i,d.channel?.opened?d.channel.channelId:void 0),signal:t?.signal});return d.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:R,acceptReceipt:A,rejectCloseReady:p.rejectCloseReady,rejectReceipt:p.rejectReceipt,settleCloseReady:p.settleCloseReady,settleReceipt:p.settleReceipt,topUpIfNeeded:oe,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=kc({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===wl.OPEN){let r=await Vc({activeSocket:n,createSessionCredential:k,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return j(),C({type:`closeStarted`}),C({type:`closed`,receipt:r}),r}return ue(t)}};return Cu(fe,{consumeSseResponse(e,t,n){let r=a(e);if(t.url&&new URL(t.url).origin!==r)throw Error(`SessionManager: session response origin mismatch`);return Gl(e,t,n,de)},rehydrate({channel:e,challenge:t,input:n,spent:r}){let i=a(n);if(e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!Al(t))throw Error(`Cannot restore session: challenge is not tempo/session.`);if(r<0n)throw Error(`Cannot restore session: spent must not be negative.`);if(r>e.cumulativeAmount)throw Error(`Cannot restore session: spent exceeds local voucher state.`);R(e.cumulativeAmount);let o=F(e,t),s=o&&o.spent>r?o.spent:r;d.lastUrl=n,d.lastChallenge=t,d.channel=e,d.spent=s,C({type:`challengeReceived`,challengeId:t.id}),C({type:`activated`,challengeId:t.id,entry:e,spent:s.toString(),units:0})}}),fe}(function(e){e.serializeSnapshot=pc,e.deserializeSnapshot=mc})(ju||={});const Mu=(1n<<64n)-1n,Nu={dev_second:1n,day:86400n,week:604800n};function Pu(e){return e instanceof Date?e:new Date(e)}function Fu(e){let t=e.getTime();if(!Number.isFinite(t))throw new Y({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new Y({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new Y({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function Iu(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new Y({reason:`periodCount is invalid`});let t=Nu[e.periodUnit];if(t===void 0)throw new Y({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>Mu)throw new Y({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new Y({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function Lu(e){let{challengeExpires:t,request:n}=e;Iu(n);let r=Fu(Pu(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new Y({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function Ru(e){return[{address:Zu(e.currency,`currency`),selector:`0x95777d59`,recipients:[Zu(e.recipient,`recipient`)]}]}function zu(e){try{let t=A.fromBytes(D.toBytes(e));if(A.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new Y({reason:`challenge id must encode 32 bytes`})}}async function Bu(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=Hu({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:he.getSignPayload(o)}),c=B.from(s);if(c.type===`keychain`||c.type===`multisig`)throw new Y({reason:`keyAuthorization must use a primitive signature`});return he.from(o,{signature:s})}function Vu(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new Y({reason:`invalid keyAuthorization payload`});let o=Uu(i.signature),s=Wu(o);if(Gu({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==zu(n))throw new Y({reason:`keyAuthorization challenge mismatch`});return Ku(o,a),Ju(qu(o),a),Yu(o.scopes,a),{authorization:o,source:{address:Xu(o,s),chainId:r}}}function Hu(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return he.from({address:Zu(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:Fu(Pu(i.subscriptionExpires)),limits:[{token:Zu(i.currency,`currency`),limit:BigInt(i.amount),period:Iu(i)}],scopes:Ru(i),type:t.keyType,witness:zu(n)})}function Uu(e){try{return he.deserialize(e)}catch(e){throw e instanceof he.InvalidSignatureTypeError?new Y({reason:`keyAuthorization must use a primitive signature`}):new Y({reason:`invalid keyAuthorization payload`})}}function Wu(e){let t=e.signature;if(!t)throw new Y({reason:`keyAuthorization must use a primitive signature`});return t}function Gu(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new Y({reason:`keyAuthorization chainId mismatch`});if(t){if(!u(n.address,Zu(t.accessKeyAddress,`accessKeyAddress`)))throw new Y({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new Y({reason:`keyAuthorization key type mismatch`})}}function Ku(e,t){if(Lu({request:t}),e.expiry!==Fu(Pu(t.subscriptionExpires)))throw new Y({reason:`keyAuthorization expiry mismatch`})}function qu(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new Y({reason:`keyAuthorization must contain exactly one token limit`});return t}function Ju(e,t){if(!u(e.token,Zu(t.currency,`currency`)))throw new Y({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new Y({reason:`keyAuthorization amount mismatch`});if(e.period!==Iu(t))throw new Y({reason:`keyAuthorization period mismatch`})}function Yu(e,t){if(!e||e.length!==1)throw new Y({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=Zu(t.currency,`currency`),r=Zu(t.recipient,`recipient`),i=new Set;for(let t of e){if(!u(t.address,n))throw new Y({reason:`keyAuthorization call target mismatch`});let e=Qu(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new Y({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new Y({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!u(t.recipients[0],r))throw new Y({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new Y({reason:`keyAuthorization must allow transferWithMemo`})}function Xu(e,t){let n=he.getSignPayload(e);try{let e=B.extractAddress({payload:n,signature:t});if(!B.verify(t,{address:e,payload:n}))throw new Y({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof Y?e:new Y({reason:`keyAuthorization signature is invalid`})}}function Zu(e,t){if(!l(e))throw new Y({reason:`${t} must be an address`});return e.toLowerCase()}function Qu(e){return typeof e==`string`?e.toLowerCase():``}const $u=U.object({accessKey:U.optional(U.custom()),account:U.optional(U.custom())});function ed(e={}){let t=Fa({chain:R,getClient:e.getClient,rpcUrl:Qn}),n=ja({account:e.account});return Bt(Po,{context:$u,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??X.testnet,o=await t({chainId:a}),s=n(o,i),c=i?.accessKey??e.accessKey??r.request.methodDetails?.accessKey;if(!c)throw Error("No `accessKey` provided. The subscription challenge must include `accessKey`, or the client must pass one to parameters/context.");nd(r.request),await e.validateRequest?.(r.request);let l=await td(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),d=Vu({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:he.serialize(l),type:`keyAuthorization`},request:r.request});if(!u(d.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return jt({challenge:r,payload:{signature:he.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function td(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await Bu({accessKey:n,account:r,challengeId:i,chainId:a,request:o});if(s)return s;let c=await e.request({method:`wallet_authorizeAccessKey`,params:[{address:n.accessKeyAddress,expiry:Fu(Pu(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:A.fromNumber(BigInt(o.amount)),period:Iu(o)}],scopes:Ru(o),witness:zu(i)}]});return he.fromRpc(c.keyAuthorization)}function nd(e){Iu(e),Fu(Pu(e.subscriptionExpires))}const rd=Object.assign(bu,{manager:ju});function id(e={}){let t=e.expectedChainId!==void 0&&(e.allowedChainIds===void 0||e.allowedChainIds.includes(e.expectedChainId)),n=e.expectedChainId===void 0?e:{...e,allowedChainIds:t?[e.expectedChainId]:[]};return[Io(e),rd(n)]}(function(e){e.charge=Io,e.common=id,e.session=rd,e.subscription=ed})(id||={});const ad=L.union([L.boolean(),L.literal(`true`).transform(()=>!0),L.literal(`false`).transform(()=>!1)]);async function od(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}const sd=L.object({allowCustomEscrow:L.optional(ad),autoSwap:L.optional(ad),channel:L.optional(L.coerce.string()),deposit:L.optional(L.union([L.string(),L.number()])),payWith:L.optional(L.string()),slippage:L.optional(L.coerce.number()),tokenIn:L.optional(L.string())}),cd=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`];function ld(){let t;return vr({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:n,options:r,methodOpts:i}){let a=mr(r.account),o=n.request,s=o.currency,l=hd(i),u=yd({autoSwap:l.autoSwap??r.autoSwap,payWith:l.payWith??r.payWith,slippage:l.slippage??r.slippage,tokenIn:l.tokenIn}),d=s??``,f=o.decimals??6,p,m,h,g=!1,_=process.env.MPPX_PRIVATE_KEY?.trim()||(er(a)?void 0:await hr(a).get());if(!_&&er(a)&&Od()){g=!0;let t=Ed(a);if(t){let i=rr(r.rpcUrl,{network:r.network});h=e({chain:await ir({network:r.network,rpcUrl:i}),transport:c(i)}),_d({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let a=s?await sr(h,s,t.wallet_address).catch(()=>void 0):void 0;d=a?.symbol??s??``,f=a?.decimals??o.decimals??6}}else if(_)m=pe(_);else{let e=Ad();if(e){let t=await hr(e).get();t&&(m=pe(t))}if(!m)throw r.account?new qn({code:`ACCOUNT_NOT_FOUND`,message:`Account "${a}" not found.`,exitCode:69}):new qn({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!g&&m){let t=rr(r.rpcUrl,{network:r.network});h=e({chain:await ir({network:r.network,rpcUrl:t}),transport:c(t)}),_d({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let i=s?await sr(h,s,m.address).catch(()=>void 0):void 0;d=i?.symbol??s??``,f=i?.decimals??o.decimals??6}if(g)return{tokenSymbol:d,tokenDecimals:f,explorerUrl:p,methods:[],async createCredential(e){let t=e.headers.get(`www-authenticate`);if(!t)throw Error(`No WWW-Authenticate header in 402 response.`);return kd(t)}};if(!m||!h)throw new qn({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let v=id({account:m,...l.allowCustomEscrow===void 0?{}:{allowCustomEscrow:l.allowCustomEscrow},getClient:()=>h,...u===void 0?{}:{autoSwap:u},maxDeposit:(()=>{if(n.intent!==`session`)return;let e=n.request.suggestedDeposit,t=(l.deposit===void 0?void 0:String(l.deposit))??e??(or(h.chain)?`10`:void 0);if(!t)throw new qn({code:`MISSING_DEPOSIT`,message:`Session payment requires a deposit. Use -M deposit=<amount> or connect to testnet.`,exitCode:2});return t})()}),y=(()=>{if(!l.channel)return;let e=l.channel,t=xd(e);return{channelId:e,...t!==void 0&&{cumulativeAmountRaw:t.toString()}}})();return t={descriptor:void 0,async signVoucher({channelId:e,cumulativeAmount:r,escrowContract:i,chainId:a,action:o=`voucher`}){let s=t?.descriptor;if(!s)throw Error(`session descriptor not available`);let c={channelId:e,cumulativeAmount:r},l=await Ms(h,m,c,i,a);return jt({challenge:n,payload:{action:o,channelId:e,...o===`close`?{closeSignature:await Ns(h,m,c,i,a)}:{},descriptor:s,cumulativeAmount:r.toString(),signature:l},source:`did:pkh:eip155:${a}:${m.address}`})},source:`did:pkh:eip155:${h.chain.id}:${m.address}`},{tokenSymbol:d,tokenDecimals:f,explorerUrl:p,methods:[...v],credentialContext:y}},prepareCredentialRequest({challenge:e,headers:t}){e.intent===`session`&&(t.Accept=`text/event-stream`)},async handleResponse(e){if(e.challenge.intent!==`session`||!t)return!1;let{challenge:n,credential:r,response:i,fetchUrl:a,fetchInit:o,verbose:s}=e,{silent:c,confirmEnabled:l,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,shownKeys:p}=e,m=c?e=>{}:e=>process.stderr.write(e),h=Dt(r),g=n.request,_=g.methodDetails,v=h.payload.channelId,y=_?.escrowContract??_?.escrow??`0x4d50500000000000000000000000000000000000`,b=_?.chainId??0,x=BigInt(g.amount),S=`cumulativeAmount`in h.payload&&h.payload.cumulativeAmount?BigInt(h.payload.cumulativeAmount):0n;if(`descriptor`in h.payload&&(t.descriptor=h.payload.descriptor),s>=1){if(h.payload.action===`open`){let e=g.suggestedDeposit,t=e?` ${Z.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
9
13
  `}${Z.dim(`Channel opened ${h.payload.channelId}`)}${t}\n`)}else m(`${l?``:`
10
- `}${Z.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let w=i;w.ok&&!w.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let T=w.headers.get(B.paymentReceipt);if(T)try{let e=JSON.parse(C.toString(T));Uu(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&ed(v,S),s>=1&&Hu(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
11
- `})}catch{}return(w.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await Wu(w,{challenge:n,channelId:v,escrowContract:y,chainId:b,cumulativeAmount:S,tickCost:x,fetchUrl:a,fetchInit:o,session:t,info:m,verbose:s,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this}):(await Ru(w),v&&y&&b&&(l&&m(`
12
- `),l&&!await e.confirm(`Close channel?`,!0)?s>=1&&m(`${Z.dim(`Kept channel open.`)}\n`):await Gu({channelId:v,cumulativeAmount:S,escrowContract:y,chainId:b,fetchUrl:a,fetchInit:o,session:t,info:m,verbose:s,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,confirmEnabled:l}))),!0},formatReceiptField(e,t){(e===`reference`||e===`txHash`)&&typeof t==`string`&&t.startsWith(`0x`)}})}function Hu(e,t){t.info(`${t.prefix??``}${Z.bold(Z.green(`Payment Receipt`))}\n`);let n=[],r=e.channelId&&e.reference&&e.channelId===e.reference,i=new Set([`acceptedCumulative`,`spent`]);for(let[a,o]of Object.entries(e)){if(o===void 0||t.shownKeys.has(a)||a===`reference`&&r)continue;let e=t.handler.formatReceiptField?.(a,o);e===void 0?i.has(a)&&typeof o==`string`?n.push([a,`${o} ${Z.dim(`(${Jn(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,Kn(`${t.explorerUrl}/tx/${o}`,o)]):n.push([a,String(o)]):n.push([a,e])}n.sort(([e],[t])=>e.localeCompare(t));let a=Math.max(...n.map(([e])=>e.length));for(let[e,r]of n)t.info(` ${Z.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
13
- `)}function Uu(e,t){if(typeof e.acceptedCumulative!=`string`)return;let n=BigInt(e.acceptedCumulative),r=typeof e.spent==`string`?BigInt(e.spent):0n;if(r>n)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(n>t)throw Error(`receipt accepted cumulative exceeds locally signed voucher amount`);if(r>t)throw Error(`receipt spent exceeds locally signed voucher amount`)}async function Wu(e,t){let n=t.cumulativeAmount,r=e.body?.getReader();if(!r)throw Error(`No response body`);let i=new TextDecoder,a=``,o=``,s=t.verbose?await Ku():void 0,c=(()=>{if(!s||!Z.isColorSupported)return;let e=e=>Math.max(0,Math.min(255,Math.round(e))),t=.299*s.r+.587*s.g+.114*s.b<128?1:-1,n=n=>r=>`\x1b[48;2;${e(s.r+n*t)};${e(s.g+n*t)};${e(s.b+n*t)}m${r}\x1b[49m`;return[n(12),n(24)]})(),l=0,u=e=>{if(c){let t=c[l%c.length];process.stdout.write(e.replace(/[^\n]+/g,e=>t(e))),l++}else process.stdout.write(e)},d=async e=>{for(let r of e){if(r.startsWith(`event: `)){o=r.slice(7).trim();continue}if(!r.startsWith(`data: `)){r===``&&(o=``);continue}let e=r.slice(6);if(e.trim()!==`[DONE]`){if(o===`payment-need-voucher`&&t.channelId&&t.escrowContract&&t.chainId){try{let r=JSON.parse(e);if(r.channelId!==t.channelId)throw Error(`payment-need-voucher channelId does not match current session`);let i=BigInt(r.requiredCumulative);if(i>n+t.tickCost)throw Error(`payment-need-voucher exceeds next locally billable amount`);n=n>i?n:i;let a=await t.session.signVoucher({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId});await globalThis.fetch(t.fetchUrl,{method:`POST`,headers:{[B.authorization]:a}})}catch(e){t.info(Z.dim(Z.yellow(` [voucher failed: ${e instanceof Error?e.message:e}]`)))}o=``;continue}if(o===`payment-receipt`){if(t.verbose>=1)try{Hu(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
14
+ `}${Z.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let C=i;C.ok&&!C.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let w=C.headers.get(V.paymentReceipt);if(w)try{let e=JSON.parse(D.toString(w));dd(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&Sd(v,S),s>=1&&ud(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
15
+ `})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await fd(C,{challenge:n,channelId:v,escrowContract:y,chainId:b,cumulativeAmount:S,tickCost:x,fetchUrl:a,fetchInit:o,session:t,info:m,verbose:s,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this}):(await od(C),v&&y&&b&&(l&&m(`
16
+ `),l&&!await e.confirm(`Close channel?`,!0)?s>=1&&m(`${Z.dim(`Kept channel open.`)}\n`):await pd({channelId:v,cumulativeAmount:S,escrowContract:y,chainId:b,fetchUrl:a,fetchInit:o,session:t,info:m,verbose:s,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,confirmEnabled:l}))),!0},formatReceiptField(e,t){(e===`reference`||e===`txHash`)&&typeof t==`string`&&t.startsWith(`0x`)}})}function ud(e,t){t.info(`${t.prefix??``}${Z.bold(Z.green(`Payment Receipt`))}\n`);let n=[],r=e.channelId&&e.reference&&e.channelId===e.reference,i=new Set([`acceptedCumulative`,`spent`]);for(let[a,o]of Object.entries(e)){if(o===void 0||t.shownKeys.has(a)||a===`reference`&&r)continue;let e=t.handler.formatReceiptField?.(a,o);e===void 0?i.has(a)&&typeof o==`string`?n.push([a,`${o} ${Z.dim(`(${tr(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,$n(`${t.explorerUrl}/tx/${o}`,o)]):n.push([a,String(o)]):n.push([a,e])}n.sort(([e],[t])=>e.localeCompare(t));let a=Math.max(...n.map(([e])=>e.length));for(let[e,r]of n)t.info(` ${Z.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
17
+ `)}function dd(e,t){if(typeof e.acceptedCumulative!=`string`)return;let n=BigInt(e.acceptedCumulative),r=typeof e.spent==`string`?BigInt(e.spent):0n;if(r>n)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(n>t)throw Error(`receipt accepted cumulative exceeds locally signed voucher amount`);if(r>t)throw Error(`receipt spent exceeds locally signed voucher amount`)}async function fd(e,t){let n=t.cumulativeAmount,r=e.body?.getReader();if(!r)throw Error(`No response body`);let i=new TextDecoder,a=``,o=``,s=t.verbose?await md():void 0,c=(()=>{if(!s||!Z.isColorSupported)return;let e=e=>Math.max(0,Math.min(255,Math.round(e))),t=.299*s.r+.587*s.g+.114*s.b<128?1:-1,n=n=>r=>`\x1b[48;2;${e(s.r+n*t)};${e(s.g+n*t)};${e(s.b+n*t)}m${r}\x1b[49m`;return[n(12),n(24)]})(),l=0,u=e=>{if(c){let t=c[l%c.length];process.stdout.write(e.replace(/[^\n]+/g,e=>t(e))),l++}else process.stdout.write(e)},d=async e=>{for(let r of e){if(r.startsWith(`event: `)){o=r.slice(7).trim();continue}if(!r.startsWith(`data: `)){r===``&&(o=``);continue}let e=r.slice(6);if(e.trim()!==`[DONE]`){if(o===`payment-need-voucher`&&t.channelId&&t.escrowContract&&t.chainId){try{let r=JSON.parse(e);if(r.channelId!==t.channelId)throw Error(`payment-need-voucher channelId does not match current session`);let i=BigInt(r.requiredCumulative);if(i>n+t.tickCost)throw Error(`payment-need-voucher exceeds next locally billable amount`);n=n>i?n:i;let a=await t.session.signVoucher({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId});await globalThis.fetch(t.fetchUrl,{method:`POST`,headers:{[V.authorization]:a}})}catch(e){t.info(Z.dim(Z.yellow(` [voucher failed: ${e instanceof Error?e.message:e}]`)))}o=``;continue}if(o===`payment-receipt`){if(t.verbose>=1)try{ud(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
14
18
 
15
19
  `})}catch{}o=``;continue}if(e.length===0)u(`
16
20
  `);else try{let t=JSON.parse(e);u(t.token??t.choices?.[0]?.delta?.content??e)}catch{u(e)}o=``}}};for(;;){let{done:e,value:t}=await r.read();if(e)break;a+=i.decode(t,{stream:!0});let n=a.split(`
17
- `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await Gu({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId,fetchUrl:t.fetchUrl,fetchInit:t.fetchInit,session:t.session,info:t.info,verbose:t.verbose,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,confirmEnabled:!1})}async function Gu(e){let t=await e.session.signVoucher({channelId:e.channelId,cumulativeAmount:e.cumulativeAmount,escrowContract:e.escrowContract,chainId:e.chainId,action:`close`}),n=await globalThis.fetch(e.fetchUrl,{...e.fetchInit,headers:{...Hi(e.fetchInit.headers),Authorization:t}});if(n.ok){if(td(e.channelId),e.verbose>=1){let t=n.headers.get(B.paymentReceipt),r;if(t)try{let e=JSON.parse(C.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${Z.dim(Kn(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${Z.dim(`Channel closed.`)} ${Z.dim(`Spent ${Jn(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${Z.dim(Z.yellow(`Channel close failed`))} ${Z.dim(`(${n.status})`)}\n`),e.info(`${Z.dim(` channelId: ${e.channelId}`)}\n${Z.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${Z.dim(` escrowContract: ${e.escrowContract}`)}\n${Z.dim(` chainId: ${e.chainId}`)}\n${Z.dim(` response: ${t||`(empty)`}`)}\n`)}}function Ku(e=100){return!process.stdin.isTTY||!process.stdout.isTTY?Promise.resolve(void 0):new Promise(t=>{let n=process.stdin.isRaw,r=``,i=()=>{clearTimeout(a),process.stdin.removeListener(`data`,o),process.stdin.isTTY&&process.stdin.setRawMode(n??!1),process.stdin.pause()},a=setTimeout(()=>{i(),t(void 0)},e),o=e=>{r+=e.toString();let n=r.match(/\x1b\]11;rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!n)return;i();let a=e=>Number.parseInt(e.slice(0,2),16);t({r:a(n[1]),g:a(n[2]),b:a(n[3])})};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on(`data`,o),process.stdout.write(`\x1B]11;?\x07`)})}function qu(e){return Ju(zu,e,Bu)}function Ju(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function Yu(e){let t=e.challenge.request.methodDetails?.chainId;if(!t||!e.clientChainId||t===e.clientChainId)return;let n=t===4217?` Use --network mainnet or --rpc-url https://rpc.tempo.xyz.`:t===42431?` Use --network testnet or --rpc-url https://rpc.moderato.tempo.xyz.`:``;throw new Bn({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function Xu(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function Zu(e){let t=Xu(e.tokenIn)??Xu(e.payWith);if(!(!e.autoSwap&&!t&&e.slippage===void 0)){if(e.autoSwap===!1&&!t&&e.slippage===void 0)return!1;if(e.slippage!==void 0&&(!Number.isFinite(e.slippage)||e.slippage<0))throw Error(`Invalid CLI options (slippage: expected a non-negative number)`);return{...t?{tokenIn:t}:{},...e.slippage===void 0?{}:{slippage:e.slippage}}}}function Qu(){return M.join(process.env.XDG_CONFIG_HOME||M.join(j.homedir(),`.config`),`mppx`,`channels`)}function $u(e){try{let t=A.readFileSync(M.join(Qu(),e),`utf-8`).trim();return t?BigInt(t):void 0}catch{return}}function ed(e,t){let n=Qu();A.mkdirSync(n,{recursive:!0}),A.writeFileSync(M.join(n,e),t.toString(),`utf-8`)}function td(e){try{A.unlinkSync(M.join(Qu(),e))}catch{}}function nd(){return j.platform()===`darwin`?M.join(j.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):M.join(process.env.XDG_DATA_HOME||M.join(j.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function rd(){try{let e=A.readFileSync(nd(),`utf-8`),t=[],n;for(let r of e.split(`
18
- `)){let e=r.trim();if(e===`[[keys]]`){n?.wallet_address&&t.push(n),n={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!n)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?n.wallet_type=o:a===`wallet_address`?n.wallet_address=o:a===`chain_id`&&(n.chain_id=Number.parseInt(o,10))}return n?.wallet_address&&t.push(n),t}catch{return[]}}function id(e){let t=rd();if(t.length===0)return;let n=e.slice(6);if(n==="default"||n===``)return t[0];let r=Number.parseInt(n,10);if(!Number.isNaN(r)&&r>=0&&r<t.length)return t[r]}let ad;function od(){if(ad!==void 0)return ad;try{k.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),ad=!0}catch{ad=!1}return ad}async function sd(e){return new Promise((t,n)=>{k.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function cd(){let e=or();if(qn(e.get())&&!od()&&j.platform()===`darwin`)try{let t=k.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===`mppx`&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}const ld=[...Object.entries(Ce),...Object.entries(we),...Object.entries(Te),...Object.entries(Ee)];function ud(){return dr({method:`evm`,supports:dd,async setup({challenge:e,options:t}){let n=e.request,r=n.network?fd(Ne(n.network)):void 0,i=n.network&&n.asset?ld.find(([,e])=>je(e,n.asset,n.network)):void 0,a=n.extra?.name,o=n.extra?.version,s=n.asset&&n.network&&typeof a==`string`&&typeof o==`string`?xe({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await ur(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...Rn({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function dd(e){if(!xn(e))return!1;let t=e.request,n=t.extra,r=n?.assetTransferMethod;return t.scheme===`exact`&&typeof t.asset==`string`&&typeof t.network==`string`&&typeof n?.name==`string`&&typeof n?.version==`string`&&(r===void 0||r===`eip3009`)}function fd(e){return Object.values(b).find(t=>t.id===e)}export{dr as createPlugin,fr as evm,xr as stripe,Vu as tempo,ud as x402};
21
+ `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await pd({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId,fetchUrl:t.fetchUrl,fetchInit:t.fetchInit,session:t.session,info:t.info,verbose:t.verbose,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,confirmEnabled:!1})}async function pd(e){let t=await e.session.signVoucher({channelId:e.channelId,cumulativeAmount:e.cumulativeAmount,escrowContract:e.escrowContract,chainId:e.chainId,action:`close`}),n=await globalThis.fetch(e.fetchUrl,{...e.fetchInit,headers:{...Yi(e.fetchInit.headers),Authorization:t}});if(n.ok){if(Cd(e.channelId),e.verbose>=1){let t=n.headers.get(V.paymentReceipt),r;if(t)try{let e=JSON.parse(D.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${Z.dim($n(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${Z.dim(`Channel closed.`)} ${Z.dim(`Spent ${tr(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${Z.dim(Z.yellow(`Channel close failed`))} ${Z.dim(`(${n.status})`)}\n`),e.info(`${Z.dim(` channelId: ${e.channelId}`)}\n${Z.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${Z.dim(` escrowContract: ${e.escrowContract}`)}\n${Z.dim(` chainId: ${e.chainId}`)}\n${Z.dim(` response: ${t||`(empty)`}`)}\n`)}}function md(e=100){return!process.stdin.isTTY||!process.stdout.isTTY?Promise.resolve(void 0):new Promise(t=>{let n=process.stdin.isRaw,r=``,i=()=>{clearTimeout(a),process.stdin.removeListener(`data`,o),process.stdin.isTTY&&process.stdin.setRawMode(n??!1),process.stdin.pause()},a=setTimeout(()=>{i(),t(void 0)},e),o=e=>{r+=e.toString();let n=r.match(/\x1b\]11;rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!n)return;i();let a=e=>Number.parseInt(e.slice(0,2),16);t({r:a(n[1]),g:a(n[2]),b:a(n[3])})};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on(`data`,o),process.stdout.write(`\x1B]11;?\x07`)})}function hd(e){return gd(sd,e,cd)}function gd(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function _d(e){let t=e.challenge.request.methodDetails?.chainId;if(!t||!e.clientChainId||t===e.clientChainId)return;let n=t===4217?` Use --network mainnet or --rpc-url https://rpc.tempo.xyz.`:t===42431?` Use --network testnet or --rpc-url https://rpc.moderato.tempo.xyz.`:``;throw new qn({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function vd(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function yd(e){let t=vd(e.tokenIn)??vd(e.payWith);if(!(!e.autoSwap&&!t&&e.slippage===void 0)){if(e.autoSwap===!1&&!t&&e.slippage===void 0)return!1;if(e.slippage!==void 0&&(!Number.isFinite(e.slippage)||e.slippage<0))throw Error(`Invalid CLI options (slippage: expected a non-negative number)`);return{...t?{tokenIn:t}:{},...e.slippage===void 0?{}:{slippage:e.slippage}}}}function bd(){return I.join(process.env.XDG_CONFIG_HOME||I.join(F.homedir(),`.config`),`mppx`,`channels`)}function xd(e){try{let t=P.readFileSync(I.join(bd(),e),`utf-8`).trim();return t?BigInt(t):void 0}catch{return}}function Sd(e,t){let n=bd();P.mkdirSync(n,{recursive:!0}),P.writeFileSync(I.join(n,e),t.toString(),`utf-8`)}function Cd(e){try{P.unlinkSync(I.join(bd(),e))}catch{}}function wd(){return F.platform()===`darwin`?I.join(F.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):I.join(process.env.XDG_DATA_HOME||I.join(F.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function Td(){try{let e=P.readFileSync(wd(),`utf-8`),t=[],n;for(let r of e.split(`
22
+ `)){let e=r.trim();if(e===`[[keys]]`){n?.wallet_address&&t.push(n),n={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!n)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?n.wallet_type=o:a===`wallet_address`?n.wallet_address=o:a===`chain_id`&&(n.chain_id=Number.parseInt(o,10))}return n?.wallet_address&&t.push(n),t}catch{return[]}}function Ed(e){let t=Td();if(t.length===0)return;let n=e.slice(6);if(n==="default"||n===``)return t[0];let r=Number.parseInt(n,10);if(!Number.isNaN(r)&&r>=0&&r<t.length)return t[r]}let Dd;function Od(){if(Dd!==void 0)return Dd;try{N.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),Dd=!0}catch{Dd=!1}return Dd}async function kd(e){return new Promise((t,n)=>{N.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function Ad(){let e=pr();if(er(e.get())&&!Od()&&F.platform()===`darwin`)try{let t=N.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===`mppx`&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}const jd=[...Object.entries(Oe),...Object.entries(ke),...Object.entries(Ae),...Object.entries(je)];function Md(){return vr({method:`evm`,supports:Nd,async setup({challenge:e,options:t}){let n=e.request,r=n.network?Pd(Re(n.network)):void 0,i=n.network&&n.asset?jd.find(([,e])=>Ie(e,n.asset,n.network)):void 0,a=n.extra?.name,o=n.extra?.version,s=n.asset&&n.network&&typeof a==`string`&&typeof o==`string`?Ee({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await _r(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...Gn({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function Nd(e){if(!On(e))return!1;let t=e.request,n=t.extra,r=n?.assetTransferMethod;return t.scheme===`exact`&&typeof t.asset==`string`&&typeof t.network==`string`&&typeof n?.name==`string`&&typeof n?.version==`string`&&(r===void 0||r===`eip3009`)}function Pd(e){return Object.values(T).find(t=>t.id===e)}export{vr as createPlugin,yr as evm,Or as stripe,ld as tempo,Md as x402};