mppx 0.12.0 → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +55 -0
- package/dist/Method.d.ts +7 -1
- package/dist/Method.js +7 -2
- package/dist/Receipt.d.ts +2 -0
- package/dist/Receipt.js +2 -0
- package/dist/cli/cli.d.ts +8 -0
- package/dist/cli/cli.js +134 -136
- package/dist/cli/plugins/index.js +12 -14
- package/dist/cli/plugins/tempo.js +9 -2
- package/dist/cli/utils.d.ts +11 -1
- package/dist/cli/utils.js +15 -2
- package/dist/cli/validate/challenge.d.ts +2 -0
- package/dist/cli/validate/challenge.js +19 -4
- package/dist/cli/validate/discovery.d.ts +1 -0
- package/dist/cli/validate/discovery.js +10 -1
- package/dist/cli/validate/payment.js +34 -12
- package/dist/client/Methods.d.ts +0 -2
- package/dist/client/Methods.js +0 -2
- package/dist/client/Mppx.js +1 -0
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.js +1 -1
- package/dist/client/internal/Fetch.d.ts +2 -0
- package/dist/client/internal/Fetch.js +8 -2
- package/dist/client/internal/MethodChallenge.d.ts +1 -0
- package/dist/evm/Types.js +1 -1
- package/dist/evm/server/Charge.js +5 -0
- package/dist/integrations/x402/Evm.js +4 -3
- package/dist/internal/HeaderCodec.d.ts +2 -2
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- package/dist/mcp/client/McpClient.js +4 -7
- package/dist/middlewares/elysia.d.ts +11 -8
- package/dist/middlewares/elysia.js +67 -14
- package/dist/middlewares/express.js +13 -6
- package/dist/middlewares/hono.js +4 -4
- package/dist/middlewares/nextjs.js +9 -5
- package/dist/proxy/internal/Headers.js +65 -0
- package/dist/proxy/services/stripe.js +1 -0
- package/dist/server/Mppx.d.ts +13 -1
- package/dist/server/Mppx.js +85 -44
- package/dist/server/NodeListener.js +71 -6
- package/dist/server/Request.d.ts +11 -1
- package/dist/server/Request.js +132 -13
- package/dist/server/Transport.d.ts +14 -1
- package/dist/server/Transport.js +1 -0
- package/dist/stripe/server/Methods.d.ts +10 -3
- package/dist/stripe/server/Methods.js +17 -2
- package/dist/stripe/server/internal/html.gen.js +1 -1
- package/dist/tempo/Methods.d.ts +1 -0
- package/dist/tempo/Methods.js +1 -0
- package/dist/tempo/client/Charge.js +17 -13
- package/dist/tempo/client/Methods.d.ts +1 -5
- package/dist/tempo/client/Methods.js +10 -5
- package/dist/tempo/client/ResolveAccount.d.ts +3 -0
- package/dist/tempo/client/index.d.ts +0 -3
- package/dist/tempo/client/index.js +0 -2
- package/dist/tempo/internal/fee-payer.d.ts +6 -3
- package/dist/tempo/internal/fee-payer.js +23 -6
- package/dist/tempo/internal/machine-token-charge.d.ts +23 -0
- package/dist/tempo/internal/machine-token-charge.js +2 -1
- package/dist/tempo/legacy/index.d.ts +1 -3
- package/dist/tempo/legacy/index.js +1 -3
- package/dist/tempo/server/Charge.js +75 -46
- package/dist/tempo/server/Methods.d.ts +55 -10
- package/dist/tempo/server/Subscription.d.ts +1 -1
- package/dist/tempo/server/Subscription.js +31 -4
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/dist/tempo/server/internal/transport.js +28 -11
- package/dist/tempo/session/client/ChannelOps.js +5 -0
- package/dist/tempo/session/client/Session.d.ts +1 -0
- package/dist/tempo/session/client/Session.js +7 -4
- package/dist/tempo/session/client/SessionManager.js +3 -0
- package/dist/tempo/session/client/Transports.d.ts +8 -1
- package/dist/tempo/session/client/Transports.js +12 -3
- package/dist/tempo/session/precompile/Chain.js +16 -1
- package/dist/tempo/session/precompile/Protocol.d.ts +2 -0
- package/dist/tempo/session/precompile/Voucher.d.ts +16 -0
- package/dist/tempo/session/precompile/Voucher.js +48 -0
- package/dist/tempo/session/server/ChannelStore.d.ts +20 -2
- package/dist/tempo/session/server/ChannelStore.js +25 -4
- package/dist/tempo/session/server/CredentialVerification.d.ts +4 -1
- package/dist/tempo/session/server/CredentialVerification.js +34 -6
- package/dist/tempo/session/server/MeteredStream.d.ts +3 -2
- package/dist/tempo/session/server/MeteredStream.js +85 -29
- package/dist/tempo/session/server/Session.d.ts +2 -1
- package/dist/tempo/session/server/Session.js +2 -1
- package/dist/tempo/session/server/Settlement.d.ts +21 -0
- package/dist/tempo/session/server/Settlement.js +92 -17
- package/dist/tempo/session/server/Sse.d.ts +3 -1
- package/dist/tempo/session/server/Sse.js +105 -32
- package/dist/tempo/session/server/Transports.d.ts +24 -19
- package/dist/tempo/session/server/Transports.js +169 -58
- package/dist/tempo/session/server/Ws.d.ts +5 -1
- package/dist/tempo/session/server/Ws.js +75 -20
- package/dist/tempo/subscription/Store.d.ts +2 -0
- package/dist/tempo/subscription/Store.js +3 -0
- package/dist/validation/core.js +2 -1
- package/dist/x402/server/EvmCharge.d.ts +3 -1
- package/dist/x402/server/EvmCharge.js +14 -1
- package/package.json +6 -6
- package/dist/tempo/legacy/client/ChannelOps.d.ts +0 -69
- package/dist/tempo/legacy/client/ChannelOps.js +0 -168
- package/dist/tempo/legacy/client/Session.d.ts +0 -185
- package/dist/tempo/legacy/client/Session.js +0 -279
- package/dist/tempo/legacy/client/SessionManager.d.ts +0 -100
- package/dist/tempo/legacy/client/SessionManager.js +0 -706
- package/dist/tempo/legacy/client/index.d.ts +0 -7
- package/dist/tempo/legacy/client/index.js +0 -5
|
@@ -1,19 +1,17 @@
|
|
|
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,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,Signature as O}from"ox";import{z as k}from"zod/mini";import*as A from"node:child_process";import*as j from"node:fs";import*as M from"node:os";import*as N from"node:path";import{z as P}from"zod";import"node:readline";import{tempo as F,tempoModerato as ee}from"viem/tempo/chains";import{ousd as I,pathusd as te,usdce as ne}from"viem/tokens";import{Abis as re,Account as ie,Actions as L,Addresses as ae,TokenId as oe,Transaction as se,withFeePayer as ce}from"viem/tempo";import{parseAccount as le,privateKeyToAccount as ue}from"viem/accounts";import{createParser as de}from"eventsource-parser";import{Channel as fe,KeyAuthorization as R,SignatureEnvelope as z,TempoAddress as pe,TxEnvelopeTempo as me}from"ox/tempo";var he=Object.defineProperty,ge=Object.getOwnPropertyDescriptor,_e=Object.getOwnPropertyNames,ve=Object.prototype.hasOwnProperty,ye=(e,t)=>{let n={};for(var r in e)he(n,r,{get:e[r],enumerable:!0});return t||he(n,Symbol.toStringTag,{value:`Module`}),n},be=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=_e(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ve.call(e,s)&&s!==n&&he(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=ge(t,s))||r.enumerable});return e},xe=(e,t,n)=>(be(e,t,`default`),n&&be(n,t,`default`));const Se=Symbol(`mppx.x402.asset`);function Ce(e){return{[Se]:!0,address:e.address,decimals:e.decimals,network:e.network,transfer:e.transfer}}function we(e,t){let n=e(t.chainId);return Ce({address:n.address,decimals:n.decimals,network:Pe(t.chainId),transfer:Ie(t.transfer,n)})}const Te={USDC:Ce({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},Ee={USDC:Ce({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},De={USDC:Ce({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:Ce({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},Oe={USDC:Ce({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})};function ke(e){return typeof e!=`object`||!e?!1:e[Se]===!0}function Ae(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function je(e){return typeof e==`string`}function Me(e,t){if(ke(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(Ae(e)){let n=e.addresses[Fe(t)];return n?{address:n,decimals:e.decimals,name:e.name}:void 0}return{address:e}}function Ne(e,t,n){let r=Me(e,n);return r?o(r.address)===o(t):!1}function Pe(e){return`eip155:${e}`}function Fe(e){return Number(e.slice(7))}function Ie(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 Le=ye({base:()=>Te,baseSepolia:()=>Ee,celo:()=>De,celoSepolia:()=>Oe,define:()=>Ce,fromToken:()=>we,isAsset:()=>ke,isRawAddress:()=>je,isToken:()=>Ae,matches:()=>Ne,resolve:()=>Me,toChainId:()=>Fe,toNetwork:()=>Pe}),Re=ye({base:()=>ze,baseSepolia:()=>Be,celo:()=>Ve,celoSepolia:()=>He});const ze=8453,Be=84532,Ve=42220,He=11142220,B={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},Ue={payment:`Payment`},We={evm:`evm`,stripe:`stripe`,tempo:`tempo`},Ge={charge:`charge`,session:`session`,subscription:`subscription`},Ke={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},qe={v1:`v1`,v2:`v2`};function Je(e,t){if(!(!e||typeof e!=`object`))return e[t]}function Ye(e){let t=C.toString(e);return JSON.parse(t)}function V(e){let t=D.canonicalize(e);return C.fromString(t,{pad:!1,url:!0})}var H=ye({address:()=>W,amount:()=>U,datetime:()=>Ze,datetimeInput:()=>Qe,hash:()=>G,period:()=>tt,signature:()=>K,toDate:()=>$e,toDatetimeString:()=>et,unwrapOptional:()=>nt});import*as Xe from"zod/mini";xe(H,Xe);function U(){return k.string().check(k.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function Ze(){return k.string().check(k.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 Qe(e=`Invalid ISO 8601 datetime`){return k.pipe(k.union([Ze(),k.custom(e=>e instanceof Date)]),k.transform($e)).check(k.refine(e=>Number.isFinite(e.getTime()),e))}function $e(e){return e instanceof Date?e:new Date(e)}function et(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function W(){return k.string().check(k.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function G(){return k.string().check(k.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function tt(){return k.string().check(k.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function K(){return k.string().check(k.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function nt(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}const rt=H.object({description:H.optional(H.string()),digest:H.optional(H.string().check(H.regex(/^sha-256=/,`Invalid digest format`))),expires:H.optional(Ze()),header:H.optional(H.string().check(H.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,`Invalid HTTP header name`))),id:H.string().check(H.minLength(1)),intent:H.string(),method:H.string(),meta:H.optional(H.record(H.string(),H.string())),opaque:H.optional(H.string()),realm:H.string(),request:H.record(H.string(),H.unknown())});function it(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=vt(o)?void 0:o,f=e.expires?et(e.expires):void 0,p=e.opaque??(i===void 0?void 0:V(i)),m=u?yt({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return rt.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 at(e){let t=[q(`id`,e.id),q(`realm`,e.realm),q(`method`,e.method),q(`intent`,e.intent),q(`request`,V(e.request))];e.description!==void 0&&t.push(q(`description`,e.description)),e.digest!==void 0&&t.push(q(`digest`,e.digest)),e.expires!==void 0&&t.push(q(`expires`,e.expires));let n=e.header;return n!==void 0&&!vt(n)&&t.push(q(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(q(`opaque`,V(e.meta))):t.push(q(`opaque`,e.opaque)),`${Ue.payment} ${t.join(`, `)}`}function q(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 ot(e,t){let n=st(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=ct(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 it({...a,request:Ye(r),...i&&{opaque:i}},t)}function st(e){let t=Ue.payment,[n]=ft(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 ct(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]=lt(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function lt(e,t){if(e[t]===`"`)return ut(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function ut(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 dt(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 ft(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(!dt(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 pt(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return mt(e.headers,t)}function mt(e,t){let n=e.get(B.wwwAuthenticate);if(!n)throw Error(`Missing ${B.wwwAuthenticate} header.`);return ht(n,t)}function ht(e,t){let n=ft(e,Ue.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 ot(e.slice(r,a).replace(/,\s*$/,``),t)})}function gt(e){let t=[e.realm,e.method,e.intent,V(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!vt(n)&&t.push(n),t.push(e.opaque??(e.meta?V(e.meta):``)),t.join(`|`)}function _t(e){return e.header??B.authorization}function vt(e){return e?.toLowerCase()===B.authorization.toLowerCase()}function yt(e,t){let n=gt(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})}var bt=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},xt=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function St(e){let t=e.match(RegExp(`^${Ue.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new bt;try{let e=C.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=Ct(r);return{challenge:rt.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:Ye(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new xt}}function Ct(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!wt(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:V(e)}}function wt(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function Tt(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function Et(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:V(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:V(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=C.fromString(s,{pad:!1,url:!0});return`${Ue.payment} ${c}`}var Dt=class extends Error{details;status=402;hint;constructor(e,t={}){super(e),this.details=t.details}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}.`)}},J=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.`)}};function At(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(new Date(e)<new Date)throw new kt({expires:e})}function jt(e){return e}function Mt(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}function Nt(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 Pt}}}}var Pt=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const Ft=[`exact`],It=`PAYMENT-REQUIRED`,Lt=`PAYMENT-SIGNATURE`,Rt=H.string().check(H.minLength(1)),zt=H.number().check(H.refine(e=>e>0,`Must be positive`)),Bt=H.string().check(H.regex(/^\d+$/,`Invalid atomic amount`)),Vt=W(),Ht=H.string().check(H.regex(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),Ut=H.object({description:H.optional(H.string()),iconUrl:H.optional(H.string()),mimeType:H.optional(H.string()),serviceName:H.optional(H.string()),tags:H.optional(H.array(H.string())),url:Rt});H.discriminatedUnion(`type`,[H.object({name:Rt,type:H.literal(`eip3009`),version:Rt}),H.object({name:H.optional(H.string()),type:H.literal(`permit2`),version:H.optional(H.string())})]);const Wt=H.object({amount:Bt,asset:Rt,extra:H.optional(H.record(H.string(),H.unknown())),maxTimeoutSeconds:zt,network:Ht,payTo:Rt,scheme:H.enum(Ft)}),Gt=H.object({info:H.record(H.string(),H.unknown()),schema:H.record(H.string(),H.unknown())}),Kt=H.record(H.string(),Gt),qt=H.object({accepts:H.array(Wt).check(H.minLength(1)),error:H.optional(H.string()),extensions:H.optional(Kt),resource:Ut,x402Version:H.literal(2)}),Jt=H.object({authorization:H.object({from:Vt,nonce:G(),to:Vt,validAfter:Bt,validBefore:Bt,value:Bt}),signature:K()}),Yt=H.object({permit2Authorization:H.object({deadline:Bt,from:Vt,nonce:Bt,permitted:H.object({amount:Bt,token:Vt}),spender:Vt,witness:H.object({to:Vt,validAfter:Bt})}),signature:K()}),Xt=H.union([Jt,Yt]),Zt=H.object({accepted:Wt,extensions:H.optional(Kt),payload:Xt,resource:H.optional(Ut),x402Version:H.literal(2)});H.object({extensions:H.optional(Kt),extra:H.optional(H.record(H.string(),H.unknown())),invalidMessage:H.optional(H.string()),invalidReason:H.optional(H.string()),isValid:H.boolean(),payer:H.optional(H.string())});const Qt=H.object({amount:H.optional(Bt),errorMessage:H.optional(H.string()),errorReason:H.optional(H.string()),extensions:H.optional(Kt),extra:H.optional(H.record(H.string(),H.unknown())),network:Rt,payer:H.optional(H.string()),success:H.boolean(),transaction:H.string()});function $t(e){let{extensions:t,resource:n,...r}=e;return Wt.parse(r)}const en=Nt(qt),tn=Nt(Zt),nn=Nt(Qt);en.encode,en.decode;function rn(e){try{let t=JSON.parse(C.toString(e));return on(t)}catch{throw new Pt}}const an=tn.encode;tn.decode,nn.encode,nn.decode;const on=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new Pt;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new Pt;let n=Ut.parse(t.resource),r=t.extensions===void 0?void 0:Kt.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}};function sn(e){let t=[V(e.accepted),V(e.resource),V(e.extensions)].join(`|`);return T.sha256(w.fromString(t),{as:`Hex`})}async function cn(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=$t(n);if(fn(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?mn(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?sn({accepted:r,extensions:i,resource:n.resource}):gn(),to:o(r.payTo),validAfter:(l-600).toString(),validBefore:(l+r.maxTimeoutSeconds).toString(),value:r.amount},d=await t.signTypedData({domain:{chainId:dn(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:un});return an({accepted:r,...i?{extensions:i}:{},payload:{authorization:u,signature:d},...n.resource?{resource:n.resource}:{},x402Version:2})}function ln(e){let t=e.challenge.request,n;try{n=$t(t),fn(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 un={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 dn(e){return Number(e.slice(7))}function fn(e,t){let n=dn(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=>je(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=o(t.asset);if(!r.some(n=>Ne(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=pn(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 pn(e,t){let n=e.currencies??e.assets,r=o(t.asset),i=n?.find(e=>Ne(e,r,t.network)),a=i?Me(i,t.network):void 0;return a?.decimals===void 0?e.decimals:a.decimals}function mn(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:hn()}}}:e}function hn(){return _n().slice(2)}function gn(){return _n()}function _n(){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 vn=Symbol.for(`mppx.x402.challenge`);function yn(e){return Object.defineProperty(e,vn,{value:!0}),e}function bn(e){return!!e?.[vn]}const xn=[`authorization`],Sn=H.string().check(H.regex(/^\d+$/,`Invalid atomic amount`));H.object({name:H.string().check(H.minLength(1)),version:H.string().check(H.minLength(1))});const Cn=H.object({chainId:H.number(),credentialTypes:H.optional(H.array(H.enum(xn)).check(H.minLength(1))),decimals:H.optional(H.number()),permit2Address:H.optional(W()),splits:H.optional(H.array(H.object({amount:Sn,recipient:W()})))});H.object({amount:Sn,currency:W(),description:H.optional(H.string()),externalId:H.optional(H.string()),methodDetails:Cn,recipient:W()});const wn=H.object({amount:U(),chainId:H.number(),currency:W(),credentialTypes:H.optional(H.array(H.enum(xn)).check(H.minLength(1))),decimals:H.number(),description:H.optional(H.string()),externalId:H.optional(H.string()),permit2Address:H.optional(W()),recipient:W(),splits:H.optional(H.array(H.object({amount:Sn,recipient:W()})))}),Tn=H.object({from:W(),nonce:G(),signature:K(),to:W(),type:H.literal(`authorization`),validAfter:Sn,validBefore:Sn,value:Sn}),En={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 Dn(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function On(e){return T.keccak256(w.fromString(`${e.id}${e.realm}`),{as:`Hex`})}function kn(e){return`eip155:${e}`}function An(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const jn=jt({name:`evm`,intent:`charge`,schema:{credential:{payload:Tn},request:H.pipe(wn,H.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:s,splits:c,...l})=>({...l,amount:f(e,i).toString(),currency:o(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:o(a)}:{},...c?{splits:c}:{}},recipient:o(s)})))}});function Mn(e){return Mt(jn,{canHandleChallenge({challenge:t}){return!Nn(t)||ln({challenge:t,config:e})},context:H.object({account:H.optional(H.custom())}),async createCredential({challenge:t,context:n}){if(Nn(t))return cn({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(Pn(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=Fn(e,i),s=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return Et(Tt({challenge:t,payload:{from:o(r.address),nonce:On(t),signature:await r.signTypedData({domain:Dn({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:o(r.address),nonce:On(t),to:o(i.recipient),validAfter:0n,validBefore:BigInt(s),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:En}),to:o(i.recipient),type:`authorization`,validAfter:`0`,validBefore:s,value:i.amount},source:An({address:o(r.address),chainId:i.methodDetails.chainId})}))}})}function Nn(e){return bn(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function Pn(e,t){let n=t.methodDetails.chainId,r=kn(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=>je(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=o(t.currency);if(!i.some(t=>Ne(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=In(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 Fn(e,t){let n=e.currencies??e.assets,r=o(t.currency),i=kn(t.methodDetails.chainId),a=n?.find(e=>Ne(e,r,i)),s=a?Me(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 In(e,t){let n=e.currencies??e.assets,r=o(t.currency),i=kn(t.methodDetails.chainId),a=n?.find(e=>Ne(e,r,i)),s=a?Me(a,i):void 0;return s?.decimals===void 0?e.decimals:s.decimals}function Ln(e){return[Ln.charge(e)]}(function(e){e.charge=Mn,e.assets=Le,e.chains=Re})(Ln||={});var Rn=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 zn(this,e)}},Y=class extends Rn{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 zn(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},Bn={ousd:I(X.mainnet).address,usdc:o(ne(X.mainnet).address),pathUsd:te(X.mainnet).address},Vn={[X.mainnet]:Bn.usdc,[X.testnet]:Bn.pathUsd},Hn=Object.freeze({[X.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[X.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})}),Un={[X.mainnet]:`0x33b901018174DDabE4841042ab76ba85D4e24f25`,[X.testnet]:`0xe1c4d3dce17bc111181ddf716f75bae49e61a336`},Wn={[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 Gn(e,t){return Z.link(e,t)}function Kn(e){return e.startsWith(`tempo:`)}function qn(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 Jn={mainnet:Wn[X.mainnet],testnet:Wn[X.testnet]};function Yn(e,t={}){return e??(t.network?Jn[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}async function Xn(t={}){let n=Yn(t.rpcUrl,{network:t.network});if(!n)return F;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 Zn(e){return typeof e==`bigint`?e:e.amount}function Qn(e){return e.id!==F.id}async function $n(e,t,n){let{Actions:r}=await import(`viem/tempo`),[i,a]=await Promise.all([r.token.getBalance(e,{account:n,token:t}).then(Zn).catch(()=>0n),r.token.getMetadata(e,{token:t}).catch(()=>({symbol:t}))]);return{balance:i,symbol:{"0x20c0000000000000000000000000000000000000":`PathUSD`,"0x20C000000000000000000000b9537d11c60E8b50":`USDC`}[t]??a.symbol,decimals:`decimals`in a&&typeof a.decimals==`number`?a.decimals:6,token:t}}function er(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:1e4}function tr(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function nr(e){return new Y({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 rr(e){if(e&&tr(e,`secret-tool`))throw nr(e)}function ir(e,t){return new Promise(n=>{A.execFile(e,t,{timeout:er()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function ar(){let e=N.join(process.env.XDG_CONFIG_HOME||N.join(M.homedir(),`.config`),`mppx`,`default`);return{get(){try{return j.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(t){j.mkdirSync(N.dirname(e),{recursive:!0}),j.writeFileSync(e,t,`utf-8`)},clear(){try{j.unlinkSync(e)}catch{}}}}function or(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:ar().get())}function sr(e=`main`){let t=`mppx`;return{async list(){let e=M.platform();if(e===`darwin`){let{stdout:e,error:n}=await ir(`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 ir(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(rr(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=M.platform();if(n===`darwin`){let{stdout:n,error:r}=await ir(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await ir(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return rr(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=M.platform();if(r===`darwin`){await ir(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await ir(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=A.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),er());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(tr(e,`secret-tool`)?nr(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=M.platform();if(n===`darwin`){await ir(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await ir(`secret-tool`,[`clear`,`service`,t,`account`,e]);rr(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function cr(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=or(e),i=await sr(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function lr(e){return(await cr(e)).account}function ur(e){return e}function dr(){return ur({method:`evm`,supports:e=>e.method===`evm`&&!bn(e),async setup({challenge:t}){let n=t.request,r=n.methodDetails,a=r?.chainId,o=a?fr(a):void 0,s=n.currency,l=await lr(),u=[...Object.values(Te),...Object.values(Ee),...Object.values(De),...Object.values(Oe)],d=s??``;if(o&&s)try{let t=e({chain:o,transport:c()}),n=await h(t,{address:s,abi:i,functionName:`symbol`});n&&(d=n)}catch{}return{tokenSymbol:d,tokenDecimals:r?.decimals??6,explorerUrl:o?.blockExplorers?.default?.url,methods:[...Ln({account:l,currencies:u})]}}})}function fr(e){return Object.values(b).find(t=>t.id===e)}function pr(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 mr=H.object({customer:H.optional(H.string().check(H.minLength(1))),hooks:H.optional(H.object({inputs:H.object({tax:H.object({calculation:H.string().check(H.minLength(1))})})})),metadata:H.optional(H.record(H.string(),H.string())),receipt_email:H.optional(H.string().check(H.minLength(1)))}),hr=H.custom(e=>typeof e==`function`),gr=H.union([mr,hr]),_r=jt({name:`stripe`,intent:`charge`,schema:{credential:{payload:H.object({externalId:H.optional(H.string()),spt:H.string()})},request:H.pipe(H.object({amount:U(),currency:H.string(),decimals:H.number(),description:H.optional(H.string()),externalId:H.optional(H.string()),metadata:H.optional(H.record(H.string(),H.string())),networkId:H.string(),paymentIntentOptions:H.optional(gr),paymentMethodTypes:H.array(H.string()).check(H.minLength(1)),recipient:H.optional(H.string())}),H.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:pr(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});function vr(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return Mt(_r,{context:H.object({paymentMethod:H.optional(H.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 Et({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function yr(e){return[vr(e)]}(function(e){e.charge=vr})(yr||={});function br(){return ur({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=Sr(P.object({paymentMethod:P.string(),secretKey:P.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new Y({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:[yr.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=xr(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 Y({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${(await d.json()).error.message}`,exitCode:77})}else throw new Y({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&&xr(e)?`/test`:``}/payments/${t}`;return Z.link(n,t,!0)}}})}function xr(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function Sr(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 Cr(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=Or(n)}return t}function wr(e,t){let n=Cr(e),r=Fr(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[Or(e)]??1,index:t}));return{definition:r,entries:i,header:Er(i),keys:n}}function Tr(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)=>Nr(e,t))}function Er(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${zr(n)}`}).join(`, `)}function Dr(e,t,n){let r=new Map;for(let e of t){let t=Or(e),n=r.get(t);n?n.push(e):r.set(t,[e])}return e.flatMap((e,t)=>{let i=r.get(Or(e));if(!i)return[];let a=kr(e,n);return!a||a.q<=0?[]:i.filter(t=>t.canHandleChallenge?.({challenge:e})??!0).map(n=>({challenge:e,index:t,match:a,method:n}))}).sort((e,t)=>Mr(e.challenge)-Mr(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function Or(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function kr(e,t){let n;for(let r of t){if(!Ar(e,r))continue;let t={...r,specificity:jr(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 Ar(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function jr(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function Mr(e){return+!!bn(e)}function Nr(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}`);Br(r,`method`),Br(i,`intent`);let a=1;for(let t of Pr(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=Lr(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function Pr(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function Fr(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>Or(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]=Ir(t,`payment preference "${e}"`)}return a}function Ir(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return Rr(e,t)}function Lr(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 Rr(Number(e),t)}function Rr(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 zr(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function Br(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}const Vr=[B.authorization,It,`PAYMENT-RESPONSE`,Lt];function Hr(e,t,n){let r=new Headers(e.headers);for(let e of Vr)e===B.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}function Ur(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}}const Wr=new WeakMap;function Gr(e){let t=Ur(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 Kr(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 qr(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=rt.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 Jr(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:qr(e.error.data):qr(e.result?._meta?.[`org.paymentauth/payment-required`])}function Yr(e,t){return!e||e.id!==t?[]:Jr(e)?.challenges??[]}async function Xr(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=!1,i,a=de({onEvent(e){if(!(r||!e.data)&&(r=!0,!(e.event&&e.event!==`message`)))try{i=Kr(JSON.parse(e.data))}catch{}}});try{for(;;){if(r)return i;let{done:e,value:o}=await t.read();if(e)return a.feed(n.decode()),a.reset({consume:!0}),i;a.feed(n.decode(o,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}function Zr(e){let t=Wr.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(t.includes(`application/json`))return e.clone().json().then(Kr).catch(()=>void 0);if(t.includes(`text/event-stream`))return Xr(e)})();return Wr.set(e,n),n}function Qr(){return{getChallenges(e,t){let n=Gr(t);return e.status===402||n===void 0?[]:Zr(e).then(e=>Yr(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=St(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}function $r(){return{getChallenges(e){return e.status!==402||!e.headers.has(B.wwwAuthenticate)?[]:pt(e)},setCredential(e,t,n){return Hr(e,n?.challenge?_t(n.challenge):B.authorization,t)}}}function ei(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(It);if(!t)return[];let n=rn(t);return n.accepts.flatMap((e,t)=>{let r=Wt.safeParse(e);if(!r.success)return[];let i=r.data;return yn(it({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 Hr(e,Lt,t)}}}function ti(e){return e}function ni(){let e=[$r(),ei(),Qr()],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 ti({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 ri=new WeakMap;function ii(e,t){return ri.set(e,t),e}function ai(e){return ri.has(e)}function oi(e,t){return Promise.resolve(ri.get(e)?.(t))}const si=new WeakMap,ci=new WeakMap;function li(e,t){return si.set(e,t),e}function ui(e){si.delete(e)}function di(e,t,n){si.has(e)&&ci.set(t,n)}function fi(e){return ci.get(e)}function pi(e,t){return Promise.resolve(si.get(e)?.(t)??t.response)}const mi=Symbol.for(`mppx.fetch.wrapper`),hi=new WeakMap;async function gi(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 _i(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=ni()}=e,l=e.eventDispatcher??vi(),u=t??wr(a),d=zi(r),f=async(e,t,r)=>{let p=Ri(e,t?.headers),m=p.has(B.acceptPayment),h=Wi(p,u),g=Ii(e,t,p),_=Fi(e,t,p,h.header,m,n),v=await d(Bi(_.input),_.init),y=Li(_.init,await g);if(!await c.isPaymentRequired(v,y))return v;let b=t?.context,{context:x,orderChallenges:S,...C}=y??{},w,T,E,D;try{for(let n=0;n<i;n++){T=await c.getChallenges(v,y);let i=(await Gi(Dr(T,a,h.entries),S??s))[0];if(!i){if(await gi(D,{challenges:T,response:v,status:`rejected`}),n>0)return v;throw Error(`No method found for challenges: ${T.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let u=i.challenge;w=u,E=i.method,w.expires&&At(w.expires,w.id);let p=Xi(v,_.input,_.input),m=D,g=at(u),x=m?.method===i.method&&m?.key===g,O=!1;if(m){let e=await gi(m,{challenges:T,response:v,status:x?`pending`:`rejected`});O=x&&!e}D=O?m:void 0;let k=Ci(async e=>{if(e===void 0&&O&&m)return m.promise;O&&m&&(await gi(m,{status:`rejected`}),D=void 0);let t=e??b;if(!ai(i.method))return Ui(u,i.method,t);let n={prepare:()=>oi(i.method,{challenge:u,context:t,fetch:d,input:p})},r=n.prepare().then(()=>Ui(u,i.method,t,n));return D={attempt:n,key:e===void 0?g:void 0,method:i.method,promise:r},r}),A=await l.emit(`challenge.received`,wi({challenge:u,challenges:T,createCredential:k,init:t,input:e,method:i.method,response:v}))??(o?await o(w,{createCredential:k}):void 0)??await k(),j=D;j&&await j.promise.catch(()=>void 0)!==A&&(await gi(j,{status:`rejected`}),D=void 0),Hi(A),await l.emit(`credential.created`,Ti({challenge:u,credential:A,init:t,input:e,method:i.method,response:v})),v=await d(p,c.setCredential({...C,headers:_.headers},A,{challenge:u}));let M=await c.isPaymentRequired(v,y);if(M||(await gi(j,{response:v,status:v.ok?`accepted`:`rejected`}),D=void 0),v.ok&&yi(l,`payment.response`)&&await l.emit(`payment.response`,Ei({challenge:u,credential:A,init:t,input:e,method:i.method,response:v})),!M)return v.ok?pi(i.method,{challenge:u,credential:A,fetch:d,headers:_.headers,input:p,...r?{refetch:()=>f(Bi(_.input),t,!1)}:{},response:v,signal:Vi(e,t)}):v}T=void 0;try{T=await c.getChallenges(v,y)}catch{}return await gi(D,{challenges:T,response:v,status:`rejected`}),v}catch(n){throw await gi(D,{challenges:T,response:v,status:`rejected`}),await l.emit(`payment.failed`,Di({challenge:w,challenges:T,error:n,init:t,input:e,method:E,response:v})),n}},p=(e,t)=>f(e,t,!0);return p[mi]=d,p}function Q(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 vi(){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 bi(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await Si(e[`*`],t,n),r}case`credential.created`:await xi(e[`credential.created`],n),await Si(e[`*`],t,n);return;case`payment.failed`:await xi(e[`payment.failed`],n),await Si(e[`*`],t,n);return;case`payment.response`:await xi(e[`payment.response`],n),await Si(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 hi.set(t,t=>e[t].size>0||e[`*`].size>0),t}function yi(e,t){return hi.get(e)?.(t)??!0}async function bi(e,t){try{return await e(t)}catch{return}}async function xi(e,t){for(let n of e)try{await n(t)}catch{}}async function Si(e,t,n){await xi(e,Object.freeze({name:t,payload:n}))}function Ci(e){let t;return n=>(t??=e(n),t)}function wi(e){return Object.freeze({challenge:Mi(e.challenge),challenges:e.challenges.map(e=>Mi(e)),createCredential:e.createCredential,init:Oi(e.init),input:ki(e.input),method:Ai(e.method),response:ji(e.response)})}function Ti(e){return Object.freeze({challenge:Mi(e.challenge),credential:e.credential,init:Oi(e.init),input:ki(e.input),method:Ai(e.method),...e.response===void 0?{}:{response:ji(e.response)}})}function Ei(e){return Object.freeze({challenge:Mi(e.challenge),credential:e.credential,init:Oi(e.init),input:ki(e.input),method:Ai(e.method),response:ji(e.response)})}function Di(e){return Object.freeze({...e.challenge?{challenge:Mi(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>Mi(e))}:{},error:e.error,init:Oi(e.init),input:ki(e.input),...e.method?{method:Ai(e.method)}:{},...e.response===void 0?{}:{response:ji(e.response)}})}function Oi(e){if(e)return Pi({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function ki(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function Ai(e){return Pi(Object.assign({},e))}function ji(e){return e instanceof Response?e.clone():Mi(e)}function Mi(e){try{return Ni(structuredClone(e))}catch{return Pi(e)}}function Ni(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Ni(t);return e}function Pi(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function Fi(e,t,n,r,i,a){let o=!!r&&!i&&Ki(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 Ii(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 Li(e,t){return t===void 0?e:{...e,body:t}}function Ri(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function zi(e){let t=e;for(;t[mi];)t=t[mi];return t}function Bi(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function Vi(e,t){return t?.signal??(e instanceof Request?e.signal:void 0)}function Hi(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
|
|
2
|
-
`))throw Error(`Credential header value contains illegal newline characters`)}async function Ui(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&&di(t,a,r),t.createCredential(a)}function Wi(e,t){let n=e.get(B.acceptPayment);if(!n)return t;try{return{...t,entries:Tr(n),header:n}}catch{return t}}async function Gi(e,t){return t?t(e):e}function Ki(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=Yi(e);return t===`same-origin`?!Ji()||n.origin===globalThis.location.origin:t.origins.some(e=>qi(n,e))}function qi(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 Ji(){return globalThis.location!==void 0}function Yi(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,Ji()?globalThis.location.href:void 0)}function Xi(e,t,n){if(!e.url)return t;let r=new URL(e.url),i=Yi(n);if(r.origin!==i.origin)throw Error(`Refusing to send payment credential across redirect from ${i.origin} to ${r.origin}`);return e.url}function Zi(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 le(r)}}function Qi(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}const $i={[F.id]:F,[ee.id]:ee};function ea(e,t={}){return c(e.url,{fetchFn:e.fetch,fetchOptions:{headers:Qi(e)},...t})}function ta(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=ce(n({request:t=>e(t)},{retryCount:0}),ea(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?ce(c(r),ea(o)):c(r);return e({chain:$i[n]??{...i,id:n},transport:a})}}function na(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 ra(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}const ia=E.slice(T.keccak256(w.fromString(`mpp`),{as:`Hex`}),0,4);function aa(e){let t=T.keccak256(w.fromString(e),{as:`Hex`});return E.toBytes(E.slice(t,0,10))}function oa(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(E.toBytes(ia),0),i[4]=1,i.set(aa(t),5),n&&i.set(aa(n),15),i.set(sa(r),25),E.fromBytes(i)}function sa(e){let t=T.keccak256(w.fromString(e),{as:`Hex`});return E.toBytes(E.slice(t,0,7))}function ca(e,t){return pe.resolve(e).toLowerCase()===pe.resolve(t).toLowerCase()}const la=[Bn.pathUsd,Bn.usdc];async function ua(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t,s=a.filter(e=>!ca(e,i)),c=await Promise.allSettled([h(e,L.token.getBalance.call(e,{account:n,token:i})),...s.map(t=>h(e,L.token.getBalance.call(e,{account:n,token:t})))]),l=c[0];if(!(l.status===`fulfilled`&&l.value>=r)){for(let t=0;t<s.length;t++){let n=c[t+1];if(n.status!==`fulfilled`)continue;let a=n.value;if(a<=0n)continue;let l=s[t];try{let t=await L.dex.getBuyQuote(e,{tokenIn:l,tokenOut:i,amountOut:r});if(a>=t){let n=t+t*BigInt(Math.round(o*100))/10000n;return[L.token.approve.call(e,{amount:n,spender:ae.stablecoinDex,token:l}),L.dex.buy.call({tokenIn:l,tokenOut:i,amountOut:r,maxAmountIn:n})]}}catch{}}throw new fa({currency:i})}}function da(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...t.filter(t=>!e.tokenIn.some(e=>ca(e,t)))]:t,slippage:e.slippage??1}:!1}var fa=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}};function pa(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:e.amount,memo:e.memo,recipient:e.recipient}))]}function ma(e,t,n){t&&(n&&!n.some(e=>ca(e,t))||e.some(e=>ca(e,t))||e.push(t))}async function ha(e,t,n){try{return(await L.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function ga(e){let t=e.chain?.feeToken;if(t)return oe.toAddress(t);let n=e.chain?.id;return n?Vn[n]:void 0}function _a(e){let t=[];return ma(t,Bn.pathUsd),ma(t,Vn[e]),t}async function va(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])ma(o,e,n);if(ma(o,await L.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),ma(o,ga(i),n),!a)for(let e of r??[])ma(o,e,n);for(let e of o)if(await ha(i,t,e))return e;return o[0]}const ya=d([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]);function ba(e){if(e!==void 0)return Hn[e]}function xa(e){let t=ba(e.chainId);return!!t&&l(e.currency,{strict:!1})&&u(e.currency,t.token)}function Sa(e){let t=ba(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:re.tip20,functionName:`approve`,args:[t.swap,i]}),to:t.token},{data:r({abi:ya,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 Ca(e,t){let n=Sa(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 wa={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]};function Ta(e){return{name:`MPP`,version:`3`,chainId:e}}function Ea(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function Da(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:Ta(n),types:wa,primaryType:`Proof`,message:Ea({account:t,challengeId:r,realm:i})}}function Oa(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const ka=[`push`,`pull`],Aa=H.object({amount:U(),memo:H.optional(G()),recipient:H.pipe(H.string(),H.transform(e=>e))}),ja=(1n<<64n)-1n,Ma={dev_second:1n,day:86400n,week:604800n},Na=H.pipe(W(),H.transform(e=>e.toLowerCase())),Pa=H.object({accessKeyAddress:Na,keyType:H.enum([`p256`,`secp256k1`,`webAuthn`])}),Fa=H.object({accessKey:H.optional(Pa),chainId:H.optional(H.number())}),Ia=Qe(`subscriptionExpires must be a valid date`).check(H.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),La=H.enum([`dev_second`,`day`,`week`]),Ra=H.pipe(H.union([H.string(),H.bigint(),H.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),H.transform(e=>e.toString())).check(H.regex(/^[1-9]\d*$/,`Invalid periodCount`),H.refine(e=>{try{return BigInt(e)<=ja}catch{return!1}},`periodCount exceeds uint64`));function za(e){return H.refine(e=>{let{amount:t,decimals:n}=e;return f(t,n)>0n},e)}function Ba(e){let{periodCount:t,periodUnit:n}=e;try{let e=Ma[n];return e!==void 0&&BigInt(t)*e<=ja}catch{return!1}}const Va=jt({name:`tempo`,intent:`charge`,schema:{credential:{payload:H.discriminatedUnion(`type`,[H.object({hash:G(),type:H.literal(`hash`)}),H.object({signature:K(),type:H.literal(`transaction`)}),H.object({signature:K(),type:H.literal(`proof`)})])},request:H.pipe(H.object({machineTokenEnabled:H.optional(H.boolean()),amount:U(),chainId:H.optional(H.number()),currency:H.string(),decimals:H.number(),description:H.optional(H.string()),externalId:H.optional(H.string()),feePayer:H.optional(H.pipe(H.union([H.boolean(),H.custom()]),H.transform(e=>typeof e==`object`||e))),memo:H.optional(H.never()),recipient:H.optional(H.string()),splits:H.optional(H.array(Aa).check(H.minLength(1),H.maxLength(10))),supportedModes:H.optional(H.array(H.enum(ka)).check(H.minLength(1)))}).check(H.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`)),H.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}}}:{}})))}}),Ha=jt({name:`tempo`,intent:`session`,schema:{credential:{payload:H.discriminatedUnion(`action`,[H.object({action:H.literal(`open`),authorizedSigner:H.optional(H.string()),channelId:G(),cumulativeAmount:U(),descriptor:H.optional(H.custom()),signature:K(),transaction:K(),type:H.literal(`transaction`)}),H.object({action:H.literal(`topUp`),additionalDeposit:U(),channelId:G(),descriptor:H.optional(H.custom()),transaction:K(),type:H.literal(`transaction`)}),H.object({action:H.literal(`voucher`),channelId:G(),cumulativeAmount:U(),descriptor:H.optional(H.custom()),signature:K()}),H.object({action:H.literal(`close`),channelId:G(),cumulativeAmount:U(),descriptor:H.optional(H.custom()),signature:K()})])},request:H.pipe(H.object({amount:U(),chainId:H.optional(H.number()),channelId:H.optional(G()),currency:H.string(),decimals:H.number(),escrowContract:H.optional(H.string()),feePayer:H.optional(H.pipe(H.union([H.boolean(),H.custom()]),H.transform(e=>typeof e==`object`||e))),feeToken:H.optional(W()),minVoucherDelta:H.optional(U()),operator:H.optional(W()),recipient:H.optional(H.string()),sessionProtocol:H.optional(H.enum([qe.v2,qe.v1])),sessionSnapshot:H.optional(H.custom()),suggestedDeposit:H.optional(U()),unitType:H.string()}).check(H.refine(({amount:e,decimals:t})=>f(e,t)>0n,`Session amount must be greater than 0`)),H.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&&{[Ke.sessionProtocol]:l},...u!==void 0&&{[Ke.sessionSnapshot]:u}}})))}}),Ua=jt({name:`tempo`,intent:`subscription`,schema:{credential:{payload:H.object({signature:K(),type:H.literal(`keyAuthorization`)})},request:H.pipe(H.object({amount:U(),accessKey:H.optional(Pa),chainId:H.optional(H.number()),currency:Na,decimals:H.number(),description:H.optional(H.string()),externalId:H.optional(H.string()),methodDetails:H.optional(Fa),periodCount:Ra,periodUnit:La,recipient:Na,subscriptionExpires:Ia}).check(za(`Subscription amount must be greater than 0`),H.refine(Ba,`Subscription period exceeds uint64`)),H.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}:{}}}))}}),Wa=H.object({account:H.optional(H.custom()),autoSwap:H.optional(H.custom()),mode:H.optional(H.enum(ka))});function Ga(e={}){let{clientId:t}=e,n=ta({chain:F,getClient:e.getClient,rpcUrl:Wn}),r=Zi({account:e.account});return Mt(Va,{context:Wa,async createCredential({challenge:i,context:a}){let o=i.request.methodDetails?.chainId;if(e.expectedChainId!==void 0&&o!==void 0&&o!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${o}.`);(o!==void 0||e.allowedChainIds?.length===0)&&ra(e.allowedChainIds,o);let s=o??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),c=await n({chainId:s});na(c,s);let l=s??c.chain?.id;if(ra(e.allowedChainIds,l),l===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");let{request:u}=i,{amount:d,methodDetails:f}=u,p=f?.supportedModes??[`pull`,`push`],h=r(c,a);if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!u.recipient||!t.has(u.recipient.toLowerCase()))throw Error(`Unexpected primary recipient: ${u.recipient}`);let n=f?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}if(BigInt(d)===0n)return Et({challenge:i,payload:{signature:await y(c,{account:h,...Da({account:h.address,chainId:l,challengeId:i.id,realm:i.realm})}),type:`proof`},source:Oa({address:h.address,chainId:l})});let b=u.currency,x=xa({chainId:l,currency:b}),S=oa({challengeId:i.id,clientId:t,serverId:i.realm}),C=pa({amount:d,methodDetails:{...f,memo:S},recipient:u.recipient}),w=C.map(e=>L.token.transfer.call(c,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:b})),T=da(a?.autoSwap??e.autoSwap,la),E=f?.machineTokenEnabled===!0,D=async t=>await e.resolveAccount?.({account:h,chainId:l,operation:{kind:`executeCalls`,...t?{calls:t}:{}}})??h,O=E?Sa({chainId:l,currency:b,transfers:C}):void 0,k=h,A;if(O){let e=await(async()=>{try{return await D(O.calls)}catch{return}})();e&&(A=await Ca(c,{account:e.address,chainId:l,currency:b,transfers:C}),A&&(k=e))}let j;A||(k=await D(T?void 0:w),j=T?await ua(c,{account:k.address,amountOut:BigInt(d),tokenOut:b,tokenIn:T.tokenIn,slippage:T.slippage}):void 0);let M=A?.calls??[...j??[],...w],N=_a(l),P=A||x?await va({account:k.address,allowedTokens:N,candidateTokens:N,client:c,prioritizeCandidates:!0}):void 0,F=(()=>{let t=a?.mode??e.mode;if(t){if(!p.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=k.type===`json-rpc`?`push`:`pull`;return p.includes(n)?n:p[0]})(),ee=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!i.expires)return e;let t=Math.floor(new Date(i.expires).getTime()/1e3);return Math.min(e,t)})();if(F===`push`){let{receipts:e}=k.type===`local`?{receipts:[await _(c,{account:k,calls:M,...P?{feeToken:P}:{},nonceKey:`expiring`,validBefore:ee})]}:await g(c,{account:k,...P?{capabilities:{feeToken:P}}:{},calls:M,experimental_fallback:M.length===1,forceAtomic:M.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return Et({challenge:i,payload:{hash:t,type:`hash`},source:Oa({address:k.address,chainId:l})})}let I=await m(c,{account:k,calls:M,...P?{feeToken:P}:{},nonceKey:`expiring`,validBefore:ee});if(I.gas=(I.gas??0n)+5000n,f?.feePayer){let e=I;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return Et({challenge:i,payload:{signature:await v(c,I),type:`transaction`},source:Oa({address:k.address,chainId:l})})}})}function Ka(e){return`accessKeyAddress`in e}function qa(e){return Ka(e)?e.accessKeyAddress:e.address}function Ja(e,t){return{name:`Tempo Stream Channel`,version:`1`,chainId:t,verifyingContract:e}}const Ya={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint128`}]};function Xa(e){return{channelId:e.channelId,cumulativeAmount:e.cumulativeAmount}}function Za(e,t,n){return s({domain:Ja(e,t),types:Ya,primaryType:`Voucher`,message:Xa(n)})}async function Qa(e,t,n,r,i){return y(e,{account:t,domain:Ja(r,i),types:Ya,primaryType:`Voucher`,message:Xa(n)})}function $a(e){let t=z.from(e);if(t.type===`keychain`){if(t.inner.type!==`secp256k1`)throw Error(`Session vouchers only unwrap secp256k1 keychain signatures; pass a direct voucherSigner for other key types.`);return O.toHex(t.inner.signature)}return z.serialize(t)}function eo(e){return e.type!==`keychain`&&e.type===`secp256k1`}function to(e){if(!eo(e))throw Error(`Session vouchers only support secp256k1 signatures until TIP-1020 voucher verification is enabled.`)}async function no(e,t,n,r,i,a){let o=a??t,s=qa(o),c=Za(r,i,n),l=$a(Ka(o)?await o.sign({hash:c,raw:!0}):await Qa(e,o,n,r,i)),u=z.from(l);if(to(u),!z.verify(u,{address:s,payload:c}))throw Error(`voucher signature does not match voucher signer`);return l}function ro(e){let t=S.encode(S.from([`address payer`,`address payee`,`address token`,`bytes32 salt`,`address authorizedSigner`,`address escrowContract`,`uint256 chainId`]),[e.payer,e.payee,e.token,e.salt,e.authorizedSigner,e.escrowContract,BigInt(e.chainId)]);return T.keccak256(t)}const io=[{type:`function`,name:`CLOSE_GRACE_PERIOD`,inputs:[],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`VOUCHER_TYPEHASH`,inputs:[],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`view`},{type:`function`,name:`channels`,inputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:`finalized`,type:`bool`,internalType:`bool`},{name:`closeRequestedAt`,type:`uint64`,internalType:`uint64`},{name:`payer`,type:`address`,internalType:`address`},{name:`payee`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`authorizedSigner`,type:`address`,internalType:`address`},{name:`deposit`,type:`uint128`,internalType:`uint128`},{name:`settled`,type:`uint128`,internalType:`uint128`}],stateMutability:`view`},{type:`function`,name:`close`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`},{name:`cumulativeAmount`,type:`uint128`,internalType:`uint128`},{name:`signature`,type:`bytes`,internalType:`bytes`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`computeChannelId`,inputs:[{name:`payer`,type:`address`,internalType:`address`},{name:`payee`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`salt`,type:`bytes32`,internalType:`bytes32`},{name:`authorizedSigner`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`view`},{type:`function`,name:`domainSeparator`,inputs:[],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`view`},{type:`function`,name:`eip712Domain`,inputs:[],outputs:[{name:`fields`,type:`bytes1`,internalType:`bytes1`},{name:`name`,type:`string`,internalType:`string`},{name:`version`,type:`string`,internalType:`string`},{name:`chainId`,type:`uint256`,internalType:`uint256`},{name:`verifyingContract`,type:`address`,internalType:`address`},{name:`salt`,type:`bytes32`,internalType:`bytes32`},{name:`extensions`,type:`uint256[]`,internalType:`uint256[]`}],stateMutability:`view`},{type:`function`,name:`getChannel`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`tuple`,internalType:`struct TempoStreamChannel.Channel`,components:[{name:`finalized`,type:`bool`,internalType:`bool`},{name:`closeRequestedAt`,type:`uint64`,internalType:`uint64`},{name:`payer`,type:`address`,internalType:`address`},{name:`payee`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`authorizedSigner`,type:`address`,internalType:`address`},{name:`deposit`,type:`uint128`,internalType:`uint128`},{name:`settled`,type:`uint128`,internalType:`uint128`}]}],stateMutability:`view`},{type:`function`,name:`getChannelsBatch`,inputs:[{name:`channelIds`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[{name:`channelStates`,type:`tuple[]`,internalType:`struct TempoStreamChannel.Channel[]`,components:[{name:`finalized`,type:`bool`,internalType:`bool`},{name:`closeRequestedAt`,type:`uint64`,internalType:`uint64`},{name:`payer`,type:`address`,internalType:`address`},{name:`payee`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`authorizedSigner`,type:`address`,internalType:`address`},{name:`deposit`,type:`uint128`,internalType:`uint128`},{name:`settled`,type:`uint128`,internalType:`uint128`}]}],stateMutability:`view`},{type:`function`,name:`getVoucherDigest`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`},{name:`cumulativeAmount`,type:`uint128`,internalType:`uint128`}],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`view`},{type:`function`,name:`open`,inputs:[{name:`payee`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`deposit`,type:`uint128`,internalType:`uint128`},{name:`salt`,type:`bytes32`,internalType:`bytes32`},{name:`authorizedSigner`,type:`address`,internalType:`address`}],outputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`}],stateMutability:`nonpayable`},{type:`function`,name:`requestClose`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`settle`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`},{name:`cumulativeAmount`,type:`uint128`,internalType:`uint128`},{name:`signature`,type:`bytes`,internalType:`bytes`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`topUp`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`},{name:`additionalDeposit`,type:`uint256`,internalType:`uint256`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`withdraw`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`}],outputs:[],stateMutability:`nonpayable`},{type:`event`,name:`ChannelClosed`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`},{name:`settledToPayee`,type:`uint256`,indexed:!1,internalType:`uint256`},{name:`refundedToPayer`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`ChannelExpired`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`}],anonymous:!1},{type:`event`,name:`ChannelOpened`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`},{name:`token`,type:`address`,indexed:!1,internalType:`address`},{name:`authorizedSigner`,type:`address`,indexed:!1,internalType:`address`},{name:`salt`,type:`bytes32`,indexed:!1,internalType:`bytes32`},{name:`deposit`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`CloseRequestCancelled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`}],anonymous:!1},{type:`event`,name:`CloseRequested`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`},{name:`closeGraceEnd`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Settled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`},{name:`cumulativeAmount`,type:`uint256`,indexed:!1,internalType:`uint256`},{name:`deltaPaid`,type:`uint256`,indexed:!1,internalType:`uint256`},{name:`newSettled`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`TopUp`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`},{name:`additionalDeposit`,type:`uint256`,indexed:!1,internalType:`uint256`},{name:`newDeposit`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`error`,name:`AmountExceedsDeposit`,inputs:[]},{type:`error`,name:`AmountNotIncreasing`,inputs:[]},{type:`error`,name:`ChannelAlreadyExists`,inputs:[]},{type:`error`,name:`ChannelFinalized`,inputs:[]},{type:`error`,name:`ChannelNotFound`,inputs:[]},{type:`error`,name:`CloseNotReady`,inputs:[]},{type:`error`,name:`DepositOverflow`,inputs:[]},{type:`error`,name:`InvalidPayee`,inputs:[]},{type:`error`,name:`InvalidSignature`,inputs:[]},{type:`error`,name:`NotPayee`,inputs:[]},{type:`error`,name:`NotPayer`,inputs:[]},{type:`error`,name:`TransferFailed`,inputs:[]}];async function ao(e,t,n){return h(e,{address:t,abi:io,functionName:`getChannel`,args:[n]})}a({abi:io,name:`open`}),a({abi:io,name:`topUp`});function oo(e,t){return t??e}function so(e,t,n,r=!1){let i=e.request.methodDetails?.escrowContract,a=n??Un[t];if(!a&&!(r&&i))throw Error("No trusted `escrowContract` available. Provide it in client parameters or use a supported chain.");if(i&&a&&i.toLowerCase()!==a.toLowerCase()&&(!r||n!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&(!a||i.toLowerCase()!==a.toLowerCase())?i:a}function co(e,t,n,r){return Et({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}async function lo(e,t,n,r,i,a,o){let s=oo(t,o),c=await no(e,t,{channelId:n,cumulativeAmount:r},i,a,s);return{action:`voucher`,channelId:n,cumulativeAmount:r.toString(),signature:c}}async function uo(e,t,n){let{escrowContract:i,payee:a,currency:o,deposit:s,initialAmount:c,chainId:l,feePayer:u}=n,d=oo(t,n.voucherSigner),f=qa(d),p=E.random(32),h=ro({authorizedSigner:f,chainId:l,escrowContract:i,payee:a,payer:t.address,salt:p,token:o}),g=r({abi:re.tip20,functionName:`approve`,args:[i,s]}),_=r({abi:io,functionName:`open`,args:[a,o,s,p,f]}),y=Math.floor(Date.now()/1e3)+25,b=await m(e,{account:t,calls:[{to:o,data:g},{to:i,data:_}],feeToken:o,nonceKey:`expiring`,validBefore:y});b.gas=(b.gas??0n)+5000n,u&&(b.feePayer=!0);let x=await v(e,b),S=await no(e,t,{channelId:h,cumulativeAmount:c},i,l,d);return{entry:{authorizedSigner:f,channelId:h,salt:p,cumulativeAmount:c,escrowContract:i,chainId:l,opened:!0},payload:{action:`open`,type:`transaction`,channelId:h,transaction:x,authorizedSigner:f,cumulativeAmount:c.toString(),signature:S}}}async function fo(e,t,n,r){try{let i=await ao(e,t,n);if(i.deposit>0n&&!i.finalized)return{authorizedSigner:BigInt(i.authorizedSigner)===0n?i.payer:i.authorizedSigner,channelId:n,salt:`0x`,cumulativeAmount:i.settled,escrowContract:t,chainId:r,opened:!0}}catch{}}const po=H.object({account:H.optional(H.custom()),action:H.optional(H.enum([`open`,`topUp`,`voucher`,`close`])),channelId:H.optional(H.string()),cumulativeAmount:H.optional(U()),cumulativeAmountRaw:H.optional(H.string()),transaction:H.optional(H.string()),additionalDeposit:H.optional(U()),additionalDepositRaw:H.optional(H.string()),depositRaw:H.optional(H.string())});function mo(e={}){let{allowCustomEscrow:t=!1,decimals:n=6}=e,r=ta({chain:F,getClient:e.getClient,rpcUrl:Wn}),i=Zi({account:e.account}),a=e.maxDeposit===void 0?void 0:f(e.maxDeposit,n),o=new Map,s=new Map,c=new Map;function l(t){e.onChannelUpdate?.(t)}function u(e,t,n){return`${e.toLowerCase()}:${t.toLowerCase()}:${n.toLowerCase()}`}function d(n,r,i){if(i){let e=o.get(i);if(e)return so(n,r,e)}return so(n,r,e.escrowContract,t)}async function p(t,i,p){let m=t.request.methodDetails,h=m?.chainId??0,g=await r({chainId:h}),_=d(t,h),v=t.request.recipient,y=t.request.currency,b=BigInt(t.request.amount),x=t.request.suggestedDeposit,S=x?BigInt(x):void 0,C=(()=>{if(p?.depositRaw)return BigInt(p.depositRaw);if(e.deposit!==void 0)return f(e.deposit,n);if(S!==void 0&&a!==void 0)return S<a?S:a;if(a!==void 0)return a;if(S!==void 0)return S;throw Error("No deposit amount available. Set `deposit`, `maxDeposit`, or ensure the server challenge includes `suggestedDeposit`.")})(),w=e.voucherSigner??i,T=u(v,y,_),E=s.get(T);if(!E){let e=p?.channelId??m?.channelId;if(e){let t=await fo(g,_,e,h);if(t){let e=p?.cumulativeAmountRaw?BigInt(p.cumulativeAmountRaw):p?.cumulativeAmount?f(p.cumulativeAmount,n):void 0;e!==void 0&&(t.cumulativeAmount=e),s.set(T,t),c.set(t.channelId,T),o.set(t.channelId,_),E=t,l(E)}else if(p?.channelId)throw Error(`Channel ${p.channelId} cannot be reused (closed or not found on-chain).`)}}E?.opened&&E.authorizedSigner.toLowerCase()!==qa(w).toLowerCase()&&(E=void 0);let D;if(E?.opened)E.cumulativeAmount+=b,D=await lo(g,i,E.channelId,E.cumulativeAmount,_,h,w),l(E);else{let e=await uo(g,i,{voucherSigner:w,escrowContract:_,payee:v,currency:y,deposit:C,initialAmount:b,chainId:h,feePayer:m?.feePayer});s.set(T,e.entry),c.set(e.entry.channelId,T),o.set(e.entry.channelId,_),D=e.payload,l(e.entry)}return co(t,D,h,i)}async function m(t,i,a){let u=t.request.methodDetails?.chainId??0,p=await r({chainId:u}),m=a.action,{channelId:h,transaction:g}=a,_=e.voucherSigner??i,v=h,y=a.cumulativeAmountRaw?BigInt(a.cumulativeAmountRaw):a.cumulativeAmount?f(a.cumulativeAmount,n):void 0,b=a.additionalDepositRaw?BigInt(a.additionalDepositRaw):a.additionalDeposit?f(a.additionalDeposit,n):void 0,x=d(t,u,v);o.set(v,x);let S;switch(m){case`open`:{if(!g)throw Error(`transaction required for open action`);if(y===void 0)throw Error(`cumulativeAmount required for open action`);let e=await no(p,i,{channelId:v,cumulativeAmount:y},x,u,_);S={action:`open`,type:`transaction`,channelId:v,transaction:g,authorizedSigner:qa(_),cumulativeAmount:y.toString(),signature:e};break}case`topUp`:if(!g)throw Error(`transaction required for topUp action`);if(b===void 0)throw Error(`additionalDeposit required for topUp action`);S={action:`topUp`,type:`transaction`,channelId:v,transaction:g,additionalDeposit:b.toString()};break;case`voucher`:{if(y===void 0)throw Error(`cumulativeAmount required for voucher action`);S=await lo(p,i,v,y,x,u,_);let e=c.get(v);if(e){let t=s.get(e);t&&(t.cumulativeAmount=t.cumulativeAmount>y?t.cumulativeAmount:y,l(t))}break}case`close`:{if(y===void 0)throw Error(`cumulativeAmount required for close action`);let e=await no(p,i,{channelId:v,cumulativeAmount:y},x,u,_);S={action:`close`,channelId:v,cumulativeAmount:y.toString(),signature:e};let t=c.get(v);if(t){let e=s.get(t);e&&(e.opened=!1,e.cumulativeAmount=e.cumulativeAmount>y?e.cumulativeAmount:y,l(e))}break}}return co(t,S,u,i)}return Mt(Ha,{canHandleChallenge({challenge:e}){let t=Je(e.request.methodDetails,Ke.sessionProtocol);return t===void 0||t===qe.v1},context:po,async createCredential({challenge:t,context:n}){let o=t.request.methodDetails?.chainId??0,s=await r({chainId:o}),c=i(s,n);if(!n?.action&&(e.deposit!==void 0||a!==void 0))return p(t,c,n);if(n?.action)return m(t,c,n);throw Error("No `action` in context and no `deposit` or `maxDeposit` configured. Either provide context with action/channelId/cumulativeAmount, or configure `deposit`/`maxDeposit` for auto-management.")}})}const ho=(1n<<96n)-1n;function go(e){return e>=0n&&e<=ho}function _o(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return go(t)?t:void 0}function vo(e){return yo(e),e}function yo(e){if(!go(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const bo=new Set([`open`,`topUp`,`voucher`,`close`]);function xo(e){return typeof e==`object`&&!!e}function So(e){return typeof e==`string`&&bo.has(e)}function Co(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!So(t.action))}function wo(e,t=`No session credential context available.`){if(!Co(e))throw Error(t);return e}function To(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function Eo(e){return xo(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function Do(e){return xo(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 Oo(e){let t=C.toString(e),n=JSON.parse(t);if(!Do(n))throw Error(`Invalid session receipt.`);return n}function ko(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function Ao(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,getAddress as a,hashTypedData as o,http as s,isAddress as c,isAddressEqual as l,parseAbi as u,parseUnits as d}from"viem";import{call as f,prepareTransactionRequest as p,readContract as m,sendCallsSync as h,sendTransactionSync as g,signTransaction as _,signTypedData as v}from"viem/actions";import*as y from"viem/chains";import{tempo as b}from"viem/chains";import{AbiParameters as x,Base64 as S,Bytes as C,Hash as w,Hex as T,Json as E}from"ox";import{z as D}from"zod/mini";import*as O from"node:child_process";import*as k from"node:fs";import*as A from"node:os";import*as j from"node:path";import{z as M}from"zod";import"node:readline";import{tempo as N,tempoModerato as ee}from"viem/tempo/chains";import{ousd as te,pathusd as ne,usdce as re}from"viem/tokens";import{Abis as ie,Account as ae,Actions as P,Addresses as oe,TokenId as se,Transaction as ce,withFeePayer as le}from"viem/tempo";import{parseAccount as ue,privateKeyToAccount as de}from"viem/accounts";import{createParser as fe}from"eventsource-parser";import{Channel as pe,KeyAuthorization as F,SignatureEnvelope as I,TempoAddress as me,TxEnvelopeTempo as he}from"ox/tempo";var ge=Object.defineProperty,_e=Object.getOwnPropertyDescriptor,ve=Object.getOwnPropertyNames,ye=Object.prototype.hasOwnProperty,be=(e,t)=>{let n={};for(var r in e)ge(n,r,{get:e[r],enumerable:!0});return t||ge(n,Symbol.toStringTag,{value:`Module`}),n},xe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=ve(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ye.call(e,s)&&s!==n&&ge(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=_e(t,s))||r.enumerable});return e},Se=(e,t,n)=>(xe(e,t,`default`),n&&xe(n,t,`default`));const Ce=Symbol(`mppx.x402.asset`);function L(e){return{[Ce]:!0,address:e.address,decimals:e.decimals,network:e.network,transfer:e.transfer}}function we(e,t){let n=e(t.chainId);return L({address:n.address,decimals:n.decimals,network:Pe(t.chainId),transfer:Ie(t.transfer,n)})}const Te={USDC:L({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},Ee={USDC:L({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},De={USDC:L({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:L({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},Oe={USDC:L({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})};function ke(e){return typeof e!=`object`||!e?!1:e[Ce]===!0}function Ae(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function je(e){return typeof e==`string`}function Me(e,t){if(ke(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(Ae(e)){let n=e.addresses[Fe(t)];return n?{address:n,decimals:e.decimals,name:e.name}:void 0}return{address:e}}function Ne(e,t,n){let r=Me(e,n);return r?a(r.address)===a(t):!1}function Pe(e){return`eip155:${e}`}function Fe(e){return Number(e.slice(7))}function Ie(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 Le=be({base:()=>Te,baseSepolia:()=>Ee,celo:()=>De,celoSepolia:()=>Oe,define:()=>L,fromToken:()=>we,isAsset:()=>ke,isRawAddress:()=>je,isToken:()=>Ae,matches:()=>Ne,resolve:()=>Me,toChainId:()=>Fe,toNetwork:()=>Pe}),Re=be({base:()=>ze,baseSepolia:()=>Be,celo:()=>Ve,celoSepolia:()=>He});const ze=8453,Be=84532,Ve=42220,He=11142220,R={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},Ue={payment:`Payment`},We={evm:`evm`,stripe:`stripe`,tempo:`tempo`},Ge={charge:`charge`,session:`session`,subscription:`subscription`},Ke={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},qe={v1:`v1`,v2:`v2`};function Je(e,t){if(!(!e||typeof e!=`object`))return e[t]}function Ye(e){let t=S.toString(e);return JSON.parse(t)}function z(e){let t=E.canonicalize(e);return S.fromString(t,{pad:!1,url:!0})}var B=be({address:()=>H,amount:()=>V,datetime:()=>Ze,datetimeInput:()=>Qe,hash:()=>U,period:()=>tt,signature:()=>W,toDate:()=>$e,toDatetimeString:()=>et,unwrapOptional:()=>nt});import*as Xe from"zod/mini";Se(B,Xe);function V(){return D.string().check(D.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function Ze(){return D.string().check(D.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 Qe(e=`Invalid ISO 8601 datetime`){return D.pipe(D.union([Ze(),D.custom(e=>e instanceof Date)]),D.transform($e)).check(D.refine(e=>Number.isFinite(e.getTime()),e))}function $e(e){return e instanceof Date?e:new Date(e)}function et(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function H(){return D.string().check(D.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function U(){return D.string().check(D.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function tt(){return D.string().check(D.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function W(){return D.string().check(D.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function nt(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}const rt=B.object({description:B.optional(B.string()),digest:B.optional(B.string().check(B.regex(/^sha-256=/,`Invalid digest format`))),expires:B.optional(Ze()),header:B.optional(B.string().check(B.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,`Invalid HTTP header name`))),id:B.string().check(B.minLength(1)),intent:B.string(),method:B.string(),meta:B.optional(B.record(B.string(),B.string())),opaque:B.optional(B.string()),realm:B.string(),request:B.record(B.string(),B.unknown())});function it(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=vt(o)?void 0:o,f=e.expires?et(e.expires):void 0,p=e.opaque??(i===void 0?void 0:z(i)),m=u?yt({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return rt.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 at(e){let t=[G(`id`,e.id),G(`realm`,e.realm),G(`method`,e.method),G(`intent`,e.intent),G(`request`,z(e.request))];e.description!==void 0&&t.push(G(`description`,e.description)),e.digest!==void 0&&t.push(G(`digest`,e.digest)),e.expires!==void 0&&t.push(G(`expires`,e.expires));let n=e.header;return n!==void 0&&!vt(n)&&t.push(G(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(G(`opaque`,z(e.meta))):t.push(G(`opaque`,e.opaque)),`${Ue.payment} ${t.join(`, `)}`}function G(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 ot(e,t){let n=st(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=ct(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 it({...a,request:Ye(r),...i&&{opaque:i}},t)}function st(e){let t=Ue.payment,[n]=ft(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 ct(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]=lt(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function lt(e,t){if(e[t]===`"`)return ut(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function ut(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 dt(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 ft(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(!dt(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 pt(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return mt(e.headers,t)}function mt(e,t){let n=e.get(R.wwwAuthenticate);if(!n)throw Error(`Missing ${R.wwwAuthenticate} header.`);return ht(n,t)}function ht(e,t){let n=ft(e,Ue.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 ot(e.slice(r,a).replace(/,\s*$/,``),t)})}function gt(e){let t=[e.realm,e.method,e.intent,z(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!vt(n)&&t.push(n),t.push(e.opaque??(e.meta?z(e.meta):``)),t.join(`|`)}function _t(e){return e.header??R.authorization}function vt(e){return e?.toLowerCase()===R.authorization.toLowerCase()}function yt(e,t){let n=gt(e),r=C.fromString(t.secretKey),i=C.fromString(n),a=w.hmac256(r,i,{as:`Bytes`});return S.fromBytes(a,{url:!0,pad:!1})}var bt=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},xt=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function St(e){let t=e.match(RegExp(`^${Ue.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new bt;try{let e=S.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=Ct(r);return{challenge:rt.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:Ye(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new xt}}function Ct(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!wt(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:z(e)}}function wt(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function Tt(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function Et(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:z(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:z(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=S.fromString(s,{pad:!1,url:!0});return`${Ue.payment} ${c}`}var Dt=class extends Error{details;status=402;hint;constructor(e,t={}){super(e),this.details=t.details}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}.`)}},K=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.`)}};function At(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(new Date(e)<new Date)throw new kt({expires:e})}function jt(e){return e}function Mt(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}function Nt(e){return{encode(t){return S.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(S.toString(t)))}catch{throw new Pt}}}}var Pt=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const Ft=[`exact`],It=`PAYMENT-REQUIRED`,Lt=`PAYMENT-SIGNATURE`,Rt=B.string().check(B.minLength(1)),zt=B.number().check(B.refine(e=>e>0,`Must be positive`)),q=B.string().check(B.regex(/^\d+$/,`Invalid atomic amount`)),Bt=H(),Vt=B.string().check(B.regex(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),Ht=B.object({description:B.optional(B.string()),iconUrl:B.optional(B.string()),mimeType:B.optional(B.string()),serviceName:B.optional(B.string()),tags:B.optional(B.array(B.string())),url:Rt});B.discriminatedUnion(`type`,[B.object({name:Rt,type:B.literal(`eip3009`),version:Rt}),B.object({name:B.optional(B.string()),type:B.literal(`permit2`),version:B.optional(B.string())})]);const Ut=B.object({amount:q,asset:Rt,extra:B.optional(B.record(B.string(),B.unknown())),maxTimeoutSeconds:zt,network:Vt,payTo:Rt,scheme:B.enum(Ft)}),Wt=B.object({info:B.record(B.string(),B.unknown()),schema:B.record(B.string(),B.unknown())}),Gt=B.record(B.string(),Wt),Kt=B.object({accepts:B.array(Ut).check(B.minLength(1)),error:B.optional(B.string()),extensions:B.optional(Gt),resource:Ht,x402Version:B.literal(2)}),qt=B.object({authorization:B.object({from:Bt,nonce:U(),to:Bt,validAfter:q,validBefore:q,value:q}),signature:W()}),Jt=B.object({permit2Authorization:B.object({deadline:q,from:Bt,nonce:q,permitted:B.object({amount:q,token:Bt}),spender:Bt,witness:B.object({to:Bt,validAfter:q})}),signature:W()}),Yt=B.union([qt,Jt]),Xt=B.object({accepted:Ut,extensions:B.optional(Gt),payload:Yt,resource:B.optional(Ht),x402Version:B.literal(2)});B.object({extensions:B.optional(Gt),extra:B.optional(B.record(B.string(),B.unknown())),invalidMessage:B.optional(B.string()),invalidReason:B.optional(B.string()),isValid:B.boolean(),payer:B.optional(B.string())});const Zt=B.object({amount:B.optional(q),errorMessage:B.optional(B.string()),errorReason:B.optional(B.string()),extensions:B.optional(Gt),extra:B.optional(B.record(B.string(),B.unknown())),network:Rt,payer:B.optional(B.string()),success:B.boolean(),transaction:B.string()});function Qt(e){let{extensions:t,resource:n,...r}=e;return Ut.parse(r)}const $t=Nt(Kt),en=Nt(Xt),tn=Nt(Zt);$t.encode,$t.decode;function nn(e){try{let t=JSON.parse(S.toString(e));return an(t)}catch{throw new Pt}}const rn=en.encode;en.decode,tn.encode,tn.decode;const an=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new Pt;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new Pt;let n=Ht.parse(t.resource),r=t.extensions===void 0?void 0:Gt.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}};function on(e){let t=[z(e.accepted),z(e.resource),z(e.extensions)].join(`|`);return w.sha256(C.fromString(t),{as:`Hex`})}async function sn(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=Qt(n);if(dn(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?pn(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?on({accepted:r,extensions:i,resource:n.resource}):hn(),to:a(r.payTo),validAfter:(l-600).toString(),validBefore:(l+r.maxTimeoutSeconds).toString(),value:r.amount},d=await t.signTypedData({domain:{chainId:un(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:ln});return rn({accepted:r,...i?{extensions:i}:{},payload:{authorization:u,signature:d},...n.resource?{resource:n.resource}:{},x402Version:2})}function cn(e){let t=e.challenge.request,n;try{n=Qt(t),dn(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 ln={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 un(e){return Number(e.slice(7))}function dn(e,t){let n=un(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=>je(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=a(t.asset);if(!r.some(n=>Ne(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=fn(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>d(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function fn(e,t){let n=e.currencies??e.assets,r=a(t.asset),i=n?.find(e=>Ne(e,r,t.network)),o=i?Me(i,t.network):void 0;return o?.decimals===void 0?e.decimals:o.decimals}function pn(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:mn()}}}:e}function mn(){return gn().slice(2)}function hn(){return gn()}function gn(){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 _n=Symbol.for(`mppx.x402.challenge`);function vn(e){return Object.defineProperty(e,_n,{value:!0}),e}function yn(e){return!!e?.[_n]}const bn=[`authorization`],xn=B.string().check(B.regex(/^\d+$/,`Invalid atomic amount`));B.object({name:B.string().check(B.minLength(1)),version:B.string().check(B.minLength(1))});const Sn=B.object({chainId:B.number(),credentialTypes:B.optional(B.array(B.enum(bn)).check(B.minLength(1))),decimals:B.optional(B.number()),permit2Address:B.optional(H()),splits:B.optional(B.array(B.object({amount:xn,recipient:H()})))});B.object({amount:xn,currency:H(),description:B.optional(B.string()),externalId:B.optional(B.string()),methodDetails:Sn,recipient:H()});const Cn=B.object({amount:V(),chainId:B.number(),currency:H(),credentialTypes:B.optional(B.array(B.enum(bn)).check(B.minLength(1))),decimals:B.number(),description:B.optional(B.string()),externalId:B.optional(B.string()),permit2Address:B.optional(H()),recipient:H(),splits:B.optional(B.array(B.object({amount:xn,recipient:H()})))}),wn=B.object({from:H(),nonce:U(),signature:W(),to:H(),type:B.literal(`authorization`),validAfter:xn,validBefore:xn,value:xn}),Tn={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 En(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function Dn(e){return w.keccak256(C.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function On(e){return`eip155:${e}`}function kn(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const An=jt({name:`evm`,intent:`charge`,schema:{credential:{payload:wn},request:B.pipe(Cn,B.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:o,recipient:s,splits:c,...l})=>({...l,amount:d(e,i).toString(),currency:a(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...o?{permit2Address:a(o)}:{},...c?{splits:c}:{}},recipient:a(s)})))}});function jn(e){return Mt(An,{canHandleChallenge({challenge:t}){return!Mn(t)||cn({challenge:t,config:e})},context:B.object({account:B.optional(B.custom())}),async createCredential({challenge:t,context:n}){if(Mn(t))return sn({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(Nn(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=Pn(e,i),s=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return Et(Tt({challenge:t,payload:{from:a(r.address),nonce:Dn(t),signature:await r.signTypedData({domain:En({authorization:o,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:a(r.address),nonce:Dn(t),to:a(i.recipient),validAfter:0n,validBefore:BigInt(s),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:Tn}),to:a(i.recipient),type:`authorization`,validAfter:`0`,validBefore:s,value:i.amount},source:kn({address:a(r.address),chainId:i.methodDetails.chainId})}))}})}function Mn(e){return yn(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function Nn(e,t){let n=t.methodDetails.chainId,r=On(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=>je(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=a(t.currency);if(!i.some(t=>Ne(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=Fn(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>d(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function Pn(e,t){let n=e.currencies??e.assets,r=a(t.currency),i=On(t.methodDetails.chainId),o=n?.find(e=>Ne(e,r,i)),s=o?Me(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 Fn(e,t){let n=e.currencies??e.assets,r=a(t.currency),i=On(t.methodDetails.chainId),o=n?.find(e=>Ne(e,r,i)),s=o?Me(o,i):void 0;return s?.decimals===void 0?e.decimals:s.decimals}function In(e){return[In.charge(e)]}(function(e){e.charge=jn,e.assets=Le,e.chains=Re})(In||={});var Ln=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 Rn(this,e)}},J=class extends Ln{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 Rn(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 Y={mainnet:4217,testnet:42431},zn={ousd:te(Y.mainnet).address,usdc:a(re(Y.mainnet).address),pathUsd:ne(Y.mainnet).address},Bn={[Y.mainnet]:zn.usdc,[Y.testnet]:zn.pathUsd},Vn=Object.freeze({[Y.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[Y.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})});Y.mainnet,Y.testnet;const Hn={[Y.mainnet]:`https://rpc.tempo.xyz`,[Y.testnet]:`https://rpc.moderato.tempo.xyz`},X=(()=>{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:X.underline(t)}\x1b]8;;\x07`:t}}})();function Un(e,t){return X.link(e,t)}function Wn(e){return e.startsWith(`tempo:`)}function Gn(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?X.dim(X.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):X.dim(t);return`${a?`${o}.${a}`:o} ${s}`}const Kn={mainnet:Hn[Y.mainnet],testnet:Hn[Y.testnet]};function qn(e,t={}){return e??(t.network?Kn[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}async function Jn(t={}){let n=qn(t.rpcUrl,{network:t.network});if(!n)return N;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 Yn(e){return typeof e==`bigint`?e:e.amount}function Xn(e){return e.id!==N.id}async function Zn(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(Yn).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 Qn(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:1e4}function $n(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function er(e){return new J({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 tr(e){if(e&&$n(e,`secret-tool`))throw er(e)}function Z(e,t){return new Promise(n=>{O.execFile(e,t,{timeout:Qn()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function nr(){let e=j.join(process.env.XDG_CONFIG_HOME||j.join(A.homedir(),`.config`),`mppx`,`default`);return{get(){try{return k.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(t){k.mkdirSync(j.dirname(e),{recursive:!0}),k.writeFileSync(e,t,`utf-8`)},clear(){try{k.unlinkSync(e)}catch{}}}}function rr(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:nr().get())}function ir(e=`main`){let t=`mppx`;return{async list(){let e=A.platform();if(e===`darwin`){let{stdout:e,error:n}=await Z(`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 Z(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(tr(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=A.platform();if(n===`darwin`){let{stdout:n,error:r}=await Z(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await Z(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return tr(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=A.platform();if(r===`darwin`){await Z(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await Z(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=O.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),Qn());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($n(e,`secret-tool`)?er(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=A.platform();if(n===`darwin`){await Z(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await Z(`secret-tool`,[`clear`,`service`,t,`account`,e]);tr(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function ar(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=rr(e),i=await ir(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function or(e){return(await ar(e)).account}function sr(e){return e}function cr(){return sr({method:`evm`,supports:e=>e.method===`evm`&&!yn(e),async setup({challenge:t}){let n=t.request,r=n.methodDetails,a=r?.chainId,o=a?lr(a):void 0,c=n.currency,l=await or(),u=[...Object.values(Te),...Object.values(Ee),...Object.values(De),...Object.values(Oe)],d=c??``;if(o&&c)try{let t=e({chain:o,transport:s()}),n=await m(t,{address:c,abi:i,functionName:`symbol`});n&&(d=n)}catch{}return{tokenSymbol:d,tokenDecimals:r?.decimals??6,explorerUrl:o?.blockExplorers?.default?.url,methods:[...In({account:l,currencies:u})]}}})}function lr(e){return Object.values(y).find(t=>t.id===e)}function ur(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 dr=B.object({customer:B.optional(B.string().check(B.minLength(1))),hooks:B.optional(B.object({inputs:B.object({tax:B.object({calculation:B.string().check(B.minLength(1))})})})),metadata:B.optional(B.record(B.string(),B.string())),receipt_email:B.optional(B.string().check(B.minLength(1)))}),fr=B.custom(e=>typeof e==`function`),pr=B.union([dr,fr]),mr=jt({name:`stripe`,intent:`charge`,schema:{credential:{payload:B.object({externalId:B.optional(B.string()),spt:B.string()})},request:B.pipe(B.object({amount:V(),currency:B.string(),decimals:B.number(),description:B.optional(B.string()),externalId:B.optional(B.string()),metadata:B.optional(B.record(B.string(),B.string())),networkId:B.string(),paymentIntentOptions:B.optional(pr),paymentMethodTypes:B.array(B.string()).check(B.minLength(1)),recipient:B.optional(B.string())}),B.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:ur(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});function hr(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return Mt(mr,{context:B.object({paymentMethod:B.optional(B.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 Et({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function gr(e){return[hr(e)]}(function(e){e.charge=hr})(gr||={});function _r(){return sr({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=yr(M.object({paymentMethod:M.string(),secretKey:M.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new J({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:[gr.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=vr(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 J({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${(await d.json()).error.message}`,exitCode:77})}else throw new J({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&&vr(e)?`/test`:``}/payments/${t}`;return X.link(n,t,!0)}}})}function vr(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function yr(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 br(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=Tr(n)}return t}function xr(e,t){let n=br(e),r=Mr(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[Tr(e)]??1,index:t}));return{definition:r,entries:i,header:Cr(i),keys:n}}function Sr(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)=>Ar(e,t))}function Cr(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${Ir(n)}`}).join(`, `)}function wr(e,t,n){let r=new Map;for(let e of t){let t=Tr(e),n=r.get(t);n?n.push(e):r.set(t,[e])}return e.flatMap((e,t)=>{let i=r.get(Tr(e));if(!i)return[];let a=Er(e,n);return!a||a.q<=0?[]:i.filter(t=>t.canHandleChallenge?.({challenge:e})??!0).map(n=>({challenge:e,index:t,match:a,method:n}))}).sort((e,t)=>kr(e.challenge)-kr(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function Tr(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function Er(e,t){let n;for(let r of t){if(!Dr(e,r))continue;let t={...r,specificity:Or(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 Dr(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function Or(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function kr(e){return+!!yn(e)}function Ar(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}`);Lr(r,`method`),Lr(i,`intent`);let a=1;for(let t of jr(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=Pr(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function jr(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function Mr(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>Tr(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]=Nr(t,`payment preference "${e}"`)}return a}function Nr(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return Fr(e,t)}function Pr(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 Fr(Number(e),t)}function Fr(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 Ir(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function Lr(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}const Rr=[R.authorization,It,`PAYMENT-RESPONSE`,Lt];function zr(e,t,n){let r=new Headers(e.headers);for(let e of Rr)e===R.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}function Br(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}}const Vr=new WeakMap;function Hr(e){let t=Br(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 Ur(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 Wr(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=rt.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 Gr(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:Wr(e.error.data):Wr(e.result?._meta?.[`org.paymentauth/payment-required`])}function Kr(e,t){return!e||e.id!==t?[]:Gr(e)?.challenges??[]}async function qr(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=!1,i,a=fe({onEvent(e){if(!(r||!e.data)&&(r=!0,!(e.event&&e.event!==`message`)))try{i=Ur(JSON.parse(e.data))}catch{}}});try{for(;;){if(r)return i;let{done:e,value:o}=await t.read();if(e)return a.feed(n.decode()),a.reset({consume:!0}),i;a.feed(n.decode(o,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}function Jr(e){let t=Vr.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(t.includes(`application/json`))return e.clone().json().then(Ur).catch(()=>void 0);if(t.includes(`text/event-stream`))return qr(e)})();return Vr.set(e,n),n}function Yr(){return{getChallenges(e,t){let n=Hr(t);return e.status===402||n===void 0?[]:Jr(e).then(e=>Kr(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=St(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}function Xr(){return{getChallenges(e){return e.status!==402||!e.headers.has(R.wwwAuthenticate)?[]:pt(e)},setCredential(e,t,n){return zr(e,n?.challenge?_t(n.challenge):R.authorization,t)}}}function Zr(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(It);if(!t)return[];let n=nn(t);return n.accepts.flatMap((e,t)=>{let r=Ut.safeParse(e);if(!r.success)return[];let i=r.data;return vn(it({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 zr(e,Lt,t)}}}function Qr(e){return e}function $r(){let e=[Xr(),Zr(),Yr()],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 Qr({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 ei=new WeakMap;function ti(e,t){return ei.set(e,t),e}function ni(e){return ei.has(e)}function ri(e,t){return Promise.resolve(ei.get(e)?.(t))}const ii=new WeakMap,ai=new WeakMap;function oi(e,t){return ii.set(e,t),e}function si(e){ii.delete(e)}function ci(e,t,n){ii.has(e)&&ai.set(t,n)}function li(e){return ai.get(e)}function ui(e,t){return Promise.resolve(ii.get(e)?.(t)??t.response)}const di=Symbol.for(`mppx.fetch.wrapper`),fi=new WeakMap;async function pi(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 mi(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=$r()}=e,l=e.eventDispatcher??hi(),u=t??xr(a),d=Ii(r),f=async(e,t,r)=>{let p=Fi(e,t?.headers),m=p.has(R.acceptPayment),h=Vi(p,u),g=Ni(e,t,p),_=Mi(e,t,p,h.header,m,n),v=await d(Li(_.input),_.init),y=Pi(_.init,await g);if(!await c.isPaymentRequired(v,y))return v;let b=t?.context,{context:x,orderChallenges:S,...C}=y??{},w,T,E,D;try{for(let n=0;n<i;n++){T=await c.getChallenges(v,y);let i=(await Hi(wr(T,a,h.entries),S??s))[0];if(!i){if(await pi(D,{challenges:T,response:v,status:`rejected`}),n>0)return v;throw Error(`No method found for challenges: ${T.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let u=i.challenge;w=u,E=i.method,w.expires&&At(w.expires,w.id);let p=qi(v,_.input,_.input),m=D,g=at(u),x=m?.method===i.method&&m?.key===g,O=!1;if(m){let e=await pi(m,{challenges:T,response:v,status:x?`pending`:`rejected`});O=x&&!e}D=O?m:void 0;let k=bi(async n=>{if(n===void 0&&O&&m)return m.promise;O&&m&&(await pi(m,{status:`rejected`}),D=void 0);let r=n??b;if(!ni(i.method))return Bi(u,i.method,r);let a={prepare:()=>ri(i.method,{challenge:u,context:r,fetch:d,input:p,signal:Ri(e,t)})},o=a.prepare().then(()=>Bi(u,i.method,r,a));return D={attempt:a,key:n===void 0?g:void 0,method:i.method,promise:o},o}),A=await l.emit(`challenge.received`,xi({challenge:u,challenges:T,createCredential:k,init:t,input:e,method:i.method,response:v}))??(o?await o(w,{createCredential:k}):void 0)??await k(),j=D;j&&await j.promise.catch(()=>void 0)!==A&&(await pi(j,{status:`rejected`}),D=void 0),zi(A),await l.emit(`credential.created`,Si({challenge:u,credential:A,init:t,input:e,method:i.method,response:v})),v=await d(p,c.setCredential({...C,headers:_.headers},A,{challenge:u}));let M=await c.isPaymentRequired(v,y);if(M||(await pi(j,{response:v,status:v.ok?`accepted`:`rejected`}),D=void 0),v.ok&&gi(l,`payment.response`)&&await l.emit(`payment.response`,Ci({challenge:u,credential:A,init:t,input:e,method:i.method,response:v})),!M)return v.ok?ui(i.method,{challenge:u,credential:A,fetch:d,headers:_.headers,input:p,...r?{refetch:()=>f(Li(_.input),t,!1)}:{},response:v,signal:Ri(e,t)}):v}T=void 0;try{T=await c.getChallenges(v,y)}catch{}return await pi(D,{challenges:T,response:v,status:`rejected`}),v}catch(n){throw await pi(D,{challenges:T,response:v,status:`rejected`}),await l.emit(`payment.failed`,wi({challenge:w,challenges:T,error:n,init:t,input:e,method:E,response:v})),n}},p=(e,t)=>f(e,t,!0);return p[di]=d,p}function Q(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 hi(){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 _i(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await yi(e[`*`],t,n),r}case`credential.created`:await vi(e[`credential.created`],n),await yi(e[`*`],t,n);return;case`payment.failed`:await vi(e[`payment.failed`],n),await yi(e[`*`],t,n);return;case`payment.response`:await vi(e[`payment.response`],n),await yi(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 fi.set(t,t=>e[t].size>0||e[`*`].size>0),t}function gi(e,t){return fi.get(e)?.(t)??!0}async function _i(e,t){try{return await e(t)}catch{return}}async function vi(e,t){for(let n of e)try{await n(t)}catch{}}async function yi(e,t,n){await vi(e,Object.freeze({name:t,payload:n}))}function bi(e){let t;return n=>(t??=e(n),t)}function xi(e){return Object.freeze({challenge:ki(e.challenge),challenges:e.challenges.map(e=>ki(e)),createCredential:e.createCredential,init:Ti(e.init),input:Ei(e.input),method:Di(e.method),response:Oi(e.response)})}function Si(e){return Object.freeze({challenge:ki(e.challenge),credential:e.credential,init:Ti(e.init),input:Ei(e.input),method:Di(e.method),...e.response===void 0?{}:{response:Oi(e.response)}})}function Ci(e){return Object.freeze({challenge:ki(e.challenge),credential:e.credential,init:Ti(e.init),input:Ei(e.input),method:Di(e.method),response:Oi(e.response)})}function wi(e){return Object.freeze({...e.challenge?{challenge:ki(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>ki(e))}:{},error:e.error,init:Ti(e.init),input:Ei(e.input),...e.method?{method:Di(e.method)}:{},...e.response===void 0?{}:{response:Oi(e.response)}})}function Ti(e){if(e)return ji({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function Ei(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function Di(e){return ji(Object.assign({},e))}function Oi(e){return e instanceof Response?e.clone():ki(e)}function ki(e){try{return Ai(structuredClone(e))}catch{return ji(e)}}function Ai(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Ai(t);return e}function ji(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function Mi(e,t,n,r,i,a){let o=!!r&&!i&&Ui(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(R.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function Ni(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 Pi(e,t){return t===void 0?e:{...e,body:t}}function Fi(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function Ii(e){let t=e;for(;t[di];)t=t[di];return t}function Li(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function Ri(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function zi(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
|
|
2
|
+
`))throw Error(`Credential header value contains illegal newline characters`)}async function Bi(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&&ci(t,a,r),t.createCredential(a)}function Vi(e,t){let n=e.get(R.acceptPayment);if(!n)return t;try{return{...t,entries:Sr(n),header:n}}catch{return t}}async function Hi(e,t){return t?t(e):e}function Ui(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=Ki(e);return t===`same-origin`?!Gi()||n.origin===globalThis.location.origin:t.origins.some(e=>Wi(n,e))}function Wi(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 Gi(){return globalThis.location!==void 0}function Ki(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,Gi()?globalThis.location.href:void 0)}function qi(e,t,n){if(!e.url)return t;let r=new URL(e.url),i=Ki(n);if(r.origin!==i.origin)throw Error(`Refusing to send payment credential across redirect from ${i.origin} to ${r.origin}`);return e.url}function Ji(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 ue(r)}}function Yi(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}const Xi={[N.id]:N,[ee.id]:ee};function Zi(e,t={}){return s(e.url,{fetchFn:e.fetch,fetchOptions:{headers:Yi(e)},...t})}function Qi(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=le(n({request:t=>e(t)},{retryCount:0}),Zi(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?le(s(r),Zi(o)):s(r);return e({chain:Xi[n]??{...i,id:n},transport:a})}}function $i(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 ea(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}const ta=T.slice(w.keccak256(C.fromString(`mpp`),{as:`Hex`}),0,4);function na(e){let t=w.keccak256(C.fromString(e),{as:`Hex`});return T.toBytes(T.slice(t,0,10))}function ra(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(T.toBytes(ta),0),i[4]=1,i.set(na(t),5),n&&i.set(na(n),15),i.set(ia(r),25),T.fromBytes(i)}function ia(e){let t=w.keccak256(C.fromString(e),{as:`Hex`});return T.toBytes(T.slice(t,0,7))}function aa(e,t){return me.resolve(e).toLowerCase()===me.resolve(t).toLowerCase()}const oa=[zn.pathUsd,zn.usdc];async function sa(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t,s=a.filter(e=>!aa(e,i)),c=await Promise.allSettled([m(e,P.token.getBalance.call(e,{account:n,token:i})),...s.map(t=>m(e,P.token.getBalance.call(e,{account:n,token:t})))]),l=c[0];if(!(l.status===`fulfilled`&&l.value>=r)){for(let t=0;t<s.length;t++){let n=c[t+1];if(n.status!==`fulfilled`)continue;let a=n.value;if(a<=0n)continue;let l=s[t];try{let t=await P.dex.getBuyQuote(e,{tokenIn:l,tokenOut:i,amountOut:r});if(a>=t){let n=t+t*BigInt(Math.round(o*100))/10000n;return[P.token.approve.call(e,{amount:n,spender:oe.stablecoinDex,token:l}),P.dex.buy.call({tokenIn:l,tokenOut:i,amountOut:r,maxAmountIn:n})]}}catch{}}throw new la({currency:i})}}function ca(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...t.filter(t=>!e.tokenIn.some(e=>aa(e,t)))]:t,slippage:e.slippage??1}:!1}var la=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}};function ua(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:e.amount,memo:e.memo,recipient:e.recipient}))]}function da(e,t,n){t&&(n&&!n.some(e=>aa(e,t))||e.some(e=>aa(e,t))||e.push(t))}async function fa(e,t,n){try{return(await P.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function pa(e){let t=e.chain?.feeToken;if(t)return se.toAddress(t);let n=e.chain?.id;return n?Bn[n]:void 0}function ma(e){let t=[];return da(t,zn.pathUsd),da(t,Bn[e]),t}async function ha(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])da(o,e,n);if(da(o,await P.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),da(o,pa(i),n),!a)for(let e of r??[])da(o,e,n);for(let e of o)if(await fa(i,t,e))return e;return o[0]}const ga=u([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]);function _a(e){if(e!==void 0)return Vn[e]}function va(e){let t=_a(e.chainId);return!!t&&c(e.currency,{strict:!1})&&l(e.currency,t.token)}function ya(e){let t=_a(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:ie.tip20,functionName:`approve`,args:[t.swap,i]}),to:t.token},{data:r({abi:ga,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 ba(e,t){let n=ya(t);if(n)try{return await m(e,P.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await f(e,{account:t.account,calls:n.calls}),n)}catch{return}}const xa={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]};function Sa(e){return{name:`MPP`,version:`3`,chainId:e}}function Ca(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function wa(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:Sa(n),types:xa,primaryType:`Proof`,message:Ca({account:t,challengeId:r,realm:i})}}function Ta(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const Ea=[`push`,`pull`],Da=B.object({amount:V(),memo:B.optional(U()),recipient:B.pipe(B.string(),B.transform(e=>e))}),Oa=(1n<<64n)-1n,ka={dev_second:1n,day:86400n,week:604800n},Aa=B.pipe(H(),B.transform(e=>e.toLowerCase())),ja=B.object({accessKeyAddress:Aa,keyType:B.enum([`p256`,`secp256k1`,`webAuthn`])}),Ma=B.object({accessKey:B.optional(ja),chainId:B.optional(B.number())}),Na=Qe(`subscriptionExpires must be a valid date`).check(B.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),Pa=B.enum([`dev_second`,`day`,`week`]),Fa=B.pipe(B.union([B.string(),B.bigint(),B.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),B.transform(e=>e.toString())).check(B.regex(/^[1-9]\d*$/,`Invalid periodCount`),B.refine(e=>{try{return BigInt(e)<=Oa}catch{return!1}},`periodCount exceeds uint64`));function Ia(e){return B.refine(e=>{let{amount:t,decimals:n}=e;return d(t,n)>0n},e)}function La(e){let{periodCount:t,periodUnit:n}=e;try{let e=ka[n];return e!==void 0&&BigInt(t)*e<=Oa}catch{return!1}}const Ra=jt({name:`tempo`,intent:`charge`,schema:{credential:{payload:B.discriminatedUnion(`type`,[B.object({hash:U(),type:B.literal(`hash`)}),B.object({signature:W(),type:B.literal(`transaction`)}),B.object({signature:W(),type:B.literal(`proof`)})])},request:B.pipe(B.object({machineTokenEnabled:B.optional(B.boolean()),amount:V(),chainId:B.optional(B.number()),currency:B.string(),decimals:B.number(),description:B.optional(B.string()),externalId:B.optional(B.string()),feePayer:B.optional(B.pipe(B.union([B.boolean(),B.custom()]),B.transform(e=>typeof e==`object`||e))),memo:B.optional(B.never()),recipient:B.optional(B.string()),splits:B.optional(B.array(Da).check(B.minLength(1),B.maxLength(10))),supportedModes:B.optional(B.array(B.enum(Ea)).check(B.minLength(1)))}).check(B.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=d(e,t),i=n.reduce((e,n)=>e+d(n.amount,t),0n);return n.every(e=>d(e.amount,t)>0n)&&i<r},`Invalid splits`)),B.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,...c})=>({...c,amount:d(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:d(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s}}}:{}})))}}),za=jt({name:`tempo`,intent:`session`,schema:{credential:{payload:B.discriminatedUnion(`action`,[B.object({action:B.literal(`open`),authorizedSigner:B.optional(B.string()),channelId:U(),cumulativeAmount:V(),descriptor:B.optional(B.custom()),signature:W(),transaction:W(),type:B.literal(`transaction`)}),B.object({action:B.literal(`topUp`),additionalDeposit:V(),channelId:U(),descriptor:B.optional(B.custom()),transaction:W(),type:B.literal(`transaction`)}),B.object({action:B.literal(`voucher`),channelId:U(),cumulativeAmount:V(),descriptor:B.optional(B.custom()),signature:W()}),B.object({action:B.literal(`close`),channelId:U(),closeSignature:W(),cumulativeAmount:V(),descriptor:B.optional(B.custom()),signature:W()})])},request:B.pipe(B.object({amount:V(),chainId:B.optional(B.number()),channelId:B.optional(U()),currency:B.string(),decimals:B.number(),escrowContract:B.optional(B.string()),feePayer:B.optional(B.pipe(B.union([B.boolean(),B.custom()]),B.transform(e=>typeof e==`object`||e))),feeToken:B.optional(H()),minVoucherDelta:B.optional(V()),operator:B.optional(H()),recipient:B.optional(B.string()),sessionProtocol:B.optional(B.enum([qe.v2,qe.v1])),sessionSnapshot:B.optional(B.custom()),suggestedDeposit:B.optional(V()),unitType:B.string()}).check(B.refine(({amount:e,decimals:t})=>d(e,t)>0n,`Session amount must be greater than 0`)),B.transform(({amount:e,chainId:t,channelId:n,decimals:r,escrowContract:i,feePayer:a,feeToken:o,minVoucherDelta:s,operator:c,sessionProtocol:l,sessionSnapshot:u,suggestedDeposit:f,...p})=>({...p,amount:d(e,r).toString(),...f?{suggestedDeposit:d(f,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:d(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&&{[Ke.sessionProtocol]:l},...u!==void 0&&{[Ke.sessionSnapshot]:u}}})))}}),Ba=jt({name:`tempo`,intent:`subscription`,schema:{credential:{payload:B.object({signature:W(),type:B.literal(`keyAuthorization`)})},request:B.pipe(B.object({amount:V(),accessKey:B.optional(ja),chainId:B.optional(B.number()),currency:Aa,decimals:B.number(),description:B.optional(B.string()),externalId:B.optional(B.string()),methodDetails:B.optional(Ma),periodCount:Fa,periodUnit:Pa,recipient:Aa,subscriptionExpires:Na}).check(Ia(`Subscription amount must be greater than 0`),B.refine(La,`Subscription period exceeds uint64`)),B.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:d(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}}),Va=B.object({account:B.optional(B.custom()),autoSwap:B.optional(B.custom()),mode:B.optional(B.enum(Ea))});function Ha(e={}){let{clientId:t}=e,n=Qi({chain:N,getClient:e.getClient,rpcUrl:Hn}),r=Ji({account:e.account});return Mt(Ra,{context:Va,async createCredential({challenge:i,context:a}){let o=i.request.methodDetails?.chainId;if(e.expectedChainId!==void 0&&o!==void 0&&o!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${o}.`);(o!==void 0||e.allowedChainIds?.length===0)&&ea(e.allowedChainIds,o);let s=o??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),c=await n({chainId:s});$i(c,s);let l=s??c.chain?.id;if(ea(e.allowedChainIds,l),l===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");let{request:u}=i,{amount:d,methodDetails:f}=u,m=f?.supportedModes??[`pull`,`push`],y=r(c,a),b=async t=>await e.resolveAccount?.({account:y,chainId:l,operation:t})??y;if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!u.recipient||!t.has(u.recipient.toLowerCase()))throw Error(`Unexpected primary recipient: ${u.recipient}`);let n=f?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}if(BigInt(d)===0n){let e=await b({kind:`signPaymentProof`});return Et({challenge:i,payload:{signature:await v(c,{account:e,...wa({account:e.address,chainId:l,challengeId:i.id,realm:i.realm})}),type:`proof`},source:Ta({address:e.address,chainId:l})})}let x=u.currency,S=va({chainId:l,currency:x}),C=ra({challengeId:i.id,clientId:t,serverId:i.realm}),w=ua({amount:d,methodDetails:{...f,memo:C},recipient:u.recipient}),T=w.map(e=>P.token.transfer.call(c,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:x})),E=ca(a?.autoSwap??e.autoSwap,oa),D=f?.machineTokenEnabled===!0?ya({chainId:l,currency:x,transfers:w}):void 0,O=y,k;if(D){let e=await(async()=>{try{return await b({calls:D.calls,kind:`executeCalls`})}catch{return}})();e&&(k=await ba(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 sa(c,{account:O.address,amountOut:BigInt(d),tokenOut:x,tokenIn:E.tokenIn,slippage:E.slippage}):void 0);let j=k?.calls??[...A??[],...T],M=ma(l),N=k||S?await ha({account:O.address,allowedTokens:M,candidateTokens:M,client:c,prioritizeCandidates:!0}):void 0,ee=(()=>{let t=a?.mode??e.mode;if(t){if(!m.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=O.type===`json-rpc`?`push`:`pull`;return m.includes(n)?n:m[0]})(),te=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!i.expires)return e;let t=Math.floor(new Date(i.expires).getTime()/1e3);return Math.min(e,t)})();if(ee===`push`){let{receipts:e}=O.type===`local`?{receipts:[await g(c,{account:O,calls:j,...N?{feeToken:N}:{},nonceKey:`expiring`,validBefore:te})]}:await h(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 Et({challenge:i,payload:{hash:t,type:`hash`},source:Ta({address:O.address,chainId:l})})}let ne=await p(c,{account:O,calls:j,...N?{feeToken:N}:{},nonceKey:`expiring`,validBefore:te});if(ne.gas=(ne.gas??0n)+5000n,f?.feePayer){let e=ne;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return Et({challenge:i,payload:{signature:await _(c,ne),type:`transaction`},source:Ta({address:O.address,chainId:l})})}})}const Ua=(1n<<96n)-1n;function Wa(e){return e>=0n&&e<=Ua}function Ga(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return Wa(t)?t:void 0}function Ka(e){return qa(e),e}function qa(e){if(!Wa(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const Ja=new Set([`open`,`topUp`,`voucher`,`close`]);function Ya(e){return typeof e==`object`&&!!e}function Xa(e){return typeof e==`string`&&Ja.has(e)}function Za(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!Xa(t.action))}function Qa(e,t=`No session credential context available.`){if(!Za(e))throw Error(t);return e}function $a(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function eo(e){return Ya(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function to(e){return Ya(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 no(e){let t=S.toString(e),n=JSON.parse(t);if(!to(n))throw Error(`Invalid session receipt.`);return n}function ro(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function io(e){let t=`message`,n=[];for(let r of e.split(`
|
|
3
3
|
`))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(`
|
|
4
|
-
`);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=jo(r);return Eo(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=jo(r);return Do(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function jo(e){try{return JSON.parse(e)}catch{return null}}function Mo(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function No(){return JSON.stringify({mpp:`payment-close-request`})}function Po(e){let t=Fo(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`&&Do(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`&&Eo(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&Do(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function Fo(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}const Io=`0x4d50500000000000000000000000000000000000`,Lo={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function Ro(e){let t=e.allowCustomEscrow??!1,n=e.fetch??globalThis.fetch,r=e.webSocket??globalThis.WebSocket,i=e.maxDeposit===void 0?null:f(e.maxDeposit,e.decimals??6),a=null,o=null,s=null,c=0n,l=0n,u=null,d=null,p=null,m=null,h=null,g=null,_=null,v=0n,y=0n,b=mo({account:e.account,allowCustomEscrow:t,voucherSigner:e.voucherSigner,getClient:e.client?()=>e.client:e.getClient,escrowContract:e.escrowContract,decimals:e.decimals,maxDeposit:e.maxDeposit,onChannelUpdate(e){e.channelId!==a?.channelId&&(c=0n,l=0n),a=e}}),x=_i({fetch:n,methods:[b],onChallenge:async(e,t)=>{o=e},orderChallenges:e.orderChallenges});function S(e){if(!e||e.channelId!==a?.channelId)return;C(e);let t=BigInt(e.acceptedCumulative),n=BigInt(e.spent);c=c>t?c:t,l=l>n?l:n}function C(e){if(!a||e.channelId!==a.channelId)return;let t=BigInt(e.acceptedCumulative),n=BigInt(e.spent);if(n>t)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(t>a.cumulativeAmount)throw Error(`receipt accepted cumulative exceeds local voucher state`);if(n>a.cumulativeAmount)throw Error(`receipt spent exceeds local voucher state`);j(t),j(n)}function w(e=()=>!0){if(_)throw Error(`receipt wait already in progress`);return new Promise((t,n)=>{_={predicate:e,resolve:t,reject:n}})}function T(){if(m)return Promise.resolve(m);if(h)throw Error(`close-ready wait already in progress`);return new Promise((e,t)=>{h={resolve:e,reject:t}})}function E(e){if(!_||!_.predicate(e))return;let t=_;_=null,t.resolve(e)}function D(e){if(m=e,!h)return;let t=h;h=null,t.resolve(e)}function O(e){if(!_)return;let t=_;_=null,t.reject(e)}function k(e){if(!h)return;let t=h;h=null,t.reject(e)}function A(e,t){if(m&&m.challengeId===e.id&&m.channelId===t)return m.spent;let n=a?.channelId===t?a.cumulativeAmount:0n;if(y>0n){let e=v*y,t=l>e?l:e;return(t>n?n:t).toString()}return(l>c?l:c).toString()}function j(e){if(i!==null&&!(e<=i))throw Error(`requested voucher amount ${e} exceeds local maxDeposit ${i}`)}function M(e){let t=e.headers.get(B.paymentReceipt),n=t?Oo(t):null;return S(n),Object.assign(e,{receipt:n,challenge:o,channelId:a?.channelId??null,cumulative:a?.cumulativeAmount??0n})}async function N(e,t){return s=e,M(await x(e,t))}function P(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)},s=(e,a)=>{if(e===`close`){if(n)return;n=!0,i=Lo.CLOSED,r=null}if(e===`open`&&(i=Lo.OPEN),e===`message`&&r){r.push(a);return}let o=`on${e}`,s=c[o];typeof s==`function`&&s(a);let l=t.get(e);if(l)for(let e of Array.from(l))typeof e.value==`function`?e.value(a):e.value.handleEvent(a),e.once&&l.delete(e)},c={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,_onmessage:null,get onmessage(){return c._onmessage},set onmessage(e){if(c._onmessage=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:c}}return{get channelId(){return a?.channelId},get cumulative(){return a?.cumulativeAmount??0n},get opened(){return a?.opened??!1},async open(e){if(a?.opened)return;if(!o)throw Error(`No challenge available. Make a request first to receive a 402 challenge, or pass a challenge via .fetch()/.sse().`);let t=e?.deposit,r=await b.createCredential({challenge:o,context:{...t!==void 0&&{depositRaw:t.toString()}}});if(!s)throw Error(`No URL available — call fetch() or sse() before open().`);let i=await n(s,{method:`POST`,headers:{[B.authorization]:r}});if(!i.ok){let e=await i.text().catch(()=>``),t=i.headers.get(B.wwwAuthenticate)??``;throw Error(`Open request failed with status ${i.status}${e?`: ${e}`:``}${t?` [${B.wwwAuthenticate}: ${t}]`:``}`)}},fetch:N,async sse(e,t){let{onReceipt:r,signal:i,...s}=t??{},c=await N(e,{...s,headers:{...Q(s.headers),Accept:`text/event-stream`},...i?{signal:i}:{}}),l=o;if(!c.body)throw Error(`Response has no body.`);let u=c.body.getReader(),d=new TextDecoder;async function*f(){let t=``;try{for(;!i?.aborted;){let{done:i,value:o}=await u.read();if(i)break;t+=d.decode(o,{stream:!0});let s=t.split(`
|
|
5
|
-
|
|
6
|
-
`);t=s.pop();for(let t of s){if(!t.trim())continue;let i=Ao(t);if(i)switch(i.type){case`message`:yield i.data;break;case`payment-need-voucher`:{if(!a||!l)break;let t=BigInt(i.data.requiredCumulative);j(t),a.cumulativeAmount=a.cumulativeAmount>t?a.cumulativeAmount:t;let r=await b.createCredential({challenge:l,context:{action:`voucher`,channelId:a.channelId,cumulativeAmountRaw:a.cumulativeAmount.toString()}}),o=await n(e,{method:`POST`,headers:{Accept:`text/event-stream`,[B.authorization]:r}});if(!o.ok)throw Error(`Voucher POST failed with status ${o.status}`);break}case`payment-receipt`:S(i.data),r?.(i.data)}}}}finally{u.releaseLock()}}return f()},async ws(t,i){if(!r)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let{onReceipt:c,protocols:l,signal:f}=i??{},h=new URL(t.toString()),_=new URL(h.toString());_.protocol===`ws:`&&(_.protocol=`http:`),_.protocol===`wss:`&&(_.protocol=`https:`),s=_.toString();let x=await n(_,f?{signal:f}:void 0);if(x.status!==402)throw Error(`Expected a 402 payment challenge from ${_}, received ${x.status} instead.`);let C=(await zo(Dr(pt(x),[b],wr([b]).entries),i?.orderChallenges??e.orderChallenges))[0]?.challenge;if(!C)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.`);o=C;let T=await b.createCredential({challenge:C,context:{}});m=null,u=C,v=0n,y=BigInt(C.request.amount);let A=St(T);d=A.payload.channelId;let M=new r(h,l);p=M;let N=P(M),F=e=>{O(Error(e)),k(Error(e)),(M.readyState===Lo.CONNECTING||M.readyState===Lo.OPEN)&&M.close(3008,e)},ee=e=>e.challengeId===C.id&&e.channelId===d,I=new Promise((e,t)=>{let n=()=>{M.removeEventListener(`error`,r),N.emit(`open`,{type:`open`}),e()},r=()=>{M.removeEventListener(`open`,n),t(Error(`WebSocket connection to ${h} failed to open.`))};M.addEventListener(`open`,n,{once:!0}),M.addEventListener(`error`,r,{once:!0})});return M.addEventListener(`close`,e=>{p===M&&(p=null),u===C&&(u=null),d===A.payload.channelId&&(d=null),g=null,O(Error(`WebSocket closed before the payment flow completed.`)),k(Error(`WebSocket closed before the payment flow completed.`)),N.emit(`close`,{code:e.code??1e3,reason:e.reason??``,type:`close`,wasClean:!0})}),M.addEventListener(`error`,()=>{N.emit(`error`,{type:`error`})}),M.addEventListener(`message`,async e=>{let t=typeof e.data==`string`?e.data:void 0;if(!t)return;let n=Po(t);if(!n){N.emit(`message`,{data:t,type:`message`});return}switch(n.mpp){case`authorization`:break;case`message`:v+=1n,N.emit(`message`,{data:n.data,type:`message`});break;case`payment-close-ready`:if(!ee(n.data)){F(`received mismatched payment-close-ready frame`);break}if(BigInt(n.data.spent)>(a?.cumulativeAmount??0n)){F(`received payment-close-ready beyond local voucher state`);break}S(n.data),c?.(n.data),D(n.data),N.emit(`close`,{code:1e3,reason:`stream complete`,type:`close`});break;case`payment-error`:O(Error(n.message)),k(Error(n.message));break;case`payment-need-voucher`:{if(n.data.channelId!==d){F(`received mismatched payment-need-voucher frame`);break}let e=BigInt(n.data.requiredCumulative);try{j(e)}catch(e){F(e instanceof Error?e.message:`requested voucher amount exceeds local maxDeposit`);break}let t=(a?.cumulativeAmount??0n)>e?a?.cumulativeAmount??0n:e;a?.channelId===d&&(a.cumulativeAmount=t);let r=await b.createCredential({challenge:C,context:{action:`voucher`,channelId:d,cumulativeAmountRaw:t.toString()}});M.send(Mo(r));break}case`payment-receipt`:if(!ee(n.data)){F(`received mismatched payment-receipt frame`);break}if(g!==null&&n.data.txHash&&(n.data.acceptedCumulative!==g||n.data.spent!==g)){F(`received mismatched payment-close receipt frame`);break}S(n.data),c?.(n.data),E(n.data)}}),f&&f.addEventListener(`abort`,()=>{O(Error(`WebSocket payment flow aborted.`)),k(Error(`WebSocket payment flow aborted.`)),M.close()},{once:!0}),await I,M.send(Mo(T)),await w(),N.socket},async close(){let e=u??o,t=d??a?.channelId;if(!a?.opened)return;if(!e)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(!t)throw Error(`Cannot close session: no channel ID available. The session may not have been fully opened.`);if(p?.readyState===Lo.OPEN){let n=m??await(async()=>(p.send(No()),T()))(),r=BigInt(n.spent);if(r>(a.cumulativeAmount>l?a.cumulativeAmount:l))throw Error(`close-ready spent exceeds local voucher state`);let i=await b.createCredential({challenge:e,context:{action:`close`,channelId:t,cumulativeAmountRaw:r.toString()}}),o=r.toString();g=o;try{let n=w(n=>!!n.txHash&&n.challengeId===e.id&&n.channelId===t&&n.acceptedCumulative===o&&n.spent===o);p.send(Mo(i));let r=await n;return p.close(),m=null,r}finally{g=null}}let r=await b.createCredential({challenge:e,context:{action:`close`,channelId:t,cumulativeAmountRaw:(()=>{let n=BigInt(A(e,t));if(n>a.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return j(n),n.toString()})()}});if(!s)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 i=await n(s,{method:`POST`,headers:{[B.authorization]:r}});if(!i.ok){let e=await i.text().catch(()=>``),t=(()=>{if(!e)return``;if(!i.headers.get(`Content-Type`)?.includes(`application/problem+json`))return e;try{return JSON.parse(e).detail??e}catch{return e}})(),n=i.headers.get(B.wwwAuthenticate)??``;throw Error(`Close request failed with status ${i.status}${t?`: ${t}`:``}${n?` [${B.wwwAuthenticate}: ${n}]`:``}`)}let c=i.headers.get(B.paymentReceipt);return c?Oo(c):void 0}}}async function zo(e,t){let n=t;return n?n(e):e}function Bo(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function Vo(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 Ho(e){return me.encodeForSigning(e)}function Uo(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function Wo(e,t){return T.keccak256(E.concat(Ho(e),t.sender))}const Go=[{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`}],Ko=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],qo={name:`descriptor`,type:`tuple`,components:Go},Jo=[{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:[qo,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[qo,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[qo,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[qo],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[qo],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[qo],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:Go},{name:`state`,type:`tuple`,components:Ko}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:Ko}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:Ko}]},{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 Yo(e,t){return{name:`TIP20 Channel Reserve`,version:`1`,chainId:t,verifyingContract:e}}const Xo={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]};function Zo(e,t){return fe.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function Qo(e,t,n){return e.toLowerCase()===fe.address.toLowerCase()?Zo(t,n):s({domain:Yo(e,t),types:Xo,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function $o(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function es(e,t){return ie.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function ts(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===fe.address.toLowerCase())try{return await es(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return y(e,{account:t,domain:Yo(r,i),types:Xo,primaryType:`Voucher`,message:n})})(),o=z.from(a);if(!$o(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return z.serialize(o)}function ns(e,t,n,r){try{let i=z.from(n.signature);if(!$o(i.type)||z.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=Qo(e,t,n),o=z.extractAddress({payload:a,signature:i});return z.verify(i,{address:o,payload:a})&&ca(o,r)}catch{return!1}}function rs(e){return typeof e==`object`&&!!e}function is(e){return typeof e==`string`&&l(e,{strict:!1})?e:void 0}function as(e){return is(e.accessKeyAddress)}function os(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(E.random(8))%e)}function ss(e){return as(e)??e.address}async function cs(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 ls(e,t){return await v(e,t)}function us(e,t,n=!1){let r=e.request.methodDetails,i=rs(r)?is(r.escrowContract)??is(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!fs(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!fs(i,a)?i:a}function ds(e,t,n,r){return Et({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function fs(e,t){return e.toLowerCase()===t.toLowerCase()}async function ps(e,t,n,r,i,a=Io){let o=Vo({...n,chainId:i,escrow:a}),s=vo(r),c=await ts(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function ms(e,t,n,r,i,a=Io){let o=await ps(e,t,n,r,i,a);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature}}async function hs(e,t,n){let i=ss(t),a=n.escrow??`0x4d50500000000000000000000000000000000000`,o=n.operator??`0x0000000000000000000000000000000000000000`,s=E.random(32),c=vo(n.deposit),l=vo(n.initialAmount),u=r({abi:Jo,functionName:`open`,args:[n.payee,o,n.token,c,s,i]}),d=await ls(e,await cs(e,{account:t,calls:[...n.prefixCalls??[],{to:a,data:u}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),f=se.deserialize(d),p={authorizedSigner:i,expiringNonceHash:Wo(Uo({...n.feePayer?{feePayer:!0}:{},transaction:f}),{sender:t.address}),operator:o,payee:n.payee,payer:t.address,salt:s,token:n.token},m=Vo({...p,chainId:n.chainId,escrow:a});return{action:`open`,type:`transaction`,channelId:m,transaction:d,signature:await ts(e,t,{channelId:m,cumulativeAmount:l},a,n.chainId),descriptor:p,cumulativeAmount:l.toString(),authorizedSigner:p.authorizedSigner}}async function gs(e,t,n,i,a,o,s=Io,c=[],l=n.token){let u=Vo({...n,chainId:a,escrow:s}),d=vo(i);return{action:`topUp`,type:`transaction`,channelId:u,transaction:await ls(e,await cs(e,{account:t,calls:[...c,{to:s,data:r({abi:Jo,functionName:`topUp`,args:[n,d]})}],feePayer:o,feeToken:l,validAfter:os()})),descriptor:n,additionalDeposit:d.toString()}}function _s(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function vs(e){return _s({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function ys(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(vs(t),t)},delete(t){e.delete(t)}}}const bs=2n**96n-1n;function xs(e){if(e<0n||e>bs)throw new J({reason:`amount exceeds uint96 range`})}async function Ss(e,t,n=Io,r){return Cs(await h(e,{address:n,abi:Jo,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function Cs(e){return xs(e.settled),xs(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}const ws=H.custom(e=>typeof e==`string`&&l(e,{strict:!1})),Ts=H.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),Es=H.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),Ds=H.object({authorizedSigner:ws,expiringNonceHash:Ts,operator:ws,payee:ws,payer:ws,salt:Ts,token:ws}),Os=Nt(H.object({acceptedCumulative:H.string(),chainId:H.number(),channelId:Ts,closeRequestedAt:H.optional(H.string()),deposit:H.string(),descriptor:Ds,escrow:ws,highestVoucher:H.optional(H.object({channelId:Ts,cumulativeAmount:H.string(),signature:Es})),requiredCumulative:H.string(),settled:H.string(),spent:H.string(),units:H.optional(H.number())}));function ks(e){return Os.encode(e)}function As(e){return Os.decode(e)}const js={status:`idle`};function Ms(e){return{status:`active`,...e}}function Ns(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:Is(e.challengeId,t.snapshot),effects:[]}:$(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Ys({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:Ls(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:$(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Qs(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?Fs({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:Ls(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:Ls(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 Ps(e,t){let n=Ns(e.state,t);return e.state=n.state,n}function Fs(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 Is(e,t){return Ms({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function Ls(e,t,n,r){return Ms({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 Rs(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function zs(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`);Rs({cumulativeAmount:i,maxVoucherCumulative:n}),Rs({cumulativeAmount:a,maxVoucherCumulative:n})}function Bs(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;zs({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function Vs(e,t){return typeof e==`bigint`?e:f(e,t)}function Hs(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(Ws(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 Us(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;Rs({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 Ws(e,t){Rs({cumulativeAmount:e,maxVoucherCumulative:t??null})}function Gs(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 Ks(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function qs(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!go(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>Ks({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function Js(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=_o(r),s=_o(a.spent);return o===void 0||s===void 0||!go(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function Ys(e){return Ms({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 Xs(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:js}}function Zs(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=Bs({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&Ps(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function Qs(e,t){return Ms({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function $s(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=_o(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 ec(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 Ns(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function tc(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 nc(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 rc(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(No()),e.waitForCloseReady()))(),a=BigInt(i.spent);qs({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=>Js({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(Mo(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}function ic(e){return`cumulativeAmount`in e}function ac(e){if(ic(e))return BigInt(e.cumulativeAmount)}async function oc(e,t){t.opened?await e.store.set(t):await e.store.delete(vs(t)),e.notifyUpdate(t)}async function sc(e,t,n){let r=ac(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 oc(e,i))}const cc=H.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),lc=H.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),uc=H.object({account:H.optional(H.custom()),autoSwap:H.optional(H.custom()),action:H.optional(H.enum([`open`,`topUp`,`voucher`,`close`])),channelId:H.optional(lc),cumulativeAmount:H.optional(U()),cumulativeAmountRaw:H.optional(H.string()),transaction:H.optional(cc),descriptor:H.optional(H.custom()),additionalDeposit:H.optional(U()),additionalDepositRaw:H.optional(H.string()),depositRaw:H.optional(H.string())});function dc(e){return e?.action!==void 0}function fc(e){return dc(e)&&e.descriptor!==void 0}function pc(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 mc(e,t,n,r){let i=pc(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function hc(e){return typeof e==`object`&&!!e}function gc(e){return typeof e==`string`&&l(e,{strict:!1})?e:void 0}function _c(e){let t=e.request.methodDetails;return hc(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:gc(t.escrowContract),escrow:gc(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:gc(t.feeToken),operator:gc(t.operator),sessionSnapshot:Je(t,Ke.sessionSnapshot)}:{}}function vc(e,t){if(typeof e==`string`&&l(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function yc(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function bc(e){return typeof e==`string`?e:void 0}async function xc(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=_c(n);(o.chainId!==void 0||i?.length===0)&&ra(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});na(c,s);let l=s??c.chain?.id;if(ra(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=us(n,r,t),d=vc(n.request.recipient,`recipient`),f=vc(n.request.currency,`currency`);return{amount:yc(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:_s({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:bc(n.request.suggestedDeposit),token:f}}async function Sc(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=Ss}=e,o=Vo({...r,chainId:i.chainId,escrow:i.escrow});Cc({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 Cc(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(!fs(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!fs(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!fs(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!fs(Bo(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function wc(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function Tc(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=pc(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function Ec(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(!ns(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},Bo(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await Sc({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:ss(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 Dc(e,t){return fs(e.address,t.payer)?fs(ss(e),Bo(t)):!1}function Oc(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(dc(r)){if(!fc(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=wc({context:r,snapshot:o.snapshot});return!n&&s&&Dc(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&Dc(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 kc(e,t,n=!1){switch(e.type){case`open`:return jc(e,t,n);case`recover`:return Mc(e,t);case`voucher`:return Nc(e,t);case`manual`:return Pc(e,t,n)}}async function Ac(e,t){if(e)return await ua(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage})}async function jc(e,t,n){let{account:r,resolved:i}=e,a=Hs({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw}),o=await hs(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 Ac(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await oc(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function Mc(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await Sc({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:ss(n),token:o.token}}),l=Tc({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`);Ws(l,a);let u=await ps(o.client,n,s,l,o.chainId,o.escrow);return await oc(t,{channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function Nc(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;Ws(a,e.maxDeposit);let o=await ps(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await oc(t,r),o}async function Pc(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=Vo({...s,chainId:o.chainId,escrow:o.escrow});Cc({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:ss(r),token:o.token});let l=await Fc({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await sc(t,o.key,l),l}async function Fc(e,t){switch(e.context.action){case`open`:return Ic(e);case`topUp`:return Lc(e,t);case`voucher`:return Rc(e);case`close`:return zc(e)}}async function Ic(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=mc(r,i,`cumulativeAmount`,`open`),c=await ps(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 Lc(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=mc(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:gs(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await Ac(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken)}function Rc(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return ps(a.client,t,i,mc(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function zc(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return ms(a.client,t,i,mc(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}const Bc={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function Vc(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=Bc.CLOSED,r=null}if(a.type===`open`&&(i=Bc.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 Hc(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function Uc(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=Vs(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 Wc(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:Qs(s,u)}:i?{channel:u,state:Ys({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function Gc(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=Hc(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,channelId:e.expectedChannelId,deposit:t.deposit,requiredCumulative:t.requiredCumulative});let n=e.getChannel();if(!n||n.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`missing-channel`};let r=n.cumulativeAmount>t.requiredCumulative?n.cumulativeAmount:vo(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function Kc(e){return e.method===We.tempo&&e.intent===Ge.session}function qc(e){return Kc(e)&&Je(e.request.methodDetails,Ke.sessionProtocol)===qe.v2}function Jc(e){return Je(e.request.methodDetails,Ke.sessionSnapshot)}function Yc(e,t,n){let r=e instanceof Request?e.headers:void 0;return{...t,headers:{...Q(r),...Q(t?.headers),[B.authorization]:n}}}function Xc(e){try{let t=typeof location>`u`?void 0:location.href,n=e instanceof Request?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function Zc(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function Qc(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}}async function $c(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);let r=await el({challenge:e.challenge,context:{action:`topUp`,channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,input:e.input});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(B.paymentReceipt);return i?Oo(i):void 0}async function el(e){let t=async t=>e.fetch(Xc(e.input),{method:`POST`,headers:{[B.authorization]:await e.createSessionCredential(t,e.context)}}),n=await t(e.challenge);if(n.status!==402)return n;let r=pt(n).find(qc);return r?t(r):n}async function tl(e){let t=nl({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,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a});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,Yc(e.input,e.init,t))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(B.paymentReceipt)&&await l(),u}function nl(e){let t=pt(e.response).find(qc);if(!t)return;let n=Jc(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function rl(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=async(r,i=!1)=>{t=r,n=(i?e.resolveSignedCloseAmount?.(r):void 0)??e.signedCloseAmount;let a=await e.createSessionCredential(r,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(e.lastUrl,{method:`POST`,headers:{[B.authorization]:a}})},i=await r(e.target.challenge);if(i.status===402){let t=pt(i).find(qc);t&&(e.setChallenge?.(t),i=await r(t,!0))}if(!i.ok){let e=await Qc(i),t=i.headers.get(B.wwwAuthenticate)??``;throw Error(`Close request failed with status ${i.status}${e?`: ${e}`:``}${t?` [${B.wwwAuthenticate}: ${t}]`:``}`)}let a=i.headers.get(B.paymentReceipt);if(!a)return;let o=Oo(a);if(!o.txHash||!E.validate(o.txHash,{strict:!0})||E.size(o.txHash)!==32||!Js({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:e.getMinimumSpent?.()??0n,receipt:o}))throw Error(`Session close response included a mismatched payment receipt.`);return o}async function il(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o={...a,headers:{...Q(a.headers),Accept:`text/event-stream`},...i?{signal:i}:{}},s=await n.doFetch(e,o);return!ko(s)&&n.getChannel()?.opened&&(s=await n.doFetch(e,o)),al(e,s,{onReceipt:r,signal:i},n)}function al(e,t,n,r){if(!ko(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let i=r.getChallenge();return ol({onNeedVoucher:t=>dl({challenge:i,driver:r,input:e},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*ol(e){for await(let t of sl(e))t.data!==void 0&&(yield t.data)}async function*sl(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=cl(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=Ao(i.replace(/\r\n|\r/g,`
|
|
7
|
-
`));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);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 cl(e,t){for(let n=0;n<e.length;n++){let r=ll(e,n,t);if(!r)continue;let i=ll(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function ll(e,t,n){return e[t]===`
|
|
4
|
+
`);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=ao(r);return eo(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=ao(r);return to(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function ao(e){try{return JSON.parse(e)}catch{return null}}function oo(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function so(){return JSON.stringify({mpp:`payment-close-request`})}function co(e){let t=lo(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`&&to(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`&&eo(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&to(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function lo(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}const uo=`0x4d50500000000000000000000000000000000000`;function fo(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function po(e){let t=x.encode(x.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 w.keccak256(t)}function mo(e){return he.encodeForSigning(e)}function ho(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function go(e,t){return w.keccak256(T.concat(mo(e),t.sender))}const _o=[{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`}],vo=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],yo={name:`descriptor`,type:`tuple`,components:_o},bo=[{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:[yo,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[yo,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[yo,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[yo],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[yo],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[yo],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:_o},{name:`state`,type:`tuple`,components:vo}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:vo}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:vo}]},{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 xo(e,t){return{name:`TIP20 Channel Reserve`,version:`1`,chainId:t,verifyingContract:e}}const So={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},Co={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]};function wo(e,t){return pe.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function To(e,t,n){return e.toLowerCase()===pe.address.toLowerCase()?wo(t,n):o({domain:xo(e,t),types:So,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function Eo(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function Do(e,t){return ae.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function Oo(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===pe.address.toLowerCase())try{return await Do(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return v(e,{account:t,domain:xo(r,i),types:So,primaryType:`Voucher`,message:n})})(),o=I.from(a);if(!Eo(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return I.serialize(o)}async function ko(e,t,n,r,i){let a=await v(e,{account:t,domain:xo(r,i),types:Co,primaryType:`CloseAuthorization`,message:n}),o=I.from(a);if(!Eo(o.type))throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive signature; received "${o.type}".`);return I.serialize(o)}function Ao(e,t,n,r){try{let i=I.from(n.signature);if(!Eo(i.type)||I.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=To(e,t,n),o=I.extractAddress({payload:a,signature:i});return I.verify(i,{address:o,payload:a})&&aa(o,r)}catch{return!1}}function jo(e){return typeof e==`object`&&!!e}function Mo(e){return typeof e==`string`&&c(e,{strict:!1})?e:void 0}function No(e){return Mo(e.accessKeyAddress)}function Po(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(T.random(8))%e)}function Fo(e){return No(e)??e.address}async function Io(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return p(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}})}async function Lo(e,t){return await _(e,t)}function Ro(e,t,n=!1){let r=e.request.methodDetails,i=jo(r)?Mo(r.escrowContract)??Mo(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!Bo(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!Bo(i,a)?i:a}function zo(e,t,n,r){return Et({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function Bo(e,t){return e.toLowerCase()===t.toLowerCase()}async function Vo(e,t,n,r,i,a=uo){let o=po({...n,chainId:i,escrow:a}),s=Ka(r),c=await Oo(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function Ho(e,t,n,r,i,a=uo){let o=await Vo(e,t,n,r,i,a),s=await ko(e,t,{channelId:o.channelId,cumulativeAmount:Ka(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function Uo(e,t,n){let i=Fo(t),a=n.escrow??`0x4d50500000000000000000000000000000000000`,o=n.operator??`0x0000000000000000000000000000000000000000`,s=T.random(32),c=Ka(n.deposit),l=Ka(n.initialAmount),u=r({abi:bo,functionName:`open`,args:[n.payee,o,n.token,c,s,i]}),d=await Lo(e,await Io(e,{account:t,calls:[...n.prefixCalls??[],{to:a,data:u}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),f=ce.deserialize(d),p={authorizedSigner:i,expiringNonceHash:go(ho({...n.feePayer?{feePayer:!0}:{},transaction:f}),{sender:t.address}),operator:o,payee:n.payee,payer:t.address,salt:s,token:n.token},m=po({...p,chainId:n.chainId,escrow:a});return{action:`open`,type:`transaction`,channelId:m,transaction:d,signature:await Oo(e,t,{channelId:m,cumulativeAmount:l},a,n.chainId),descriptor:p,cumulativeAmount:l.toString(),authorizedSigner:p.authorizedSigner}}async function Wo(e,t,n,i,a,o,s=uo,c=[],l=n.token){let u=po({...n,chainId:a,escrow:s}),d=Ka(i);return{action:`topUp`,type:`transaction`,channelId:u,transaction:await Lo(e,await Io(e,{account:t,calls:[...c,{to:s,data:r({abi:bo,functionName:`topUp`,args:[n,d]})}],feePayer:o,feeToken:l,validAfter:Po()})),descriptor:n,additionalDeposit:d.toString()}}function Go(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Ko(e){return Go({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function qo(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Ko(t),t)},delete(t){e.delete(t)}}}const Jo=2n**96n-1n;function Yo(e){if(e<0n||e>Jo)throw new K({reason:`amount exceeds uint96 range`})}async function Xo(e,t,n=uo,r){return Zo(await m(e,{address:n,abi:bo,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function Zo(e){return Yo(e.settled),Yo(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}const Qo=B.custom(e=>typeof e==`string`&&c(e,{strict:!1})),$o=B.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),es=B.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),ts=B.object({authorizedSigner:Qo,expiringNonceHash:$o,operator:Qo,payee:Qo,payer:Qo,salt:$o,token:Qo}),ns=Nt(B.object({acceptedCumulative:B.string(),chainId:B.number(),channelId:$o,closeRequestedAt:B.optional(B.string()),deposit:B.string(),descriptor:ts,escrow:Qo,highestVoucher:B.optional(B.object({channelId:$o,cumulativeAmount:B.string(),signature:es})),requiredCumulative:B.string(),settled:B.string(),spent:B.string(),units:B.optional(B.number())}));function rs(e){return ns.encode(e)}function is(e){return ns.decode(e)}const as={status:`idle`};function os(e){return{status:`active`,...e}}function ss(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:us(e.challengeId,t.snapshot),effects:[]}:$(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Cs({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:ds(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:$(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Es(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?ls({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:ds(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:ds(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 cs(e,t){let n=ss(e.state,t);return e.state=n.state,n}function ls(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 us(e,t){return os({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function ds(e,t,n,r){return os({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 fs(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function ps(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`);fs({cumulativeAmount:i,maxVoucherCumulative:n}),fs({cumulativeAmount:a,maxVoucherCumulative:n})}function ms(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;ps({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function hs(e,t){return typeof e==`bigint`?e:d(e,t)}function gs(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(vs(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 _s(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;fs({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 vs(e,t){fs({cumulativeAmount:e,maxVoucherCumulative:t??null})}function ys(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 bs(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function xs(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!Wa(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>bs({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function Ss(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=Ga(r),s=Ga(a.spent);return o===void 0||s===void 0||!Wa(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function Cs(e){return os({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 ws(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:as}}function Ts(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=ms({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&cs(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function Es(e,t){return os({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function Ds(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=Ga(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 Os(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 ss(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function ks(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 As(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 js(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(so()),e.waitForCloseReady()))(),a=BigInt(i.spent);xs({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=>Ss({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(oo(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}function Ms(e){return`cumulativeAmount`in e}function Ns(e){if(Ms(e))return BigInt(e.cumulativeAmount)}async function Ps(e,t){t.opened?await e.store.set(t):await e.store.delete(Ko(t)),e.notifyUpdate(t)}async function Fs(e,t,n){let r=Ns(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 Ps(e,i))}const Is=B.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),Ls=B.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),Rs=B.object({account:B.optional(B.custom()),autoSwap:B.optional(B.custom()),action:B.optional(B.enum([`open`,`topUp`,`voucher`,`close`])),channelId:B.optional(Ls),cumulativeAmount:B.optional(V()),cumulativeAmountRaw:B.optional(B.string()),transaction:B.optional(Is),descriptor:B.optional(B.custom()),additionalDeposit:B.optional(V()),additionalDepositRaw:B.optional(B.string()),depositRaw:B.optional(B.string())});function zs(e){return e?.action!==void 0}function Bs(e){return zs(e)&&e.descriptor!==void 0}function Vs(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 d(i,t)}function Hs(e,t,n,r){let i=Vs(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function Us(e){return typeof e==`object`&&!!e}function Ws(e){return typeof e==`string`&&c(e,{strict:!1})?e:void 0}function Gs(e){let t=e.request.methodDetails;return Us(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:Ws(t.escrowContract),escrow:Ws(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:Ws(t.feeToken),operator:Ws(t.operator),sessionSnapshot:Je(t,Ke.sessionSnapshot)}:{}}function Ks(e,t){if(typeof e==`string`&&c(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function qs(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function Js(e){return typeof e==`string`?e:void 0}async function Ys(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=Gs(n);(o.chainId!==void 0||i?.length===0)&&ea(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});$i(c,s);let l=s??c.chain?.id;if(ea(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=Ro(n,r,t),d=Ks(n.request.recipient,`recipient`),f=Ks(n.request.currency,`currency`);return{amount:qs(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:Go({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:Js(n.request.suggestedDeposit),token:f}}async function Xs(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=Xo}=e,o=po({...r,chainId:i.chainId,escrow:i.escrow});Zs({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 Zs(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(!Bo(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!Bo(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!Bo(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!Bo(fo(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function Qs(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function $s(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=Vs(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function ec(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(!Ao(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},fo(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await Xs({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:Fo(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 tc(e,t){return Bo(e.address,t.payer)?Bo(Fo(e),fo(t)):!1}function nc(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(zs(r)){if(!Bs(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=Qs({context:r,snapshot:o.snapshot});return!n&&s&&tc(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&tc(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 rc(e,t,n=!1){switch(e.type){case`open`:return ac(e,t,n);case`recover`:return oc(e,t);case`voucher`:return sc(e,t);case`manual`:return cc(e,t,n)}}async function ic(e,t){if(e)return await sa(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage})}async function ac(e,t,n){let{account:r,resolved:i}=e,a=gs({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw}),o=await Uo(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 ic(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await Ps(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function oc(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await Xs({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:Fo(n),token:o.token}}),l=$s({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`);vs(l,a);let u=await Vo(o.client,n,s,l,o.chainId,o.escrow);return await Ps(t,{channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function sc(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;vs(a,e.maxDeposit);let o=await Vo(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await Ps(t,r),o}async function cc(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=po({...s,chainId:o.chainId,escrow:o.escrow});Zs({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:Fo(r),token:o.token});let l=await lc({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await Fs(t,o.key,l),l}async function lc(e,t){switch(e.context.action){case`open`:return uc(e);case`topUp`:return dc(e,t);case`voucher`:return fc(e);case`close`:return pc(e)}}async function uc(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=Hs(r,i,`cumulativeAmount`,`open`),c=await Vo(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 dc(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=Hs(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:Wo(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await ic(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken)}function fc(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Vo(a.client,t,i,Hs(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function pc(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Ho(a.client,t,i,Hs(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}const mc={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function hc(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=mc.CLOSED,r=null}if(a.type===`open`&&(i=mc.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 gc(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function _c(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=hs(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 vc(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:Es(s,u)}:i?{channel:u,state:Cs({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function yc(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=gc(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,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:Ka(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function bc(e){return e.method===We.tempo&&e.intent===Ge.session}function xc(e){return bc(e)&&Je(e.request.methodDetails,Ke.sessionProtocol)===qe.v2}function Sc(e){return Je(e.request.methodDetails,Ke.sessionSnapshot)}function Cc(e,t,n){let r=e instanceof Request?e.headers:void 0;return{...t,headers:{...Q(r),...Q(t?.headers),[R.authorization]:n}}}function wc(e){try{let t=typeof location>`u`?void 0:location.href,n=e instanceof Request?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function Tc(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function Ec(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}}async function Dc(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);let r=await Oc({challenge:e.challenge,context:{action:`topUp`,channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,input:e.input,signal:e.signal});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(R.paymentReceipt);return i?no(i):void 0}async function Oc(e){let t=async t=>e.fetch(wc(e.input),{method:`POST`,...e.signal?{signal:e.signal}:{},headers:{[R.authorization]:await e.createSessionCredential(t,e.context)}}),n=await t(e.challenge);if(n.status!==402)return n;let r=pt(n).find(xc);return r?t(r):n}async function kc(e){let t=Ac({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,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,Cc(e.input,e.init,t))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(R.paymentReceipt)&&await l(),u}function Ac(e){let t=pt(e.response).find(xc);if(!t)return;let n=Sc(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function jc(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=async(r,i=!1)=>{t=r,n=(i?e.resolveSignedCloseAmount?.(r):void 0)??e.signedCloseAmount;let a=await e.createSessionCredential(r,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(e.lastUrl,{method:`POST`,headers:{[R.authorization]:a}})},i=await r(e.target.challenge);if(i.status===402){let t=pt(i).find(xc);t&&(e.setChallenge?.(t),i=await r(t,!0))}if(!i.ok){let e=await Ec(i),t=i.headers.get(R.wwwAuthenticate)??``;throw Error(`Close request failed with status ${i.status}${e?`: ${e}`:``}${t?` [${R.wwwAuthenticate}: ${t}]`:``}`)}let a=i.headers.get(R.paymentReceipt);if(!a)return;let o=no(a);if(!o.txHash||!T.validate(o.txHash,{strict:!0})||T.size(o.txHash)!==32||!Ss({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:e.getMinimumSpent?.()??0n,receipt:o}))throw Error(`Session close response included a mismatched payment receipt.`);return o}async function Mc(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...Q(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)),Nc(e,c,{onReceipt:r,signal:o},n)}function Nc(e,t,n,r){if(!ro(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let i=r.getChallenge();return Pc({onNeedVoucher:t=>zc({challenge:i,driver:r,input:e,signal:n?.signal},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*Pc(e){for await(let t of Fc(e))t.data!==void 0&&(yield t.data)}async function*Fc(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=Ic(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=io(i.replace(/\r\n|\r/g,`
|
|
5
|
+
`));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 Ic(e,t){for(let n=0;n<e.length;n++){let r=Lc(e,n,t);if(!r)continue;let i=Lc(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function Lc(e,t,n){return e[t]===`
|
|
8
6
|
`?1:e[t]===`\r`?e[t+1]===`
|
|
9
|
-
`?2:t+1===e.length&&!n?0:1:0}function ul(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=sl({...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 dl(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await Gc({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,input:e.input,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await el({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,input:e.input});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function fl(e){let t=new URL(e.input.toString()),n=Zc(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=pt(r).find(qc);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 pl(e){let t=await fl(e);return{...t,credential:await e.createSessionCredential(t.challenge,{})}}function ml(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:St(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:To(t)}}function hl(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function gl(e){if(!hl(e))return`received mismatched payment-close-ready frame`;let t=_o(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 _l(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!hl(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!Js({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function vl(e){let{challenge:t,credential:n,options:r,WebSocket:i,wsUrl:a}=e,o=new i(a,r?.protocols),s=ml({challenge:t,credential:n,socket:o});e.setSocketSession(s);let c=Vc(o),l=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(o.readyState===Bc.CONNECTING||o.readyState===Bc.OPEN)&&o.close(3008,t)};return o.addEventListener(`close`,t=>{s.socket=null,s.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),c.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),o.addEventListener(`error`,()=>{c.emit(`error`,{type:`error`})}),o.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await bl({driver:e,failSocketFlow:l,managedEmit:c.emit,message:n,rawSocket:o,socketState:s})}),r?.signal?.addEventListener(`abort`,()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),o.close()},{once:!0}),await yl(o,c.emit,a),o.send(Mo(n)),await e.waitForReceipt(),c.socket}function yl(e,t,n){return new Promise((r,i)=>{let a=()=>{e.removeEventListener(`error`,o),t(`open`,{type:`open`}),r()},o=()=>{e.removeEventListener(`open`,a),i(Error(`WebSocket connection to ${n} failed to open.`))};e.addEventListener(`open`,a,{once:!0}),e.addEventListener(`error`,o,{once:!0})})}async function bl(e){let t=Po(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`:xl(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 Sl(e,t.data);return;case`payment-receipt`:Cl(e,t.data);return}}function xl(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=gl({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 Sl(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 Gc({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:n,event:t,expectedChannelId:e.socketState.channelId,getChannel:e.driver.getChannel,input:e.driver.httpUrl,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(Mo(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function Cl(e,t){let n=_l({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)}const wl=new WeakMap;async function Tl(e,t){let n=wl.get(e)??new Map;wl.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 El(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function Dl(e,t,n){try{let r=e.response?.headers.get(B.paymentReceipt);if(r){let e=Oo(r);if(e.challengeId===t.id&&El(n,e))return!0}}catch{}return e.challenges?.some(e=>qc(e)?El(n,Jc(e)):!1)??!1}function Ol(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=ta({chain:x,getClient:c,rpcUrl:Wn}),h=Zi({account:t}),g=l===void 0?void 0:f(l,a),_=u===void 0?void 0:f(u,a),v=i??ys(),y={store:v,notifyUpdate:e=>d?.(e)},b=async(e,t,n)=>{let r=h(e.client,t),i=t?.action?t.descriptor:n?.descriptor??wc({context:t,snapshot:e.snapshot})?.descriptor;return await p?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:Bo(i)}:{}}})??r},S=async(e,t,n)=>Oc({account:await b(e,t,n),entry:n,context:t,decimals:a,maxDeposit:g,resolved:e}),C=Mt(Ha,{canHandleChallenge:({challenge:e})=>qc(e),context:uc,async createCredential(e){let{challenge:t,context:i}=e,a=await xc({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m}),c=fi(e),l=()=>{};try{let e=!dc(i)&&i?.descriptor===void 0;e&&(l=await Tl(v,a.key),c&&(await v.get(a.key))?.opened&&await c.prepare());let n=await v.get(a.key),o=await S(a,i,n);if(!e&&c&&o.type===`open`){l=await Tl(v,a.key);let e=await v.get(a.key);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await v.get(a.key)),o=await S(a,i,n))}let s,u=c&&o.type===`open`?{store:{get:e=>v.get(e),async set(e){s=e},delete:e=>v.delete(e)},notifyUpdate(){}}:y,d=await ds(t,await kc(o,u,da(i?.autoSwap??r,la)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||Dl(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await v.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await v.set(e),y.notifyUpdate(e))}return!0}finally{l()}}}else l();return d}catch(e){throw l(),e}}}),w=async({challenge:e,channel:t,deposit:n,fetch:r,input:i,requiredCumulative:a})=>{let o=t.deposit>n?t.deposit:n,s=Us({deposit:o,maxDeposit:g,requiredCumulative:a,suggestedDeposit:e.request.suggestedDeposit===void 0?void 0:BigInt(e.request.suggestedDeposit),topUpAmount:_});s>0n&&await $c({additionalDeposit:s,challenge:e,channel:t,channelId:t.channelId,createSessionCredential:(e,t)=>C.createCredential({challenge:e,context:t}),fetch:r,input:i});let c=o+s;if(c===t.deposit)return;let l=await v.get(vs(t)),u=l?.channelId.toLowerCase()===t.channelId.toLowerCase()?l:t,d={...u,deposit:u.deposit>c?u.deposit:c};await v.set(d),y.notifyUpdate(d)};return ii(C,async({challenge:e,context:t,fetch:r,input:i})=>{if(!qc(e))return;let a=t===void 0?void 0:uc.parse(t);if(dc(a))return;let c=await xc({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),l=await v.get(c.key);if(!l?.opened)return;let u=c.snapshot?.channelId.toLowerCase()===l.channelId.toLowerCase()?c.snapshot:void 0,d=l.cumulativeAmount+To(e),f=u?BigInt(u.requiredCumulative):d,p=f>d?f:d,h=u?BigInt(u.deposit):l.deposit,g=h>l.deposit?h:l.deposit;p<=g&&g===l.deposit||!Dc(await b(c,a,l),l.descriptor)||await w({challenge:e,channel:l,deposit:g,fetch:r,input:i,requiredCumulative:p})}),li(C,async({challenge:e,credential:t,fetch:r,headers:i,input:a,refetch:c,response:l,signal:u})=>{if(!qc(e))return l;if(!ko(l))return wo(St(t).payload).action===`open`&&i.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await c?.()??l:l;let d=(await xc({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,f=await v.get(d),p={assertVoucherWithinLocalLimit:e=>Ws(e,g),createSessionCredential:(e,t)=>C.createCredential({challenge:e,context:t}),fetch:r,getChannel:()=>f??null,async topUpIfNeeded({deposit:t,requiredCumulative:n}){f&&await w({challenge:e,channel:f,deposit:f.deposit>t?f.deposit:t,fetch:r,input:a,requiredCumulative:n})}};return ul({onNeedVoucher:t=>dl({challenge:e,driver:p,input:a},t),onReceipt(){},response:l,signal:u})})}const kl=new WeakMap;function Al(e,t){kl.set(e,t)}function jl(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 Ml(e){let t=jl(`close-ready`),n=jl(`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 Nl(e){return e.method===We.tempo&&e.intent===Ge.charge}function Pl(e){if(!Nl(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Fl(e,t,n){if(!n)return t;let r={...Q(e instanceof Request?e.headers:void 0),...Q(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===B.paymentSession.toLowerCase())?t:{...t,headers:{...r,[B.paymentSession]:n}}}function Il(e,t){return e===void 0?t:{...uc.parse(e),...t}}function Ll(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 Rl(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&ra(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=Ll(e),i=ta({chain:x,getClient:e.client?()=>e.client:e.getClient,rpcUrl:Wn}),a=Zi({account:e.account}),o=Xs(),s=e.credentialContext===void 0?void 0:Il(e.credentialContext,{}),c=Ml({getSocketSession:()=>o.socketSession}),l=e.channelStore??ys(),u=new Set,d;async function f(e){let t=await l.get(e);if(t?.opened&&!u.has(t.channelId))return t}let p={async get(e){let t=await f(e);return t&&d&&(d.seenExisting.add(e),!d.committed&&!d.created.has(e)&&(d.resumed??=t)),t},async set(e){let t=vs(e);e.opened&&u.delete(e.channelId),d?.trackCreates&&!d.seenExisting.has(t)&&d.created.set(t,e),await l.set(e)},delete:e=>l.delete(e)};async function m(e){let t=vs(e);u.add(e.channelId),d?.seenExisting.delete(t),d?.resumed===e&&(d.resumed=void 0),await Promise.resolve(l.delete(t)).catch(()=>void 0)}async function h(){let e=d;if(e?.created.size){for(let[t,n]of e.created)u.add(n.channelId),await Promise.resolve(l.delete(t)).catch(()=>void 0);e.created.clear(),await I(e.committed??e.previous)}}function g(e){let t=Je(e.request.methodDetails,Ke.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=d;if(!n?.created.size||!o.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&o.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=tc({channel:o.channel,spent:o.spent,state:o.state}),!0;return!1}function _(e){return Ps(o,e)}function v(){let e=o.state.status===`active`?o.state:d?.committed?.state??d?.previous.state;return e?.status===`active`?e.units:0}function y(e){let t=d,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit||(t.resumed=void 0,t.committed=tc({channel:o.channel,spent:o.spent,state:o.state}))}let b=Ol({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:p,onChannelUpdate(e){e.channelId!==o.channel?.channelId&&(o.spent=0n),o.channel=e,o.lastChallenge&&_({type:`activated`,challengeId:o.lastChallenge.id,entry:e,spent:o.spent.toString(),units:v()}),y(e)}});ui(b);let S=Ga({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient}),C=_i({fetch:r.fetch,methods:[b],onChallenge:async(e,t)=>{if(!Kc(e))return;let n=d,r=n&&n.challengesReceived>0&&e.id===o.lastChallenge?.id,i=r&&at(e)===at(o.lastChallenge);n&&n.challengesReceived++,!i&&(g(e)||(n?.created.size?await h():r&&await I(n.committed??n.previous)),o.lastChallenge=e,_({type:`challengeReceived`,challengeId:e.id}))}});function w(e,t){return b.createCredential({challenge:e,context:Il(s,t)})}function T(e){Zs({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:o})}function E(e=o.state.status===`active`?o.state.units:0){!o.channel||!o.lastChallenge||o.state.status!==`active`&&o.state.status!==`withdrawable`&&o.state.status!==`closeRequested`&&_({type:`activated`,challengeId:o.lastChallenge.id,entry:o.channel,spent:o.spent.toString(),units:e})}async function D(t){let n=t.headers.get(B.paymentSessionSnapshot);if(!n)return;let r=As(n);ra(e.allowedChainIds,r.chainId);let s=await i({chainId:r.chainId});na(s,r.chainId);let c=a(s),{entry:l,spent:u}=await Ec({account:await e.resolveAccount?.({account:c,chainId:r.chainId,operation:{authority:Bo(r.descriptor),kind:`authorizePaymentChannel`}})??c,client:s,snapshot:r});return N(l.cumulativeAmount),await Promise.resolve(p.set(l)).catch(()=>void 0),o.channel=l,o.spent=u,l}async function O(t,n){if(!e.bootstrap||o.channel?.opened)return;let i=t instanceof Request?t.headers:void 0,{body:a,method:s,...c}=n??{},l=t instanceof Request?t.url:t,u={...c,method:`HEAD`,headers:{...Q(i),...Q(n?.headers),[B.acceptPayment]:`${We.tempo}/${Ge.charge}`}};try{let e=await r.fetch(l,u);if(e.status!==402)return await D(e);let t=pt(e).find(Nl);if(!t||!Pl(t))return;let n=await S.createCredential({challenge:t,context:{}}),i=await r.fetch(l,{...u,headers:{...Q(u.headers),[B.authorization]:n}});return i.ok?await D(i):void 0}catch{return}}function k(e,t){let n=o.socketSession;return $s({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:o.channel?.channelId===t?o.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:o.spent,tickCost:n?.tickCost})}function A(e,t){let n=Jc(t);if(!n)return;if(Vo({...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 j(e,t){let n=A(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(o.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>o.spent&&(o.spent=i),n}function M(e,t=e.challenge,n=!1){let r=(n?j(e,t):A(e.channel,t))?.acceptedCumulative??k(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return N(r),r.toString()}function N(e){Rs({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}async function P(e){let{knownDeposit:t,...n}=e,i=await $c({...n,channel:o.channel,createSessionCredential:w,fetch:r.fetch});T(i);let a=Wc({additionalDeposit:e.additionalDeposit,channel:o.channel,channelId:e.channelId,challengeId:o.lastChallenge?.id,currentState:o.state,knownDeposit:t,receipt:i,spent:o.spent});return a?.channel&&o.lastChallenge&&(await p.set(a.channel),_({type:`activated`,challengeId:o.lastChallenge.id,entry:a.channel,spent:o.spent.toString(),units:v()}),y(a.channel)),i}async function F(e){let t=o.channel?.channelId===e.channelId?o.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=Us({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 P({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n})}async function ee(e,t){let n=ec({channel:o.channel,channelId:e,challengeId:o.lastChallenge?.id,cumulativeAmount:t,spent:o.spent,state:o.state});n&&o.channel&&(_({type:`activated`,challengeId:n.challengeId,entry:o.channel,spent:n.spent,units:n.units}),await l.set(o.channel))}async function I(e){let t=nc(e,o.channel);o.channel=t.channel,o.spent=t.spent,o.state=t.state,o.channel?.opened&&await l.set(o.channel)}function te(e){let t=e.headers.get(B.paymentReceipt),n=t?Oo(t):null;return T(n),Object.assign(e,{receipt:n,challenge:o.lastChallenge,channelId:o.channel?.channelId??null,cumulative:o.channel?.cumulativeAmount??0n})}async function ne(e,t){if(d)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);o.lastUrl=e;let n=tc({channel:o.channel,spent:o.spent,state:o.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};d=i;try{await O(e,t),i.trackCreates=!0;let a=Fl(e,t,o.channel?.opened?o.channel.channelId:void 0);s&&(a={...a,context:s});let c=!n.channel?.opened;async function l(){let n=i.resumed;return!c||!n?!1:(c=!1,await m(n),a=Fl(e,t,void 0),!0)}for(;;){let t;try{t=await C(e,a)}catch(e){if(i.created.size?await h():await I(i.committed??n),await l())continue;throw e}let s=te(t),c=!1;if(s.status===402){let t=await tl({input:e,init:a,response:s,createSessionCredential:w,fetch:r.fetch,getChannel:()=>o.channel,restoreCumulative:ee,setChallenge(e){o.lastChallenge=e},topUpIfNeeded:F});t&&(c=!0,s=te(t))}if(!c&&!s.ok&&!s.receipt){if(i.created.size?await h():await I(i.committed??n),await l())continue;return s}return s}}finally{d=void 0}}async function re(e){let t=await rl({createSessionCredential:w,fetch:r.fetch,getMinimumSpent:()=>o.spent,lastUrl:o.lastUrl,resolveSignedCloseAmount:t=>M(e,t,!0),signedCloseAmount:M(e),setChallenge(e){o.lastChallenge=e},target:e});return t&&(E(),_({type:`closeStarted`}),_({type:`closed`,receipt:t})),t}let ie={createSessionCredential:w,doFetch:ne,fetch:r.fetch,getChannel:()=>o.channel,getChallenge:()=>o.lastChallenge,assertVoucherWithinLocalLimit:N,acceptReceipt(e){T(e)},topUpIfNeeded:F},L={get channelId(){return o.channel?.channelId},get cumulative(){return o.channel?.cumulativeAmount??0n},get opened(){return o.channel?.opened??!1},get state(){return o.state},fetch:ne,async topUp(e){let t=Uc({amount:e,assertVoucherWithinLocalLimit:N,channel:o.channel,decimals:r.decimals,lastChallenge:o.lastChallenge,lastUrl:o.lastUrl});return P({additionalDeposit:t.additionalDeposit,challenge:t.challenge,channelId:t.channelId,input:t.input})},async sse(e,t){return il(e,t,ie)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=Zc(e),i=t?.signal?{signal:t.signal}:void 0;await O(n,i);let a=o.channel?.opened?o.channel.channelId:void 0,{challenge:s,credential:l,httpUrl:u,wsUrl:d}=await pl({async createSessionCredential(e,t){return o.lastChallenge=e,await oi(b,{challenge:e,context:t,fetch:r.fetch,input:n}),w(e,t)},fetch:r.fetch,input:e,onProbeUrl(e){o.lastUrl=e.toString()},probeInit:Fl(n,i,a),signal:t?.signal});return o.lastChallenge=s,vl({challenge:s,credential:l,httpUrl:u,WebSocket:r.WebSocket,wsUrl:d,options:t,createSessionCredential:w,getChannel:()=>o.channel,setSocketSession(e){o.socketSession=e},async refreshChallenge(){let e=await fl({fetch:r.fetch,input:u,probeInit:Fl(u,i,o.channel?.opened?o.channel.channelId:void 0),signal:t?.signal});return o.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:N,acceptReceipt:T,rejectCloseReady:c.rejectCloseReady,rejectReceipt:c.rejectReceipt,settleCloseReady:c.settleCloseReady,settleReceipt:c.settleReceipt,topUpIfNeeded:F,waitForReceipt:c.waitForReceipt})},async close(){let e=o.socketSession,t=Gs({channel:o.channel,currentSocket:e,lastChallenge:o.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===Bc.OPEN){let r=await rc({activeSocket:n,createSessionCredential:w,currentSocket:e,spent:o.spent,target:t,waitForCloseReady:c.waitForCloseReady,waitForReceipt:c.waitForReceipt});return E(),_({type:`closeStarted`}),_({type:`closed`,receipt:r}),r}return re(t)}};return Al(L,{consumeSseResponse(e,t,n){return al(e,t,n,ie)},rehydrate({channel:e,challenge:t,input:n,spent:r}){if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!Kc(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.`);N(e.cumulativeAmount);let i=A(e,t),a=i&&i.spent>r?i.spent:r;o.lastUrl=n,o.lastChallenge=t,o.channel=e,o.spent=a,_({type:`challengeReceived`,challengeId:t.id}),_({type:`activated`,challengeId:t.id,entry:e,spent:a.toString(),units:0})}}),L}(function(e){e.serializeSnapshot=ks,e.deserializeSnapshot=As})(Rl||={});const zl=(1n<<64n)-1n,Bl={dev_second:1n,day:86400n,week:604800n};function Vl(e){return e instanceof Date?e:new Date(e)}function Hl(e){let t=e.getTime();if(!Number.isFinite(t))throw new J({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new J({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new J({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function Ul(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new J({reason:`periodCount is invalid`});let t=Bl[e.periodUnit];if(t===void 0)throw new J({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>zl)throw new J({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new J({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function Wl(e){let{challengeExpires:t,request:n}=e;Ul(n);let r=Hl(Vl(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new J({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function Gl(e){return[{address:iu(e.currency,`currency`),selector:`0x95777d59`,recipients:[iu(e.recipient,`recipient`)]}]}function Kl(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 J({reason:`challenge id must encode 32 bytes`})}}async function ql(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=Yl({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 J({reason:`keyAuthorization must use a primitive signature`});return R.from(o,{signature:s})}function Jl(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new J({reason:`invalid keyAuthorization payload`});let o=Xl(i.signature),s=Zl(o);if(Ql({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==Kl(n))throw new J({reason:`keyAuthorization challenge mismatch`});return $l(o,a),tu(eu(o),a),nu(o.scopes,a),{authorization:o,source:{address:ru(o,s),chainId:r}}}function Yl(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return R.from({address:iu(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:Hl(Vl(i.subscriptionExpires)),limits:[{token:iu(i.currency,`currency`),limit:BigInt(i.amount),period:Ul(i)}],scopes:Gl(i),type:t.keyType,witness:Kl(n)})}function Xl(e){try{return R.deserialize(e)}catch(e){throw e instanceof R.InvalidSignatureTypeError?new J({reason:`keyAuthorization must use a primitive signature`}):new J({reason:`invalid keyAuthorization payload`})}}function Zl(e){let t=e.signature;if(!t)throw new J({reason:`keyAuthorization must use a primitive signature`});return t}function Ql(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new J({reason:`keyAuthorization chainId mismatch`});if(t){if(!u(n.address,iu(t.accessKeyAddress,`accessKeyAddress`)))throw new J({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new J({reason:`keyAuthorization key type mismatch`})}}function $l(e,t){if(Wl({request:t}),e.expiry!==Hl(Vl(t.subscriptionExpires)))throw new J({reason:`keyAuthorization expiry mismatch`})}function eu(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new J({reason:`keyAuthorization must contain exactly one token limit`});return t}function tu(e,t){if(!u(e.token,iu(t.currency,`currency`)))throw new J({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new J({reason:`keyAuthorization amount mismatch`});if(e.period!==Ul(t))throw new J({reason:`keyAuthorization period mismatch`})}function nu(e,t){if(!e||e.length!==1)throw new J({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=iu(t.currency,`currency`),r=iu(t.recipient,`recipient`),i=new Set;for(let t of e){if(!u(t.address,n))throw new J({reason:`keyAuthorization call target mismatch`});let e=au(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new J({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new J({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!u(t.recipients[0],r))throw new J({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new J({reason:`keyAuthorization must allow transferWithMemo`})}function ru(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 J({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof J?e:new J({reason:`keyAuthorization signature is invalid`})}}function iu(e,t){if(!l(e))throw new J({reason:`${t} must be an address`});return e.toLowerCase()}function au(e){return typeof e==`string`?e.toLowerCase():``}const ou=H.object({accessKey:H.optional(H.custom()),account:H.optional(H.custom())});function su(e={}){let t=ta({chain:F,getClient:e.getClient,rpcUrl:Wn}),n=Zi({account:e.account});return Mt(Ua,{context:ou,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.");lu(r.request),await e.validateRequest?.(r.request);let l=await cu(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),d=Jl({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:R.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 Et({challenge:r,payload:{signature:R.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function cu(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await ql({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:Hl(Vl(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:E.fromNumber(BigInt(o.amount)),period:Ul(o)}],scopes:Gl(o),witness:Kl(i)}]});return R.fromRpc(c.keyAuthorization)}function lu(e){Ul(e),Hl(Vl(e.subscriptionExpires))}const uu=Object.assign(Ol,{manager:Rl}),du=Object.assign(Ro,{method:mo});function fu(e={}){return[Ga(e),uu(e)]}(function(e){e.charge=Ga,e.common=fu,e.session=uu,e.sessionLegacy=du,e.subscription=su})(fu||={});const pu=P.union([P.boolean(),P.literal(`true`).transform(()=>!0),P.literal(`false`).transform(()=>!1)]);async function mu(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}const hu=P.object({allowCustomEscrow:P.optional(pu),autoSwap:P.optional(pu),channel:P.optional(P.coerce.string()),deposit:P.optional(P.union([P.string(),P.number()])),payWith:P.optional(P.string()),slippage:P.optional(P.coerce.number()),tokenIn:P.optional(P.string())}),gu=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`];function _u(){let t;return ur({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:n,options:r,methodOpts:i}){let a=or(r.account),o=n.request,s=o.currency,l=Cu(i),u=Du({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()||(Kn(a)?void 0:await sr(a).get());if(!_&&Kn(a)&&Iu()){g=!0;let t=Pu(a);if(t){let i=Yn(r.rpcUrl,{network:r.network});h=e({chain:await Xn({network:r.network,rpcUrl:i}),transport:c(i)}),Tu({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let a=s?await $n(h,s,t.wallet_address).catch(()=>void 0):void 0;d=a?.symbol??s??``,f=a?.decimals??o.decimals??6}}else if(_)m=ue(_);else{let e=Ru();if(e){let t=await sr(e).get();t&&(m=ue(t))}if(!m)throw r.account?new Y({code:`ACCOUNT_NOT_FOUND`,message:`Account "${a}" not found.`,exitCode:69}):new Y({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!g&&m){let t=Yn(r.rpcUrl,{network:r.network});h=e({chain:await Xn({network:r.network,rpcUrl:t}),transport:c(t)}),Tu({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let i=s?await $n(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 Lu(t)}};if(!m||!h)throw new Y({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let v=fu({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??(Qn(h.chain)?`10`:void 0);if(!t)throw new Y({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=ku(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`);return Et({challenge:n,payload:{action:o,channelId:e,descriptor:s,cumulativeAmount:r.toString(),signature:await ts(h,m,{channelId:e,cumulativeAmount:r},i,a)},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=St(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?``:`
|
|
10
|
-
`}${
|
|
11
|
-
`}${
|
|
12
|
-
`})}catch{}return(w.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await
|
|
13
|
-
`),l&&!await e.confirm(`Close channel?`,!0)?s>=1&&m(`${
|
|
14
|
-
`)}function
|
|
7
|
+
`?2:t+1===e.length&&!n?0:1:0}function Rc(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=Fc({...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 zc(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await yc({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await Oc({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function Bc(e){let t=new URL(e.input.toString()),n=Tc(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=pt(r).find(xc);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 Vc(e){let t=await Bc(e);return{...t,credential:await e.createSessionCredential(t.challenge,{})}}function Hc(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:St(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:$a(t)}}function Uc(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function Wc(e){if(!Uc(e))return`received mismatched payment-close-ready frame`;let t=Ga(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 Gc(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!Uc(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!Ss({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function Kc(e){let{challenge:t,credential:n,options:r,WebSocket:i,wsUrl:a}=e,o=new i(a,r?.protocols),s=Hc({challenge:t,credential:n,socket:o});e.setSocketSession(s);let c=hc(o),l=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(o.readyState===mc.CONNECTING||o.readyState===mc.OPEN)&&o.close(3008,t)};return o.addEventListener(`close`,t=>{s.socket=null,s.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),c.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),o.addEventListener(`error`,()=>{c.emit(`error`,{type:`error`})}),o.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await Jc({driver:e,failSocketFlow:l,managedEmit:c.emit,message:n,rawSocket:o,socketState:s})}),r?.signal?.addEventListener(`abort`,()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),o.close()},{once:!0}),await qc(o,c.emit,a),o.send(oo(n)),await e.waitForReceipt(),c.socket}function qc(e,t,n){return new Promise((r,i)=>{let a=()=>{e.removeEventListener(`error`,o),t(`open`,{type:`open`}),r()},o=()=>{e.removeEventListener(`open`,a),i(Error(`WebSocket connection to ${n} failed to open.`))};e.addEventListener(`open`,a,{once:!0}),e.addEventListener(`error`,o,{once:!0})})}async function Jc(e){let t=co(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`:Yc(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 Xc(e,t.data);return;case`payment-receipt`:Zc(e,t.data);return}}function Yc(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=Wc({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 Xc(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 yc({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(oo(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function Zc(e,t){let n=Gc({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)}const Qc=new WeakMap;async function $c(e,t){let n=Qc.get(e)??new Map;Qc.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 el(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function tl(e,t,n){try{let r=e.response?.headers.get(R.paymentReceipt);if(r){let e=no(r);if(e.challengeId===t.id&&el(n,e))return!0}}catch{}return e.challenges?.some(e=>xc(e)?el(n,Sc(e)):!1)??!1}function nl(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:f,resolveAccount:p}=e,m=Qi({chain:b,getClient:c,rpcUrl:Hn}),h=Ji({account:t}),g=l===void 0?void 0:d(l,a),_=u===void 0?void 0:d(u,a),v=i??qo(),y={store:v,notifyUpdate:e=>f?.(e)},x=async(e,t,n)=>{let r=h(e.client,t),i=t?.action?t.descriptor:n?.descriptor??Qs({context:t,snapshot:e.snapshot})?.descriptor;return await p?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:fo(i)}:{}}})??r},S=async(e,t,n)=>nc({account:await x(e,t,n),entry:n,context:t,decimals:a,maxDeposit:g,resolved:e}),C=Mt(za,{canHandleChallenge:({challenge:e})=>xc(e),context:Rs,async createCredential(e){let{challenge:t,context:i}=e,a=await Ys({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m}),c=li(e),l=()=>{};try{let e=!zs(i)&&i?.descriptor===void 0;e&&(l=await $c(v,a.key),c&&(await v.get(a.key))?.opened&&await c.prepare());let n=await v.get(a.key),o=await S(a,i,n);if(!e&&c&&o.type===`open`){l=await $c(v,a.key);let e=await v.get(a.key);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await v.get(a.key)),o=await S(a,i,n))}let s,u=c&&o.type===`open`?{store:{get:e=>v.get(e),async set(e){s=e},delete:e=>v.delete(e)},notifyUpdate(){}}:y,d=await zo(t,await rc(o,u,ca(i?.autoSwap??r,oa)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||tl(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await v.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await v.set(e),y.notifyUpdate(e))}return!0}finally{l()}}}else l();return d}catch(e){throw l(),e}}}),w=async({challenge:e,channel:t,deposit:n,fetch:r,input:i,requiredCumulative:a,signal:o})=>{let s=t.deposit>n?t.deposit:n,c=_s({deposit:s,maxDeposit:g,requiredCumulative:a,suggestedDeposit:e.request.suggestedDeposit===void 0?void 0:BigInt(e.request.suggestedDeposit),topUpAmount:_});c>0n&&await Dc({additionalDeposit:c,challenge:e,channel:t,channelId:t.channelId,createSessionCredential:(e,t)=>C.createCredential({challenge:e,context:t}),fetch:r,input:i,signal:o});let l=s+c;if(l===t.deposit)return;let u=await v.get(Ko(t)),d=u?.channelId.toLowerCase()===t.channelId.toLowerCase()?u:t,f={...d,deposit:d.deposit>l?d.deposit:l};await v.set(f),y.notifyUpdate(f)};return ti(C,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!xc(e))return;let c=t===void 0?void 0:Rs.parse(t);if(zs(c))return;let l=await Ys({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),u=await v.get(l.key);if(!u?.opened)return;let d=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,f=u.cumulativeAmount+$a(e),p=d?BigInt(d.requiredCumulative):f,h=p>f?p:f,g=d?BigInt(d.deposit):u.deposit,_=g>u.deposit?g:u.deposit;h<=_&&_===u.deposit||!tc(await x(l,c,u),u.descriptor)||await w({challenge:e,channel:u,deposit:_,fetch:r,input:i,requiredCumulative:h,signal:a})}),oi(C,async({challenge:e,credential:t,fetch:r,headers:i,input:a,refetch:c,response:l,signal:u})=>{if(!xc(e))return l;if(!ro(l))return Qa(St(t).payload).action===`open`&&i.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await c?.()??l:l;let d=(await Ys({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,f=await v.get(d),p={assertVoucherWithinLocalLimit:e=>vs(e,g),createSessionCredential:(e,t)=>C.createCredential({challenge:e,context:t}),fetch:r,getChannel:()=>f??null,async topUpIfNeeded({deposit:t,requiredCumulative:n,signal:i}){f&&await w({challenge:e,channel:f,deposit:f.deposit>t?f.deposit:t,fetch:r,input:a,requiredCumulative:n,signal:i})}};return Rc({onNeedVoucher:(t,n)=>zc({challenge:e,driver:p,input:a,signal:n},t),onReceipt(){},response:l,signal:u})})}const rl=new WeakMap;function il(e,t){rl.set(e,t)}function al(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 ol(e){let t=al(`close-ready`),n=al(`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 sl(e){return e.method===We.tempo&&e.intent===Ge.charge}function cl(e){if(!sl(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function ll(e,t,n){if(!n)return t;let r={...Q(e instanceof Request?e.headers:void 0),...Q(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===R.paymentSession.toLowerCase())?t:{...t,headers:{...r,[R.paymentSession]:n}}}function ul(e,t){return e===void 0?t:{...Rs.parse(e),...t}}function dl(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:d(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:d(e.topUpAmount,t),WebSocket:n}}function fl(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&ea(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=dl(e),i=Qi({chain:b,getClient:e.client?()=>e.client:e.getClient,rpcUrl:Hn}),a=Ji({account:e.account}),o=ws(),s=e.credentialContext===void 0?void 0:ul(e.credentialContext,{}),c=ol({getSocketSession:()=>o.socketSession}),l=e.channelStore??qo(),u=new Set,d;async function f(e){let t=await l.get(e);if(t?.opened&&!u.has(t.channelId))return t}let p={async get(e){let t=await f(e);return t&&d&&(d.seenExisting.add(e),!d.committed&&!d.created.has(e)&&(d.resumed??=t)),t},async set(e){let t=Ko(e);e.opened&&u.delete(e.channelId),d?.trackCreates&&!d.seenExisting.has(t)&&d.created.set(t,e),await l.set(e)},delete:e=>l.delete(e)};async function m(e){let t=Ko(e);u.add(e.channelId),d?.seenExisting.delete(t),d?.resumed===e&&(d.resumed=void 0),await Promise.resolve(l.delete(t)).catch(()=>void 0)}async function h(){let e=d;if(e?.created.size){for(let[t,n]of e.created)u.add(n.channelId),await Promise.resolve(l.delete(t)).catch(()=>void 0);e.created.clear(),await re(e.committed??e.previous)}}function g(e){let t=Je(e.request.methodDetails,Ke.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=d;if(!n?.created.size||!o.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&o.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=ks({channel:o.channel,spent:o.spent,state:o.state}),!0;return!1}function _(e){return cs(o,e)}function v(){let e=o.state.status===`active`?o.state:d?.committed?.state??d?.previous.state;return e?.status===`active`?e.units:0}function y(e){let t=d,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit||(t.resumed=void 0,t.committed=ks({channel:o.channel,spent:o.spent,state:o.state}))}let x=nl({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:p,onChannelUpdate(e){e.channelId!==o.channel?.channelId&&(o.spent=0n),o.channel=e,o.lastChallenge&&_({type:`activated`,challengeId:o.lastChallenge.id,entry:e,spent:o.spent.toString(),units:v()}),y(e)}});si(x);let S=Ha({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),C=mi({fetch:r.fetch,methods:[x],onChallenge:async(e,t)=>{if(!bc(e))return;let n=d,r=n&&n.challengesReceived>0&&e.id===o.lastChallenge?.id,i=r&&at(e)===at(o.lastChallenge);n&&n.challengesReceived++,!i&&(g(e)||(n?.created.size?await h():r&&await re(n.committed??n.previous)),o.lastChallenge=e,_({type:`challengeReceived`,challengeId:e.id}))}});function w(e,t){return x.createCredential({challenge:e,context:ul(s,t)})}function T(e){Ts({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:o})}function E(e=o.state.status===`active`?o.state.units:0){!o.channel||!o.lastChallenge||o.state.status!==`active`&&o.state.status!==`withdrawable`&&o.state.status!==`closeRequested`&&_({type:`activated`,challengeId:o.lastChallenge.id,entry:o.channel,spent:o.spent.toString(),units:e})}async function D(t){let n=t.headers.get(R.paymentSessionSnapshot);if(!n)return;let r=is(n);ea(e.allowedChainIds,r.chainId);let s=await i({chainId:r.chainId});$i(s,r.chainId);let c=a(s),{entry:l,spent:u}=await ec({account:await e.resolveAccount?.({account:c,chainId:r.chainId,operation:{authority:fo(r.descriptor),kind:`authorizePaymentChannel`}})??c,client:s,snapshot:r});return N(l.cumulativeAmount),await Promise.resolve(p.set(l)).catch(()=>void 0),o.channel=l,o.spent=u,l}async function O(t,n){if(!e.bootstrap||o.channel?.opened)return;let i=t instanceof Request?t.headers:void 0,{body:a,method:s,...c}=n??{},l=t instanceof Request?t.url:t,u={...c,method:`HEAD`,headers:{...Q(i),...Q(n?.headers),[R.acceptPayment]:`${We.tempo}/${Ge.charge}`}};try{let e=await r.fetch(l,u);if(e.status!==402)return await D(e);let t=pt(e).find(sl);if(!t||!cl(t))return;let n=await S.createCredential({challenge:t,context:{}}),i=await r.fetch(l,{...u,headers:{...Q(u.headers),[R.authorization]:n}});return i.ok?await D(i):void 0}catch{return}}function k(e,t){let n=o.socketSession;return Ds({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:o.channel?.channelId===t?o.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:o.spent,tickCost:n?.tickCost})}function A(e,t){let n=Sc(t);if(!n)return;if(po({...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 j(e,t){let n=A(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(o.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>o.spent&&(o.spent=i),n}function M(e,t=e.challenge,n=!1){let r=(n?j(e,t):A(e.channel,t))?.acceptedCumulative??k(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return N(r),r.toString()}function N(e){fs({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}async function ee(e){let{knownDeposit:t,...n}=e,i=await Dc({...n,channel:o.channel,createSessionCredential:w,fetch:r.fetch});T(i);let a=vc({additionalDeposit:e.additionalDeposit,channel:o.channel,channelId:e.channelId,challengeId:o.lastChallenge?.id,currentState:o.state,knownDeposit:t,receipt:i,spent:o.spent});return a?.channel&&o.lastChallenge&&(await p.set(a.channel),_({type:`activated`,challengeId:o.lastChallenge.id,entry:a.channel,spent:o.spent.toString(),units:v()}),y(a.channel)),i}async function te(e){let t=o.channel?.channelId===e.channelId?o.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=_s({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 ee({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})}async function ne(e,t){let n=Os({channel:o.channel,channelId:e,challengeId:o.lastChallenge?.id,cumulativeAmount:t,spent:o.spent,state:o.state});n&&o.channel&&(_({type:`activated`,challengeId:n.challengeId,entry:o.channel,spent:n.spent,units:n.units}),await l.set(o.channel))}async function re(e){let t=As(e,o.channel);o.channel=t.channel,o.spent=t.spent,o.state=t.state,o.channel?.opened&&await l.set(o.channel)}function ie(e){let t=e.headers.get(R.paymentReceipt),n=t?no(t):null;return T(n),Object.assign(e,{receipt:n,challenge:o.lastChallenge,channelId:o.channel?.channelId??null,cumulative:o.channel?.cumulativeAmount??0n})}async function ae(e,t){if(d)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);o.lastUrl=e;let n=ks({channel:o.channel,spent:o.spent,state:o.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};d=i;try{await O(e,t),i.trackCreates=!0;let a=ll(e,t,o.channel?.opened?o.channel.channelId:void 0);s&&(a={...a,context:s});let c=!n.channel?.opened;async function l(){let n=i.resumed;return!c||!n?!1:(c=!1,await m(n),a=ll(e,t,void 0),!0)}for(;;){let t;try{t=await C(e,a)}catch(e){if(i.created.size?await h():await re(i.committed??n),await l())continue;throw e}let s=ie(t),c=!1;if(s.status===402){let t=await kc({input:e,init:a,response:s,createSessionCredential:w,fetch:r.fetch,getChannel:()=>o.channel,restoreCumulative:ne,setChallenge(e){o.lastChallenge=e},topUpIfNeeded:te});t&&(c=!0,s=ie(t))}if(!c&&!s.ok&&!s.receipt){if(i.created.size?await h():await re(i.committed??n),await l())continue;return s}return s}}finally{d=void 0}}async function P(e){let t=await jc({createSessionCredential:w,fetch:r.fetch,getMinimumSpent:()=>o.spent,lastUrl:o.lastUrl,resolveSignedCloseAmount:t=>M(e,t,!0),signedCloseAmount:M(e),setChallenge(e){o.lastChallenge=e},target:e});return t&&(E(),_({type:`closeStarted`}),_({type:`closed`,receipt:t})),t}let oe={createSessionCredential:w,doFetch:ae,fetch:r.fetch,getChannel:()=>o.channel,getChallenge:()=>o.lastChallenge,assertVoucherWithinLocalLimit:N,acceptReceipt(e){T(e)},topUpIfNeeded:te},se={get channelId(){return o.channel?.channelId},get cumulative(){return o.channel?.cumulativeAmount??0n},get opened(){return o.channel?.opened??!1},get state(){return o.state},fetch:ae,async topUp(e){let t=_c({amount:e,assertVoucherWithinLocalLimit:N,channel:o.channel,decimals:r.decimals,lastChallenge:o.lastChallenge,lastUrl:o.lastUrl});return ee({additionalDeposit:t.additionalDeposit,challenge:t.challenge,channelId:t.channelId,input:t.input})},async sse(e,t){return Mc(e,t,oe)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=Tc(e),i=t?.signal?{signal:t.signal}:void 0;await O(n,i);let a=o.channel?.opened?o.channel.channelId:void 0,{challenge:s,credential:l,httpUrl:u,wsUrl:d}=await Vc({async createSessionCredential(e,i){return o.lastChallenge=e,await ri(x,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),w(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){o.lastUrl=e.toString()},probeInit:ll(n,i,a),signal:t?.signal});return o.lastChallenge=s,Kc({challenge:s,credential:l,httpUrl:u,WebSocket:r.WebSocket,wsUrl:d,options:t,createSessionCredential:w,getChannel:()=>o.channel,setSocketSession(e){o.socketSession=e},async refreshChallenge(){let e=await Bc({fetch:r.fetch,input:u,probeInit:ll(u,i,o.channel?.opened?o.channel.channelId:void 0),signal:t?.signal});return o.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:N,acceptReceipt:T,rejectCloseReady:c.rejectCloseReady,rejectReceipt:c.rejectReceipt,settleCloseReady:c.settleCloseReady,settleReceipt:c.settleReceipt,topUpIfNeeded:te,waitForReceipt:c.waitForReceipt})},async close(){let e=o.socketSession,t=ys({channel:o.channel,currentSocket:e,lastChallenge:o.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===mc.OPEN){let r=await js({activeSocket:n,createSessionCredential:w,currentSocket:e,spent:o.spent,target:t,waitForCloseReady:c.waitForCloseReady,waitForReceipt:c.waitForReceipt});return E(),_({type:`closeStarted`}),_({type:`closed`,receipt:r}),r}return P(t)}};return il(se,{consumeSseResponse(e,t,n){return Nc(e,t,n,oe)},rehydrate({channel:e,challenge:t,input:n,spent:r}){if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!bc(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.`);N(e.cumulativeAmount);let i=A(e,t),a=i&&i.spent>r?i.spent:r;o.lastUrl=n,o.lastChallenge=t,o.channel=e,o.spent=a,_({type:`challengeReceived`,challengeId:t.id}),_({type:`activated`,challengeId:t.id,entry:e,spent:a.toString(),units:0})}}),se}(function(e){e.serializeSnapshot=rs,e.deserializeSnapshot=is})(fl||={});const pl=(1n<<64n)-1n,ml={dev_second:1n,day:86400n,week:604800n};function hl(e){return e instanceof Date?e:new Date(e)}function gl(e){let t=e.getTime();if(!Number.isFinite(t))throw new K({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new K({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new K({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function _l(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new K({reason:`periodCount is invalid`});let t=ml[e.periodUnit];if(t===void 0)throw new K({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>pl)throw new K({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new K({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function vl(e){let{challengeExpires:t,request:n}=e;_l(n);let r=gl(hl(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new K({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function yl(e){return[{address:Ml(e.currency,`currency`),selector:`0x95777d59`,recipients:[Ml(e.recipient,`recipient`)]}]}function bl(e){try{let t=T.fromBytes(S.toBytes(e));if(T.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new K({reason:`challenge id must encode 32 bytes`})}}async function xl(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=Cl({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:F.getSignPayload(o)}),c=I.from(s);if(c.type===`keychain`||c.type===`multisig`)throw new K({reason:`keyAuthorization must use a primitive signature`});return F.from(o,{signature:s})}function Sl(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new K({reason:`invalid keyAuthorization payload`});let o=wl(i.signature),s=Tl(o);if(El({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==bl(n))throw new K({reason:`keyAuthorization challenge mismatch`});return Dl(o,a),kl(Ol(o),a),Al(o.scopes,a),{authorization:o,source:{address:jl(o,s),chainId:r}}}function Cl(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return F.from({address:Ml(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:gl(hl(i.subscriptionExpires)),limits:[{token:Ml(i.currency,`currency`),limit:BigInt(i.amount),period:_l(i)}],scopes:yl(i),type:t.keyType,witness:bl(n)})}function wl(e){try{return F.deserialize(e)}catch(e){throw e instanceof F.InvalidSignatureTypeError?new K({reason:`keyAuthorization must use a primitive signature`}):new K({reason:`invalid keyAuthorization payload`})}}function Tl(e){let t=e.signature;if(!t)throw new K({reason:`keyAuthorization must use a primitive signature`});return t}function El(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new K({reason:`keyAuthorization chainId mismatch`});if(t){if(!l(n.address,Ml(t.accessKeyAddress,`accessKeyAddress`)))throw new K({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new K({reason:`keyAuthorization key type mismatch`})}}function Dl(e,t){if(vl({request:t}),e.expiry!==gl(hl(t.subscriptionExpires)))throw new K({reason:`keyAuthorization expiry mismatch`})}function Ol(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new K({reason:`keyAuthorization must contain exactly one token limit`});return t}function kl(e,t){if(!l(e.token,Ml(t.currency,`currency`)))throw new K({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new K({reason:`keyAuthorization amount mismatch`});if(e.period!==_l(t))throw new K({reason:`keyAuthorization period mismatch`})}function Al(e,t){if(!e||e.length!==1)throw new K({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=Ml(t.currency,`currency`),r=Ml(t.recipient,`recipient`),i=new Set;for(let t of e){if(!l(t.address,n))throw new K({reason:`keyAuthorization call target mismatch`});let e=Nl(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new K({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new K({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!l(t.recipients[0],r))throw new K({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new K({reason:`keyAuthorization must allow transferWithMemo`})}function jl(e,t){let n=F.getSignPayload(e);try{let e=I.extractAddress({payload:n,signature:t});if(!I.verify(t,{address:e,payload:n}))throw new K({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof K?e:new K({reason:`keyAuthorization signature is invalid`})}}function Ml(e,t){if(!c(e))throw new K({reason:`${t} must be an address`});return e.toLowerCase()}function Nl(e){return typeof e==`string`?e.toLowerCase():``}const Pl=B.object({accessKey:B.optional(B.custom()),account:B.optional(B.custom())});function Fl(e={}){let t=Qi({chain:N,getClient:e.getClient,rpcUrl:Hn}),n=Ji({account:e.account});return Mt(Ba,{context:Pl,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??Y.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.");Ll(r.request),await e.validateRequest?.(r.request);let u=await Il(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),d=Sl({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:F.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 Et({challenge:r,payload:{signature:F.serialize(u),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function Il(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await xl({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:gl(hl(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:T.fromNumber(BigInt(o.amount)),period:_l(o)}],scopes:yl(o),witness:bl(i)}]});return F.fromRpc(c.keyAuthorization)}function Ll(e){_l(e),gl(hl(e.subscriptionExpires))}const Rl=Object.assign(nl,{manager:fl});function zl(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[Ha(e),Rl(n)]}(function(e){e.charge=Ha,e.common=zl,e.session=Rl,e.subscription=Fl})(zl||={});const Bl=M.union([M.boolean(),M.literal(`true`).transform(()=>!0),M.literal(`false`).transform(()=>!1)]);async function Vl(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}const Hl=M.object({allowCustomEscrow:M.optional(Bl),autoSwap:M.optional(Bl),channel:M.optional(M.coerce.string()),deposit:M.optional(M.union([M.string(),M.number()])),payWith:M.optional(M.string()),slippage:M.optional(M.coerce.number()),tokenIn:M.optional(M.string())}),Ul=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`];function Wl(){let t;return sr({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:n,options:r,methodOpts:i}){let a=rr(r.account),o=n.request,c=o.currency,l=Xl(i),u=eu({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()||(Wn(a)?void 0:await ir(a).get());if(!_&&Wn(a)&&lu()){g=!0;let t=su(a);if(t){let i=qn(r.rpcUrl,{network:r.network});h=e({chain:await Jn({network:r.network,rpcUrl:i}),transport:s(i)}),Ql({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let a=c?await Zn(h,c,t.wallet_address).catch(()=>void 0):void 0;d=a?.symbol??c??``,f=a?.decimals??o.decimals??6}}else if(_)m=de(_);else{let e=du();if(e){let t=await ir(e).get();t&&(m=de(t))}if(!m)throw r.account?new J({code:`ACCOUNT_NOT_FOUND`,message:`Account "${a}" not found.`,exitCode:69}):new J({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!g&&m){let t=qn(r.rpcUrl,{network:r.network});h=e({chain:await Jn({network:r.network,rpcUrl:t}),transport:s(t)}),Ql({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let i=c?await Zn(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 uu(t)}};if(!m||!h)throw new J({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let v=zl({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??(Xn(h.chain)?`10`:void 0);if(!t)throw new J({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=nu(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 Oo(h,m,c,i,a);return Et({challenge:n,payload:{action:o,channelId:e,...o===`close`?{closeSignature:await ko(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=St(r),g=n.request,_=g.methodDetails,v=h.payload.channelId,y=_?.escrowContract??_?.escrow??`0x4d50500000000000000000000000000000000000`,b=_?.chainId??0,x=BigInt(g.amount),C=`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?` ${X.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
|
|
8
|
+
`}${X.dim(`Channel opened ${h.payload.channelId}`)}${t}\n`)}else m(`${l?``:`
|
|
9
|
+
`}${X.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&&(C=BigInt(h.payload.cumulativeAmount));let T=w.headers.get(R.paymentReceipt);if(T)try{let e=JSON.parse(S.toString(T));Kl(e,C),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&ru(v,C),s>=1&&Gl(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
|
|
10
|
+
`})}catch{}return(w.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await ql(w,{challenge:n,channelId:v,escrowContract:y,chainId:b,cumulativeAmount:C,tickCost:x,fetchUrl:a,fetchInit:o,session:t,info:m,verbose:s,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this}):(await Vl(w),v&&y&&b&&(l&&m(`
|
|
11
|
+
`),l&&!await e.confirm(`Close channel?`,!0)?s>=1&&m(`${X.dim(`Kept channel open.`)}\n`):await Jl({channelId:v,cumulativeAmount:C,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 Gl(e,t){t.info(`${t.prefix??``}${X.bold(X.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} ${X.dim(`(${Gn(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,Un(`${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(` ${X.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
|
|
12
|
+
`)}function Kl(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 ql(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 Yl():void 0,c=(()=>{if(!s||!X.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:{[R.authorization]:a}})}catch(e){t.info(X.dim(X.yellow(` [voucher failed: ${e instanceof Error?e.message:e}]`)))}o=``;continue}if(o===`payment-receipt`){if(t.verbose>=1)try{Gl(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
|
|
15
13
|
|
|
16
14
|
`})}catch{}o=``;continue}if(e.length===0)u(`
|
|
17
15
|
`);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(`
|
|
18
|
-
`);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await
|
|
19
|
-
`)){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
|
|
16
|
+
`);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await Jl({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 Jl(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:{...Q(e.fetchInit.headers),Authorization:t}});if(n.ok){if(iu(e.channelId),e.verbose>=1){let t=n.headers.get(R.paymentReceipt),r;if(t)try{let e=JSON.parse(S.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${X.dim(Un(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${X.dim(`Channel closed.`)} ${X.dim(`Spent ${Gn(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${X.dim(X.yellow(`Channel close failed`))} ${X.dim(`(${n.status})`)}\n`),e.info(`${X.dim(` channelId: ${e.channelId}`)}\n${X.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${X.dim(` escrowContract: ${e.escrowContract}`)}\n${X.dim(` chainId: ${e.chainId}`)}\n${X.dim(` response: ${t||`(empty)`}`)}\n`)}}function Yl(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 Xl(e){return Zl(Hl,e,Ul)}function Zl(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 Ql(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 J({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function $l(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function eu(e){let t=$l(e.tokenIn)??$l(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 tu(){return j.join(process.env.XDG_CONFIG_HOME||j.join(A.homedir(),`.config`),`mppx`,`channels`)}function nu(e){try{let t=k.readFileSync(j.join(tu(),e),`utf-8`).trim();return t?BigInt(t):void 0}catch{return}}function ru(e,t){let n=tu();k.mkdirSync(n,{recursive:!0}),k.writeFileSync(j.join(n,e),t.toString(),`utf-8`)}function iu(e){try{k.unlinkSync(j.join(tu(),e))}catch{}}function au(){return A.platform()===`darwin`?j.join(A.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):j.join(process.env.XDG_DATA_HOME||j.join(A.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function ou(){try{let e=k.readFileSync(au(),`utf-8`),t=[],n;for(let r of e.split(`
|
|
17
|
+
`)){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 su(e){let t=ou();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 cu;function lu(){if(cu!==void 0)return cu;try{O.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),cu=!0}catch{cu=!1}return cu}async function uu(e){return new Promise((t,n)=>{O.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 du(){let e=nr();if(Wn(e.get())&&!lu()&&A.platform()===`darwin`)try{let t=O.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 fu=[...Object.entries(Te),...Object.entries(Ee),...Object.entries(De),...Object.entries(Oe)];function pu(){return sr({method:`evm`,supports:mu,async setup({challenge:e,options:t}){let n=e.request,r=n.network?hu(Fe(n.network)):void 0,i=n.network&&n.asset?fu.find(([,e])=>Ne(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`?L({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await or(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...In({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function mu(e){if(!yn(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 hu(e){return Object.values(y).find(t=>t.id===e)}export{sr as createPlugin,cr as evm,_r as stripe,Wl as tempo,pu as x402};
|