mppx 0.21.2 → 0.21.3

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.
@@ -1,22 +1,22 @@
1
- import{createClient as e,createTransport as t,custom as n,decodeErrorResult as r,encodeFunctionData as i,erc20Abi as a,formatUnits as o,getAbiItem as s,getAddress as c,hashTypedData as l,http as u,isAddress as d,isAddressEqual as f,keccak256 as p,parseAbi as m,parseEventLogs as h,parseUnits as g}from"viem";import{call as _,getBlockNumber as v,getLogs as y,prepareTransactionRequest as b,readContract as x,sendCallsSync as S,sendRawTransactionSync as C,sendTransactionSync as w,signTransaction as T,signTypedData as E,waitForTransactionReceipt as ee}from"viem/actions";import*as te from"viem/chains";import{tempo as ne}from"viem/chains";import{AbiParameters as D,Base64 as O,Bytes as k,Hash as A,Hex as j,Json as M}from"ox";import*as N from"zod/mini";import*as P from"node:child_process";import*as F from"node:fs";import*as I from"node:os";import*as L from"node:path";import{z as R}from"zod";import"node:readline";import{tempo as z,tempoModerato as re}from"viem/tempo/chains";import{ousd as ie,pathusd as ae,usdce as oe}from"viem/tokens";import{Abis as se,Account as ce,Actions as B,Addresses as le,TokenId as ue,Transaction as de,withFeePayer as fe}from"viem/tempo";import{parseAccount as pe,privateKeyToAccount as me}from"viem/accounts";import{AccountConfig as he,Channel as ge,KeyAuthorization as _e,SignatureEnvelope as V,TempoAddress as ve,TxEnvelopeTempo as ye}from"ox/tempo";var be=Object.defineProperty,xe=Object.getOwnPropertyDescriptor,Se=Object.getOwnPropertyNames,Ce=Object.prototype.hasOwnProperty,we=(e,t)=>{let n={};for(var r in e)be(n,r,{get:e[r],enumerable:!0});return t||be(n,Symbol.toStringTag,{value:`Module`}),n},Te=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Se(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ce.call(e,s)&&s!==n&&be(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=xe(t,s))||r.enumerable});return e},Ee=(e,t,n)=>(Te(e,t,`default`),n&&Te(n,t,`default`));function De(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function Oe(e,t){let{chainId:n,decimals:r}=t;if(typeof e==`string`)return{address:e,chainId:n,decimals:r};if(De(e))return e.addresses[n]?e(n):void 0;if(e.chainId===n)return e}function ke(e,t,n={}){let{chainId:r,decimals:i}=n,a=e=>e.toLowerCase()===t.toLowerCase();for(let t of e){if(typeof t==`string`){if(a(t))return{currency:t,decimals:i};continue}if((r===void 0?De(t)?Object.keys(t.addresses).map(e=>Oe(t,{chainId:Number(e)})):[t]:[Oe(t,{chainId:r})]).some(e=>e&&a(e.address)))return{currency:t,decimals:t.decimals}}}const Ae=Symbol(`mppx.x402.asset`);function je(e){return{[Ae]:!0,address:e.address,chainId:Ge(e.network),decimals:e.decimals,network:e.network,transfer:e.transfer}}function Me(e,t){let n=e(t.chainId);return je({address:n.address,decimals:n.decimals,network:We(t.chainId),transfer:Ke(t.transfer,n)})}const Ne={USDC:je({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},Pe={USDC:je({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},Fe={USDC:je({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:je({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},Ie={USDC:je({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},Le=[Ne,Pe,Fe,Ie].flatMap(e=>Object.values(e));function Re(e,t){let n=e.toLowerCase();return Le.find(e=>e.network===t&&e.address.toLowerCase()===n)}function ze(e){return typeof e!=`object`||!e?!1:e[Ae]===!0}const Be=De;function Ve(e){return typeof e==`string`}function He(e,t){if(ze(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(typeof e==`string`)return{address:e};let n=Oe(e,{chainId:Ge(t)});if(n)return{address:n.address,decimals:n.decimals,name:n.name}}function Ue(e,t,n){let r=He(e,n);return r?c(r.address)===c(t):!1}function We(e){return`eip155:${e}`}function Ge(e){return Number(e.slice(7))}function Ke(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 qe=we({base:()=>Ne,baseSepolia:()=>Pe,celo:()=>Fe,celoSepolia:()=>Ie,define:()=>je,fromToken:()=>Me,isAsset:()=>ze,isRawAddress:()=>Ve,isToken:()=>Be,lookup:()=>Re,matches:()=>Ue,resolve:()=>He,toChainId:()=>Ge,toNetwork:()=>We}),Je=we({base:()=>Ye,baseSepolia:()=>Xe,celo:()=>Ze,celoSepolia:()=>Qe});const Ye=8453,Xe=84532,Ze=42220,Qe=11142220,H={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},$e={payment:`Payment`},et={evm:`evm`,stripe:`stripe`,tempo:`tempo`},tt={charge:`charge`,session:`session`,subscription:`subscription`},nt={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},rt={v1:`v1`,v2:`v2`};function it(e,t){if(!(!e||typeof e!=`object`))return e[t]}function at(e){let t=O.toString(e);return JSON.parse(t)}function U(e){let t=M.canonicalize(e);return O.fromString(t,{pad:!1,url:!0})}var W=we({address:()=>K,amount:()=>G,datetime:()=>st,datetimeInput:()=>ct,hash:()=>q,period:()=>dt,signature:()=>J,toDate:()=>lt,toDatetimeString:()=>ut,unwrapOptional:()=>ft});import*as ot from"zod/mini";Ee(W,ot);function G(){return N.string().check(N.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function st(){return N.string().check(N.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 ct(e=`Invalid ISO 8601 datetime`){return N.pipe(N.union([st(),N.custom(e=>e instanceof Date)]),N.transform(lt)).check(N.refine(e=>Number.isFinite(e.getTime()),e))}function lt(e){return e instanceof Date?e:new Date(e)}function ut(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function K(){return N.string().check(N.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function q(){return N.string().check(N.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function dt(){return N.string().check(N.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function J(){return N.string().check(N.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function ft(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}const pt=`Unsupported credential header: challenges may only select Payment-Authorization.`;var mt=class extends Error{name=`UnsupportedCredentialHeaderError`;constructor(){super(pt)}};const ht=W.object({description:W.optional(W.string()),digest:W.optional(W.string().check(W.regex(/^sha-256=/,`Invalid digest format`))),expires:W.optional(st()),header:W.optional(W.string().check(W.refine(Lt,pt))),id:W.string().check(W.minLength(1)),intent:W.string(),method:W.string(),meta:W.optional(W.record(W.string(),W.string())),opaque:W.optional(W.string()),realm:W.string(),request:W.record(W.string(),W.unknown())}),gt=W.extend(ht,{header:W.optional(W.string())});function _t(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=Rt(o),f=e.expires?ut(e.expires):void 0,p=e.opaque??(i===void 0?void 0:U(i)),m=u?Bt({...e,expires:f,header:d,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return ht.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 vt(e){let t=[yt(`id`,e.id),yt(`realm`,e.realm),yt(`method`,e.method),yt(`intent`,e.intent),yt(`request`,U(e.request))];e.description!==void 0&&t.push(yt(`description`,e.description)),e.digest!==void 0&&t.push(yt(`digest`,e.digest)),e.expires!==void 0&&t.push(yt(`expires`,e.expires));let n=zt(e.header);return n!==void 0&&t.push(yt(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(yt(`opaque`,U(e.meta))):t.push(yt(`opaque`,e.opaque)),`${$e.payment} ${t.join(`, `)}`}function yt(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 bt(e,t){let n=xt(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,header:a,...o}=St(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>16384)throw Error(`Request parameter too large.`);if(o.method&&!/^[a-z][a-z0-9:_-]*$/.test(o.method))throw Error(`Invalid method: "${o.method}". Must be lowercase per spec.`);if(a!==void 0&&!Lt(a))throw new mt;let s=_t({...o,request:at(r),...i&&{opaque:i}},t);return a===void 0?s:{...s,header:a}}function xt(e){let t=$e.payment,[n]=Dt(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 St(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]=Ct(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function Ct(e,t){if(e[t]===`"`)return wt(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function wt(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 Tt(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 Et(e){return Dt(e,$e.payment).length>0||e.split(`,`).some(e=>e.trim().toLowerCase()===$e.payment.toLowerCase())}function Dt(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(!Tt(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 Ot(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return kt(e.headers,t)}function kt(e,t){let n=e.get(H.wwwAuthenticate);if(!n)throw Error(`Missing ${H.wwwAuthenticate} header.`);return At(n,t)}function At(e,t){let n=Nt(e);if(n.length===0)throw Error(`No Payment schemes found.`);return n.flatMap(e=>{try{return[bt(e,t)]}catch(e){if(e instanceof mt)return[];throw e}})}function jt(e){return e?Nt(e).filter(e=>{try{return bt(e),!1}catch(e){return e instanceof mt}}).length:0}function Mt(e,t){return t<=0?e:t===1?`${e}. Skipped 1 challenge that selects a credential header other than Payment-Authorization`:`${e}. Skipped ${t} challenges that select a credential header other than Payment-Authorization`}function Nt(e){let t=Dt(e,$e.payment);return t.map((n,r)=>{let i=r+1<t.length?t[r+1]:e.length;return e.slice(n,i).replace(/,\s*$/,``)})}function Pt(e){let t=[e.realm,e.method,e.intent,U(e.request),e.expires??``,e.digest??``],n=zt(e.header);return n!==void 0&&t.push(n),t.push(e.opaque??(e.meta?U(e.meta):``)),t.join(`|`)}function Ft(e){let{header:t}=e;return t===void 0?H.authorization:Lt(t)?H.paymentAuthorization:t}function It(e){if(typeof e!=`object`||!e||!(`header`in e))return!1;let{header:t}=e;return t!==void 0&&!(typeof t==`string`&&Lt(t))}function Lt(e){return/^payment-authorization$/i.test(e)}function Rt(e){return zt(e)===void 0?void 0:H.paymentAuthorization}function zt(e){if(e!==void 0&&!/^authorization$/i.test(e)){if(Lt(e))return e;throw new mt}}function Bt(e,t){let n=Pt(e),r=k.fromString(t.secretKey),i=k.fromString(n),a=A.hmac256(r,i,{as:`Bytes`});return O.fromBytes(a,{url:!0,pad:!1})}const Vt=65536;var Ht=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},Ut=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function Wt(e){if(e.length>Vt)throw new Ut;let t=e.match(RegExp(`^${$e.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new Ht;try{let e=O.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=Gt(r);return{challenge:ht.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:at(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new Ut}}function Gt(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!Kt(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:U(e)}}function Kt(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function qt(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function Jt(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:U(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:U(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=O.fromString(s,{pad:!1,url:!0});return`${$e.payment} ${c}`}function Yt(e){return e.length>Vt?null:e.split(`,`).map(e=>e.trim()).find(e=>RegExp(`^${$e.payment}\\s+`,`i`).test(e))??null}const Xt=Symbol.for(`mppx.x402.challenge`);function Zt(e){return Object.defineProperty(e,Xt,{value:!0}),e}function Qt(e){return!!e?.[Xt]}function $t(e,t){return t?`${e} Add funds at ${t}`:e}var en=class extends Error{details;status=402;hint;fundingUrl;constructor(e,t={}){super(e),this.details=t.details,this.fundingUrl=t.fundingUrl,t.cause!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t.cause,writable:!0})}toProblemDetails(e){return{type:this.type,title:this.title,status:this.status,detail:this.message,...this.details&&Object.keys(this.details).length>0&&{details:this.details},...this.hint&&{hint:this.hint},...this.fundingUrl&&{fundingUrl:this.fundingUrl},...e&&{challengeId:e}}}},tn=class extends en{name=`InvalidChallengeError`;title=`Invalid Challenge`;status=402;type=`https://paymentauth.org/problems/invalid-challenge`;constructor(e={}){let{id:t,reason:n}=e,r=t?` "${t}"`:``,i=n?`: ${n}`:``;super(`Challenge${r} is invalid${i}.`)}},Y=class extends en{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,fundingUrl:n,reason:r}=e;super($t(r?`Payment verification failed: ${r}.`:`Payment verification failed.`,n),{details:t,fundingUrl:n})}},nn=class extends en{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.`)}},rn=class extends en{name=`PaymentOutcomeUnknownError`;title=`Payment Outcome Unknown`;type=`https://paymentauth.org/problems/payment-outcome-unknown`;challenge;credential;transactionHash;constructor(e){let{cause:t,challenge:n,credential:r,transactionHash:i}=e;super(`Payment outcome is unknown after sending a credential for challenge "${n.id}". Do not blindly retry.`,{cause:t}),this.challenge=n,this.credential=r,this.transactionHash=i}},an=class extends Error{name=`ConfigurableVouchersUnsupportedError`;signer;constructor(e){let{signer:t}=e;super(`Configurable account ${t} signs vouchers with TIP-1166 configurable account signatures, but the session challenge does not advertise \`configurableVouchers\`, so the channel was not opened.`),this.signer=t}},on=class extends Error{name=`SignerConfigChangedError`;channelId;reason;signer;constructor(e){let{cause:t,channelId:n,reason:r,signer:i}=e;super(`Signer ${i} of channel ${n} changed its account config since the channel opened, so the top-up was not signed. Close the channel and open a new one.`),this.channelId=n,this.reason=r,this.signer=i,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}},sn=class extends Error{name=`SpendingLimitExceededError`;accessKey;account;constructor(e){let{accessKey:t,account:n,cause:r}=e;super(`Access key spending limit exceeded: ${t?`key ${t} of `:``}account ${n} cannot pay this amount, so the payment was not signed.`),this.accessKey=t,this.account=n,r!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:r,writable:!0})}},cn=class extends Error{name=`ZoneSettlementPendingError`;challengeId;senderTag;senderTags;zoneId;constructor(e){let{cause:t,challengeId:n,zoneId:r}=e,i=e.senderTags??(e.senderTag?[e.senderTag]:[]),a=i.length===1?i[0]:void 0,o=a??(i.length?`with sender tag ${i.join(` or `)}`:void 0);super(`Zone ${r} withdrawal ${o?`${o} `:``}for challenge "${n}" has not settled on Tempo yet. Retry the challenge to resume waiting instead of paying again.`),this.challengeId=n,this.senderTag=a,this.senderTags=i,this.zoneId=r,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}},ln=class extends en{name=`InsufficientBalanceError`;title=`Insufficient Balance`;status=402;type=`https://paymentauth.org/problems/session/insufficient-balance`;constructor(e={}){let{cause:t,fundingUrl:n,reason:r}=e;super($t(r?`Insufficient balance: ${r}.`:`Insufficient balance.`,n),{cause:t,fundingUrl:n})}};function un(e,t){if(!e)throw new tn({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new tn({...t&&{id:t},reason:`malformed expires timestamp`});if(Date.parse(e)<=Date.now())throw new nn({expires:e})}function dn(e){let{_mppx_nonce:t,_mppx_identity:n,_mppx_expiry_grace:r,...i}=e??{};return Object.keys(i).length?i:void 0}function fn(e){return e}function pn(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}function mn(e){return{encode(t){return O.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(O.toString(t)))}catch{throw new hn}}}}var hn=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const gn=[`exact`],_n=`PAYMENT-REQUIRED`,vn=`PAYMENT-SIGNATURE`,yn=W.string().check(W.minLength(1)),bn=W.number().check(W.refine(e=>e>0,`Must be positive`)),xn=W.string().check(W.regex(/^\d+$/,`Invalid atomic amount`)),Sn=K(),Cn=W.string().check(W.regex(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),wn=W.object({description:W.optional(W.string()),iconUrl:W.optional(W.string()),mimeType:W.optional(W.string()),serviceName:W.optional(W.string()),tags:W.optional(W.array(W.string())),url:yn});W.discriminatedUnion(`type`,[W.object({name:yn,type:W.literal(`eip3009`),version:yn}),W.object({name:W.optional(W.string()),type:W.literal(`permit2`),version:W.optional(W.string())})]);const Tn=W.object({amount:xn,asset:yn,extra:W.optional(W.record(W.string(),W.unknown())),maxTimeoutSeconds:bn,network:Cn,payTo:yn,scheme:W.enum(gn)}),En=W.looseObject({info:W.record(W.string(),W.unknown()),schema:W.record(W.string(),W.unknown())}),Dn=W.record(W.string(),En),On=W.object({accepts:W.array(Tn).check(W.minLength(1)),error:W.optional(W.string()),extensions:W.optional(Dn),resource:wn,x402Version:W.literal(2)}),kn=W.object({authorization:W.object({from:Sn,nonce:q(),to:Sn,validAfter:xn,validBefore:xn,value:xn}),signature:J()}),An=W.object({permit2Authorization:W.object({deadline:xn,from:Sn,nonce:xn,permitted:W.object({amount:xn,token:Sn}),spender:Sn,witness:W.object({to:Sn,validAfter:xn})}),signature:J()}),jn=W.union([kn,An]),Mn=W.object({accepted:Tn,extensions:W.optional(Dn),payload:jn,resource:W.optional(wn),x402Version:W.literal(2)});W.object({extensions:W.optional(W.record(W.string(),W.unknown())),extra:W.optional(W.record(W.string(),W.unknown())),invalidMessage:W.optional(W.string()),invalidReason:W.optional(W.string()),isValid:W.boolean(),payer:W.optional(W.string())});const Nn=W.object({amount:W.optional(xn),errorMessage:W.optional(W.string()),errorReason:W.optional(W.string()),extensions:W.optional(W.record(W.string(),W.unknown())),extra:W.optional(W.record(W.string(),W.unknown())),network:yn,payer:W.optional(W.string()),success:W.boolean(),transaction:W.string()}),Pn=W.object({extra:W.optional(W.record(W.string(),W.unknown())),network:yn,scheme:yn,x402Version:W.number()});W.object({extensions:W.optional(W.array(W.string())),kinds:W.array(Pn),signers:W.optional(W.record(W.string(),W.array(W.string())))});function Fn(e){let{extensions:t,resource:n,...r}=e;return Tn.parse(r)}const In=mn(On),Ln=mn(Mn),Rn=mn(Nn);In.encode,In.decode;function zn(e){try{let t=JSON.parse(O.toString(e));return Vn(t)}catch{throw new hn}}const Bn=Ln.encode;Ln.decode,Rn.encode,Rn.decode;const Vn=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new hn;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new hn;let n=wn.parse(t.resource),r=t.extensions===void 0?void 0:Dn.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}};function Hn(e){let t=[U(e.accepted),U(e.resource),U(e.extensions)].join(`|`);return A.sha256(k.fromString(t),{as:`Hex`})}async function Un(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=Fn(n);if(qn(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?Yn(n.extensions):n.extensions,a=r.extra?.assetTransferMethod??`eip3009`;if(a!==`eip3009`)throw Error(`x402 exact ${String(a)} signing is not implemented yet.`);let o=r.extra?.name,s=r.extra?.version;if(typeof o!=`string`||typeof s!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let l=Math.floor(Date.now()/1e3),u={from:c(t.address),nonce:i?.mppx?Hn({accepted:r,extensions:i,resource:n.resource}):Zn(),to:c(r.payTo),validAfter:(l-600).toString(),validBefore:(l+r.maxTimeoutSeconds).toString(),value:r.amount},d=await t.signTypedData({domain:{chainId:Kn(r.network),name:o,verifyingContract:c(r.asset),version:s},message:{...u,value:BigInt(u.value),validAfter:BigInt(u.validAfter),validBefore:BigInt(u.validBefore)},primaryType:`TransferWithAuthorization`,types:Gn});return Bn({accepted:r,...i?{extensions:i}:{},payload:{authorization:u,signature:d},...n.resource?{resource:n.resource}:{},x402Version:2})}function Wn(e){let t=e.challenge.request,n;try{n=Fn(t),qn(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 Gn={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 Kn(e){return Number(e.slice(7))}function qn(e,t){let n=Kn(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=>Ve(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=c(t.asset);if(!r.some(n=>Ue(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=Jn(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>g(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function Jn(e,t){let n=e.currencies??e.assets,r=c(t.asset),i=n?.find(e=>Ue(e,r,t.network)),a=i?He(i,t.network):void 0;return a?.decimals===void 0?e.decimals===void 0?Re(r,t.network)?.decimals:e.decimals:a.decimals}function Yn(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:Xn()}}}:e}function Xn(){return Qn().slice(2)}function Zn(){return Qn()}function Qn(){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=[`authorization`],er=W.string().check(W.regex(/^\d+$/,`Invalid atomic amount`));W.object({name:W.string().check(W.minLength(1)),version:W.string().check(W.minLength(1))});const tr=W.object({chainId:W.number(),credentialTypes:W.optional(W.array(W.enum($n)).check(W.minLength(1))),decimals:W.optional(W.number()),permit2Address:W.optional(K()),splits:W.optional(W.array(W.object({amount:er,recipient:K()})))});W.object({amount:er,currency:K(),description:W.optional(W.string()),externalId:W.optional(W.string()),methodDetails:tr,recipient:K()});const nr=W.object({amount:G(),chainId:W.number(),currency:K(),credentialTypes:W.optional(W.array(W.enum($n)).check(W.minLength(1))),decimals:W.number(),description:W.optional(W.string()),externalId:W.optional(W.string()),permit2Address:W.optional(K()),recipient:K(),splits:W.optional(W.array(W.object({amount:er,recipient:K()})))}),rr=W.object({from:K(),nonce:q(),signature:J(),to:K(),type:W.literal(`authorization`),validAfter:er,validBefore:er,value:er}),ir={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 ar(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function or(e){return A.keccak256(k.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function sr(e){return`eip155:${e}`}function cr(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const lr=fn({name:`evm`,intent:`charge`,schema:{credential:{payload:rr},request:W.pipe(nr,W.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:s,...l})=>({...l,amount:g(e,i).toString(),currency:c(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:c(a)}:{},...s?{splits:s}:{}},recipient:c(o)})))}});function ur(e){return pn(lr,{canHandleChallenge({challenge:t}){return!dr(t)||Wn({challenge:t,config:e})},context:W.object({account:W.optional(W.custom())}),async createCredential({challenge:t,context:n}){if(dr(t))return Un({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(fr(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=pr(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return Jt(qt({challenge:t,payload:{from:c(r.address),nonce:or(t),signature:await r.signTypedData({domain:ar({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:c(r.address),nonce:or(t),to:c(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:ir}),to:c(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:cr({address:c(r.address),chainId:i.methodDetails.chainId})}))}})}function dr(e){return Qt(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function fr(e,t){let n=t.methodDetails.chainId,r=sr(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=>Ve(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=c(t.currency);if(!i.some(t=>Ue(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=mr(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>g(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function pr(e,t){let n=e.currencies??e.assets,r=c(t.currency),i=sr(t.methodDetails.chainId),a=n?.find(e=>Ue(e,r,i)),o=a?He(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;let s=Re(r,i)?.transfer;if(s?.type===`eip3009`)return{name:s.name,version:s.version};throw Error(`EVM authorization requires token name and version.`)}function mr(e,t){let n=e.currencies??e.assets,r=c(t.currency),i=sr(t.methodDetails.chainId),a=n?.find(e=>Ue(e,r,i)),o=a?He(a,i):void 0;return o?.decimals===void 0?e.decimals===void 0?Re(r,i)?.decimals:e.decimals:o.decimals}function hr(e){return[hr.charge(e)]}(function(e){e.charge=ur,e.assets=qe,e.chains=Je})(hr||={});var gr=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 vr(this,e)}},_r=class extends gr{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 vr(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=(()=>{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}}})(),Z={mainnet:4217,testnet:42431},yr={ousd:ie(Z.mainnet).address,usdc:c(oe(Z.mainnet).address),pathUsd:ae(Z.mainnet).address},br={[Z.mainnet]:yr.usdc,[Z.testnet]:yr.pathUsd},xr=Object.freeze({[Z.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[Z.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})});Z.mainnet,Z.testnet;const Sr={[Z.mainnet]:`https://rpc.tempo.xyz`,[Z.testnet]:`https://rpc.moderato.tempo.xyz`};function Cr(e,t){return X.link(e,t)}function wr(e){return e.startsWith(`tempo:`)}function Tr(e,t,n=6,r){let[i,a]=(Number(e)/10**n).toString().split(`.`),o=i.replace(/\B(?=(\d{3})+(?!\d))/g,`_`),s=r?.explorerUrl&&r.token?X.dim(X.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):X.dim(t);return`${a?`${o}.${a}`:o} ${s}`}const Er={mainnet:Sr[Z.mainnet],testnet:Sr[Z.testnet]};function Dr(e,t={}){return e??(t.network?Er[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}async function Or(t={}){let n=Dr(t.rpcUrl,{network:t.network});if(!n)return z;let{getChainId:r}=await import(`viem/actions`),i=await r(e({transport:u(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 kr(e){return typeof e==`bigint`?e:e.amount}function Ar(e){return e.id!==z.id}async function jr(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(kr).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 Mr(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:1e4}function Nr(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function Pr(e){return new _r({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 Fr(e){if(e&&Nr(e,`secret-tool`))throw Pr(e)}function Ir(e,t){return new Promise(n=>{P.execFile(e,t,{timeout:Mr()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function Lr(){let e=L.join(process.env.XDG_CONFIG_HOME||L.join(I.homedir(),`.config`),`mppx`,`default`);return{get(){try{return F.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(t){F.mkdirSync(L.dirname(e),{recursive:!0}),F.writeFileSync(e,t,`utf-8`)},clear(){try{F.unlinkSync(e)}catch{}}}}function Rr(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:Lr().get())}function zr(e=`main`){let t=`mppx`;return{async list(){let e=I.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(Fr(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=I.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 Fr(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=I.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=P.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),Mr());return r.stdin?.write(n),r.stdin?.end(),new Promise((e,t)=>{r.on(`close`,n=>{clearTimeout(i),n===0?e():t(Error(`secret-tool exited with code ${n}`))}),r.on(`error`,e=>{clearTimeout(i),t(Nr(e,`secret-tool`)?Pr(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=I.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]);Fr(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function Br(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 zr(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function Vr(e){return(await Br(e)).account}function Hr(e){return e}function Ur(){return Hr({method:`evm`,supports:e=>e.method===`evm`&&!Qt(e),async setup({challenge:t,options:n}){let r=t.request,i=r.methodDetails,o=i?.chainId,s=o?Wr(o):void 0,c=r.currency,l=await Vr(n.account),d=[...Object.values(Ne),...Object.values(Pe),...Object.values(Fe),...Object.values(Ie)],f=c??``;if(s&&c)try{let t=e({chain:s,transport:u()}),n=await x(t,{address:c,abi:a,functionName:`symbol`});n&&(f=n)}catch{}return{tokenSymbol:f,tokenDecimals:i?.decimals??6,explorerUrl:s?.blockExplorers?.default?.url,methods:[...hr({account:l,currencies:d})]}}})}function Wr(e){return Object.values(te).find(t=>t.id===e)}function Gr(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 Kr=W.object({customer:W.optional(W.string().check(W.minLength(1))),hooks:W.optional(W.object({inputs:W.object({tax:W.object({calculation:W.string().check(W.minLength(1))})})})),metadata:W.optional(W.record(W.string(),W.string())),receipt_email:W.optional(W.string().check(W.minLength(1)))}),qr=W.custom(e=>typeof e==`function`),Jr=W.union([Kr,qr]),Yr=fn({name:`stripe`,intent:`charge`,schema:{credential:{payload:W.object({externalId:W.optional(W.string()),spt:W.string()})},request:W.pipe(W.object({amount:G(),currency:W.string(),decimals:W.number(),description:W.optional(W.string()),externalId:W.optional(W.string()),metadata:W.optional(W.record(W.string(),W.string())),networkId:W.string(),paymentIntentOptions:W.optional(Jr),paymentMethodTypes:W.array(W.string()).check(W.minLength(1)),recipient:W.optional(W.string())}),W.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:Gr(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});function Xr(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return pn(Yr,{context:W.object({paymentMethod:W.optional(W.string())}),async createCredential({challenge:e,context:a}){let o=a?.paymentMethod??i;if(!o)throw Error(`paymentMethod is required (pass via context or parameters)`);let s=e.request.amount,c=e.request.currency,l=typeof e.request.externalId==`string`?e.request.externalId:void 0,u=e.request.methodDetails?.networkId;if(!u)throw Error(`networkId is required in challenge.methodDetails`);let d=e.request.methodDetails?.metadata;if(d?.externalId)throw Error(`methodDetails.metadata.externalId is reserved; use credential externalId instead`);let f=e.expires?Math.floor(new Date(e.expires).getTime()/1e3):Math.floor(Date.now()/1e3)+3600,p=await n({amount:s,challenge:e,client:t,currency:c,expiresAt:f,metadata:d,networkId:u,paymentMethod:o}),m=l??r;return Jt({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function Zr(e){return[Xr(e)]}(function(e){e.charge=Xr})(Zr||={});function Qr(){return Hr({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=ei(R.object({paymentMethod:R.string(),secretKey:R.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new _r({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:[Zr.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=$r(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 _r({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${(await d.json()).error.message}`,exitCode:77})}else throw new _r({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&&$r(e)?`/test`:``}/payments/${t}`;return X.link(n,t,!0)}}})}function $r(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function ei(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}const ti=Symbol.for(`mppx.fetch.skipPayment`);Object.freeze({phase:`unproved`});function ni(e,t,n={}){return async(r,i)=>{let a=new Request(r,i),o=ri(a.headers)??n.challenge,{response:s}=await t.send((t,n)=>e(t,{...n,...i?.[ti]?{[ti]:!0}:{}}),a,{...n,challenge:o});if(s.status===402&&o)for(let e of ii(s))e.method===o.method&&e.intent===o.intent&&await t.challenge(s,{challenge:e},a.url);return s}}function ri(e){for(let[,t]of e){let e=Yt(t);if(e)try{return Wt(e).challenge}catch{}}}function ii(e){try{return Ot(e)}catch{return[]}}const ai=Symbol(`mppx.deferredContext`);function oi(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=di(n)}return t}function si(e,t){let n=oi(e),r=vi(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[di(e)]??1,index:t}));return{definition:r,entries:i,header:li(i),keys:n}}function ci(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)=>gi(e,t))}function li(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${Si(n)}`}).join(`, `)}function ui(e,t,n,r){let i=new Map;for(let e of t){let t=di(e),n=i.get(t);n?n.push(e):i.set(t,[e])}return e.flatMap((e,t)=>{let a=i.get(di(e));if(!a)return[];let o=fi(e,n);return!o||o.q<=0?[]:a.filter(t=>t.canHandleChallenge?.(r===void 0?{challenge:e}:{challenge:e,context:r})??!0).map(n=>({challenge:e,index:t,match:o,method:n}))}).sort((e,t)=>hi(e.challenge)-hi(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function di(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function fi(e,t){let n;for(let r of t){if(!pi(e,r))continue;let t={...r,specificity:mi(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 pi(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function mi(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function hi(e){return+!!Qt(e)}function gi(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}`);Ci(r,`method`),Ci(i,`intent`);let a=1;for(let t of _i(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=bi(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function _i(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function vi(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>di(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]=yi(t,`payment preference "${e}"`)}return a}function yi(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return xi(e,t)}function bi(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 xi(Number(e),t)}function xi(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 Si(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function Ci(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}function wi(e){let t=``,n=!1,r=!1,i,a=``;function o(t){if(t===``){i!==void 0&&e({data:i,event:a||`message`}),i=void 0,a=``;return}let n=t.indexOf(`:`);if(n===0)return;let r=n===-1?t:t.slice(0,n);if(r!==`data`&&r!==`event`)return;let o=``;n!==-1&&(o=t.slice(t.charCodeAt(n+1)===32?n+2:n+1)),r===`event`?a=o:i=i===void 0?o:i+`
1
+ import{createClient as e,createTransport as t,custom as n,decodeErrorResult as r,encodeFunctionData as i,erc20Abi as a,formatUnits as o,getAbiItem as s,getAddress as c,hashTypedData as l,http as u,isAddress as d,isAddressEqual as f,keccak256 as p,parseAbi as m,parseEventLogs as h,parseUnits as g}from"viem";import{call as _,getBlockNumber as v,getLogs as y,prepareTransactionRequest as b,readContract as x,sendCallsSync as S,sendRawTransactionSync as C,sendTransactionSync as w,signTransaction as T,signTypedData as E,waitForTransactionReceipt as ee}from"viem/actions";import*as D from"viem/chains";import{tempo as te}from"viem/chains";import{AbiParameters as O,Base64 as k,Bytes as A,Hash as j,Hex as M,Json as N}from"ox";import*as P from"zod/mini";import*as F from"node:child_process";import*as I from"node:fs";import*as L from"node:os";import*as R from"node:path";import{z}from"zod";import"node:readline";import{tempo as B,tempoModerato as ne}from"viem/tempo/chains";import{ousd as re,pathusd as ie,usdce as ae}from"viem/tokens";import{Abis as oe,Account as se,Actions as V,Addresses as ce,TokenId as le,Transaction as ue,withFeePayer as de}from"viem/tempo";import{parseAccount as fe,privateKeyToAccount as pe}from"viem/accounts";import{AccountConfig as me,Channel as he,KeyAuthorization as ge,SignatureEnvelope as H,TempoAddress as _e,TxEnvelopeTempo as ve}from"ox/tempo";var ye=Object.defineProperty,be=Object.getOwnPropertyDescriptor,xe=Object.getOwnPropertyNames,Se=Object.prototype.hasOwnProperty,Ce=(e,t)=>{let n={};for(var r in e)ye(n,r,{get:e[r],enumerable:!0});return t||ye(n,Symbol.toStringTag,{value:`Module`}),n},we=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=xe(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Se.call(e,s)&&s!==n&&ye(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=be(t,s))||r.enumerable});return e},Te=(e,t,n)=>(we(e,t,`default`),n&&we(n,t,`default`));function Ee(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function De(e,t){let{chainId:n,decimals:r}=t;if(typeof e==`string`)return{address:e,chainId:n,decimals:r};if(Ee(e))return e.addresses[n]?e(n):void 0;if(e.chainId===n)return e}function Oe(e,t,n={}){let{chainId:r,decimals:i}=n,a=e=>e.toLowerCase()===t.toLowerCase();for(let t of e){if(typeof t==`string`){if(a(t))return{currency:t,decimals:i};continue}if((r===void 0?Ee(t)?Object.keys(t.addresses).map(e=>De(t,{chainId:Number(e)})):[t]:[De(t,{chainId:r})]).some(e=>e&&a(e.address)))return{currency:t,decimals:t.decimals}}}const ke=Symbol(`mppx.x402.asset`);function Ae(e){return{[ke]:!0,address:e.address,chainId:We(e.network),decimals:e.decimals,network:e.network,transfer:e.transfer}}function je(e,t){let n=e(t.chainId);return Ae({address:n.address,decimals:n.decimals,network:Ue(t.chainId),transfer:Ge(t.transfer,n)})}const Me={USDC:Ae({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},Ne={USDC:Ae({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},Pe={USDC:Ae({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:Ae({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},Fe={USDC:Ae({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},Ie=[Me,Ne,Pe,Fe].flatMap(e=>Object.values(e));function Le(e,t){let n=e.toLowerCase();return Ie.find(e=>e.network===t&&e.address.toLowerCase()===n)}function Re(e){return typeof e!=`object`||!e?!1:e[ke]===!0}const ze=Ee;function Be(e){return typeof e==`string`}function Ve(e,t){if(Re(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(typeof e==`string`)return{address:e};let n=De(e,{chainId:We(t)});if(n)return{address:n.address,decimals:n.decimals,name:n.name}}function He(e,t,n){let r=Ve(e,n);return r?c(r.address)===c(t):!1}function Ue(e){return`eip155:${e}`}function We(e){return Number(e.slice(7))}function Ge(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 Ke=Ce({base:()=>Me,baseSepolia:()=>Ne,celo:()=>Pe,celoSepolia:()=>Fe,define:()=>Ae,fromToken:()=>je,isAsset:()=>Re,isRawAddress:()=>Be,isToken:()=>ze,lookup:()=>Le,matches:()=>He,resolve:()=>Ve,toChainId:()=>We,toNetwork:()=>Ue}),qe=Ce({base:()=>Je,baseSepolia:()=>Ye,celo:()=>Xe,celoSepolia:()=>Ze});const Je=8453,Ye=84532,Xe=42220,Ze=11142220,U={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},Qe={payment:`Payment`},$e={evm:`evm`,stripe:`stripe`,tempo:`tempo`},et={charge:`charge`,session:`session`,subscription:`subscription`},tt={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},nt={v1:`v1`,v2:`v2`};function rt(e,t){if(!(!e||typeof e!=`object`))return e[t]}function it(e,t){return t?`${e} Add funds at ${t}`:e}var at=class extends Error{details;status=402;hint;fundingUrl;constructor(e,t={}){super(e),this.details=t.details,this.fundingUrl=t.fundingUrl,t.cause!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t.cause,writable:!0})}toProblemDetails(e){return{type:this.type,title:this.title,status:this.status,detail:this.message,...this.details&&Object.keys(this.details).length>0&&{details:this.details},...this.hint&&{hint:this.hint},...this.fundingUrl&&{fundingUrl:this.fundingUrl},...e&&{challengeId:e}}}},ot=class extends at{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}.`)}},W=class extends at{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,fundingUrl:n,reason:r}=e;super(it(r?`Payment verification failed: ${r}.`:`Payment verification failed.`,n),{details:t,fundingUrl:n})}},st=class extends at{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.`)}},ct=class extends at{name=`PaymentOutcomeUnknownError`;title=`Payment Outcome Unknown`;type=`https://paymentauth.org/problems/payment-outcome-unknown`;challenge;credential;transactionHash;constructor(e){let{cause:t,challenge:n,credential:r,transactionHash:i}=e;super(`Payment outcome is unknown after sending a credential for challenge "${n.id}". Do not blindly retry.`,{cause:t}),this.challenge=n,this.credential=r,this.transactionHash=i}},lt=class extends Error{name=`LegacyUnicodeEscapedChallengeError`;constructor(){super(`Legacy unicode-escaped challenge: the server escaped a bound parameter as \\uXXXX; upgrade the server.`)}},ut=class extends Error{name=`ConfigurableVouchersUnsupportedError`;signer;constructor(e){let{signer:t}=e;super(`Configurable account ${t} signs vouchers with TIP-1166 configurable account signatures, but the session challenge does not advertise \`configurableVouchers\`, so the channel was not opened.`),this.signer=t}},dt=class extends Error{name=`SignerConfigChangedError`;channelId;reason;signer;constructor(e){let{cause:t,channelId:n,reason:r,signer:i}=e;super(`Signer ${i} of channel ${n} changed its account config since the channel opened, so the top-up was not signed. Close the channel and open a new one.`),this.channelId=n,this.reason=r,this.signer=i,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}},ft=class extends Error{name=`SpendingLimitExceededError`;accessKey;account;constructor(e){let{accessKey:t,account:n,cause:r}=e;super(`Access key spending limit exceeded: ${t?`key ${t} of `:``}account ${n} cannot pay this amount, so the payment was not signed.`),this.accessKey=t,this.account=n,r!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:r,writable:!0})}},pt=class extends Error{name=`ZoneSettlementPendingError`;challengeId;senderTag;senderTags;zoneId;constructor(e){let{cause:t,challengeId:n,zoneId:r}=e,i=e.senderTags??(e.senderTag?[e.senderTag]:[]),a=i.length===1?i[0]:void 0,o=a??(i.length?`with sender tag ${i.join(` or `)}`:void 0);super(`Zone ${r} withdrawal ${o?`${o} `:``}for challenge "${n}" has not settled on Tempo yet. Retry the challenge to resume waiting instead of paying again.`),this.challengeId=n,this.senderTag=a,this.senderTags=i,this.zoneId=r,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}},mt=class extends at{name=`InsufficientBalanceError`;title=`Insufficient Balance`;status=402;type=`https://paymentauth.org/problems/session/insufficient-balance`;constructor(e={}){let{cause:t,fundingUrl:n,reason:r}=e;super(it(r?`Insufficient balance: ${r}.`:`Insufficient balance.`,n),{cause:t,fundingUrl:n})}};function ht(e){let t=k.toString(e);return JSON.parse(t)}function gt(e){let t=N.canonicalize(e);return k.fromString(t,{pad:!1,url:!0})}var G=Ce({address:()=>q,amount:()=>K,datetime:()=>vt,datetimeInput:()=>yt,hash:()=>J,period:()=>St,signature:()=>Y,toDate:()=>bt,toDatetimeString:()=>xt,unwrapOptional:()=>Ct});import*as _t from"zod/mini";Te(G,_t);function K(){return P.string().check(P.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function vt(){return P.string().check(P.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 yt(e=`Invalid ISO 8601 datetime`){return P.pipe(P.union([vt(),P.custom(e=>e instanceof Date)]),P.transform(bt)).check(P.refine(e=>Number.isFinite(e.getTime()),e))}function bt(e){return e instanceof Date?e:new Date(e)}function xt(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function q(){return P.string().check(P.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function J(){return P.string().check(P.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function St(){return P.string().check(P.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function Y(){return P.string().check(P.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function Ct(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}const wt=Symbol(`mppx.Challenge.legacyUnicodeEscape`),Tt=new Set([`digest`,`expires`,`header`,`intent`,`method`,`opaque`,`realm`,`request`]),Et=`Unsupported credential header: challenges may only select Payment-Authorization.`;var Dt=class extends Error{name=`UnsupportedCredentialHeaderError`;constructor(){super(Et)}};const Ot=G.object({description:G.optional(G.string()),digest:G.optional(G.string().check(G.regex(/^sha-256=/,`Invalid digest format`))),expires:G.optional(vt()),header:G.optional(G.string().check(G.refine($t,Et))),id:G.string().check(G.minLength(1)),intent:G.string(),method:G.string(),meta:G.optional(G.record(G.string(),G.string())),opaque:G.optional(G.string()),realm:G.string(),request:G.record(G.string(),G.unknown())}),kt=G.extend(Ot,{header:G.optional(G.string())});function At(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=en(o),f=e.expires?xt(e.expires):void 0,p=e.opaque??(i===void 0?void 0:gt(i)),m=u?nn({...e,expires:f,header:d,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return Ot.parse({id:m,realm:c,method:a,intent:s,request:l,...n&&{description:n},...r&&{digest:r},...f&&{expires:f},...d!==void 0&&{header:d},...i!==void 0&&{meta:i},...p!==void 0&&{opaque:p}})}const jt=/^[a-z]+$/;var Mt=class extends Error{name=`InvalidMethodError`;constructor(e){super(`Invalid method: "${e}". Must be lowercase letters a-z per spec.`)}};function Nt(e){if(!jt.test(e))throw new Mt(e)}function Pt(e,t){let n=Lt(e);if(!n)throw Error(`Missing Payment scheme.`);let r=new Set,{request:i,opaque:a,header:o,...s}=Rt(n,r);if(!i)throw Error(`Missing request parameter.`);if(i.length>16384)throw Error(`Request parameter too large.`);if(s.method!==void 0&&Nt(s.method),o!==void 0&&!$t(o))throw new Dt;let c=At({...s,request:ht(i),...a&&{opaque:a}},t),l=o===void 0?c:{...c,header:o};return[...r].some(e=>Tt.has(e))&&(l[wt]=!0),l}function Ft(e){return!!(e&&typeof e==`object`&&e[wt])}function It(e){if(Ft(e))throw new lt}function Lt(e){let t=Qe.payment,[n]=Ut(e,t);if(n===void 0)return null;let r=n+t.length;for(;r<e.length&&/\s/.test(e[r]??``);)r++;return e.slice(r)}function Rt(e,t){let n=Object.create(null),r=0;for(;r<e.length;){for(;r<e.length&&/[\s,]/.test(e[r]??``);)r++;if(r>=e.length)break;let i=r;for(;r<e.length&&/[A-Za-z0-9_-]/.test(e[r]??``);)r++;let a=e.slice(i,r).toLowerCase();if(!a)throw Error(`Malformed auth-param.`);for(;r<e.length&&/\s/.test(e[r]??``);)r++;if(e[r]!==`=`)break;for(r++;r<e.length&&/\s/.test(e[r]??``);)r++;let[o,s,c]=zt(e,r);if(r=s,c&&t?.add(a),a in n)throw Error(`Duplicate parameter: ${a}`);n[a]=o}return n}function zt(e,t){if(e[t]===`"`)return Bt(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function Bt(e,t){let n=t,r=!1,i=!1,a=t,o;for(;n<e.length;){let s=e[n];if(n++,r){s===`u`&&/^[0-9a-fA-F]{4}/.test(e.slice(n,n+4))&&(i=!0),o??=[],o.push(s),a=n,r=!1;continue}if(s===`\\`){o??=[],o.push(e.slice(a,n-1)),a=n,r=!0;continue}if(s===`"`)return[o?[...o,e.slice(a,n-1)].join(``):e.slice(t,n-1),n,i]}throw Error(`Unterminated quoted-string.`)}function Vt(e,t,n){if(e.slice(t,t+n.length).toLowerCase()!==n.toLowerCase())return!1;let r=e[t+n.length];return!!(r&&/\s/.test(r))}function Ht(e){return Ut(e,Qe.payment).length>0||e.split(`,`).some(e=>e.trim().toLowerCase()===Qe.payment.toLowerCase())}function Ut(e,t){let n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(r){i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}if(!Vt(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 Wt(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return Gt(e.headers,t)}function Gt(e,t){let n=e.get(U.wwwAuthenticate);if(!n)throw Error(`Missing ${U.wwwAuthenticate} header.`);return Kt(n,t)}function Kt(e,t){let n=Yt(e);if(n.length===0)throw Error(`No Payment schemes found.`);return n.flatMap(e=>{try{return[Pt(e,t)]}catch(e){if(e instanceof Dt||e instanceof Mt)return[];throw e}})}function qt(e){return e?Yt(e).filter(e=>{try{return Pt(e),!1}catch(e){return e instanceof Dt}}).length:0}function Jt(e,t){return t<=0?e:t===1?`${e}. Skipped 1 challenge that selects a credential header other than Payment-Authorization`:`${e}. Skipped ${t} challenges that select a credential header other than Payment-Authorization`}function Yt(e){let t=Ut(e,Qe.payment);return t.map((n,r)=>{let i=r+1<t.length?t[r+1]:e.length;return e.slice(n,i).replace(/,\s*$/,``)})}function Xt(e){let t=[e.realm,e.method,e.intent,gt(e.request),e.expires??``,e.digest??``],n=tn(e.header);return n!==void 0&&t.push(n),t.push(e.opaque??(e.meta?gt(e.meta):``)),t.join(`|`)}function Zt(e){let{header:t}=e;return t===void 0?U.authorization:$t(t)?U.paymentAuthorization:t}function Qt(e){if(typeof e!=`object`||!e||!(`header`in e))return!1;let{header:t}=e;return t!==void 0&&!(typeof t==`string`&&$t(t))}function $t(e){return/^payment-authorization$/i.test(e)}function en(e){return tn(e)===void 0?void 0:U.paymentAuthorization}function tn(e){if(e!==void 0&&!/^authorization$/i.test(e)){if($t(e))return e;throw new Dt}}function nn(e,t){let n=Xt(e),r=A.fromString(t.secretKey),i=A.fromString(n),a=j.hmac256(r,i,{as:`Bytes`});return k.fromBytes(a,{url:!0,pad:!1})}const rn=65536;var an=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},on=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function sn(e){if(e.length>rn)throw new on;let t=e.match(RegExp(`^${Qe.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new an;try{let e=k.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=cn(r);return{challenge:Ot.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:ht(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new on}}function cn(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!ln(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:gt(e)}}function ln(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function un(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function dn(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:gt(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:gt(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=k.fromString(s,{pad:!1,url:!0});return`${Qe.payment} ${c}`}function fn(e){return e.length>rn?null:e.split(`,`).map(e=>e.trim()).find(e=>RegExp(`^${Qe.payment}\\s+`,`i`).test(e))??null}const pn=Symbol.for(`mppx.x402.challenge`);function mn(e){return Object.defineProperty(e,pn,{value:!0}),e}function hn(e){return!!e?.[pn]}function gn(e,t){if(!e)throw new ot({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new ot({...t&&{id:t},reason:`malformed expires timestamp`});if(Date.parse(e)<=Date.now())throw new st({expires:e})}function _n(e){let{_mppx_nonce:t,_mppx_identity:n,_mppx_expiry_grace:r,...i}=e??{};return Object.keys(i).length?i:void 0}function vn(e){return e}function yn(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,async createCredential(e){return It(e.challenge),i.call(this,e)}}}function bn(e){return{encode(t){return k.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(k.toString(t)))}catch{throw new xn}}}}var xn=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const Sn=[`exact`],Cn=`PAYMENT-REQUIRED`,wn=`PAYMENT-SIGNATURE`,Tn=G.string().check(G.minLength(1)),En=G.number().check(G.refine(e=>e>0,`Must be positive`)),Dn=G.string().check(G.regex(/^\d+$/,`Invalid atomic amount`)),On=q(),kn=G.string().check(G.regex(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),An=G.object({description:G.optional(G.string()),iconUrl:G.optional(G.string()),mimeType:G.optional(G.string()),serviceName:G.optional(G.string()),tags:G.optional(G.array(G.string())),url:Tn});G.discriminatedUnion(`type`,[G.object({name:Tn,type:G.literal(`eip3009`),version:Tn}),G.object({name:G.optional(G.string()),type:G.literal(`permit2`),version:G.optional(G.string())})]);const jn=G.object({amount:Dn,asset:Tn,extra:G.optional(G.record(G.string(),G.unknown())),maxTimeoutSeconds:En,network:kn,payTo:Tn,scheme:G.enum(Sn)}),Mn=G.looseObject({info:G.record(G.string(),G.unknown()),schema:G.record(G.string(),G.unknown())}),Nn=G.record(G.string(),Mn),Pn=G.object({accepts:G.array(jn).check(G.minLength(1)),error:G.optional(G.string()),extensions:G.optional(Nn),resource:An,x402Version:G.literal(2)}),Fn=G.object({authorization:G.object({from:On,nonce:J(),to:On,validAfter:Dn,validBefore:Dn,value:Dn}),signature:Y()}),In=G.object({permit2Authorization:G.object({deadline:Dn,from:On,nonce:Dn,permitted:G.object({amount:Dn,token:On}),spender:On,witness:G.object({to:On,validAfter:Dn})}),signature:Y()}),Ln=G.union([Fn,In]),Rn=G.object({accepted:jn,extensions:G.optional(Nn),payload:Ln,resource:G.optional(An),x402Version:G.literal(2)});G.object({extensions:G.optional(G.record(G.string(),G.unknown())),extra:G.optional(G.record(G.string(),G.unknown())),invalidMessage:G.optional(G.string()),invalidReason:G.optional(G.string()),isValid:G.boolean(),payer:G.optional(G.string())});const zn=G.object({amount:G.optional(Dn),errorMessage:G.optional(G.string()),errorReason:G.optional(G.string()),extensions:G.optional(G.record(G.string(),G.unknown())),extra:G.optional(G.record(G.string(),G.unknown())),network:Tn,payer:G.optional(G.string()),success:G.boolean(),transaction:G.string()}),Bn=G.object({extra:G.optional(G.record(G.string(),G.unknown())),network:Tn,scheme:Tn,x402Version:G.number()});G.object({extensions:G.optional(G.array(G.string())),kinds:G.array(Bn),signers:G.optional(G.record(G.string(),G.array(G.string())))});function Vn(e){let{extensions:t,resource:n,...r}=e;return jn.parse(r)}const Hn=bn(Pn),Un=bn(Rn),Wn=bn(zn);Hn.encode,Hn.decode;function Gn(e){try{let t=JSON.parse(k.toString(e));return qn(t)}catch{throw new xn}}const Kn=Un.encode;Un.decode,Wn.encode,Wn.decode;const qn=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new xn;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new xn;let n=An.parse(t.resource),r=t.extensions===void 0?void 0:Nn.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}};function Jn(e){let t=[gt(e.accepted),gt(e.resource),gt(e.extensions)].join(`|`);return j.sha256(A.fromString(t),{as:`Hex`})}async function Yn(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=Vn(n);if($n(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?tr(n.extensions):n.extensions,a=r.extra?.assetTransferMethod??`eip3009`;if(a!==`eip3009`)throw Error(`x402 exact ${String(a)} signing is not implemented yet.`);let o=r.extra?.name,s=r.extra?.version;if(typeof o!=`string`||typeof s!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let l=Math.floor(Date.now()/1e3),u={from:c(t.address),nonce:i?.mppx?Jn({accepted:r,extensions:i,resource:n.resource}):rr(),to:c(r.payTo),validAfter:(l-600).toString(),validBefore:(l+r.maxTimeoutSeconds).toString(),value:r.amount},d=await t.signTypedData({domain:{chainId:Qn(r.network),name:o,verifyingContract:c(r.asset),version:s},message:{...u,value:BigInt(u.value),validAfter:BigInt(u.validAfter),validBefore:BigInt(u.validBefore)},primaryType:`TransferWithAuthorization`,types:Zn});return Kn({accepted:r,...i?{extensions:i}:{},payload:{authorization:u,signature:d},...n.resource?{resource:n.resource}:{},x402Version:2})}function Xn(e){let t=e.challenge.request,n;try{n=Vn(t),$n(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 Zn={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 Qn(e){return Number(e.slice(7))}function $n(e,t){let n=Qn(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=>Be(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=c(t.asset);if(!r.some(n=>He(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=er(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>g(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function er(e,t){let n=e.currencies??e.assets,r=c(t.asset),i=n?.find(e=>He(e,r,t.network)),a=i?Ve(i,t.network):void 0;return a?.decimals===void 0?e.decimals===void 0?Le(r,t.network)?.decimals:e.decimals:a.decimals}function tr(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:nr()}}}:e}function nr(){return ir().slice(2)}function rr(){return ir()}function ir(){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 ar=[`authorization`],or=G.string().check(G.regex(/^\d+$/,`Invalid atomic amount`));G.object({name:G.string().check(G.minLength(1)),version:G.string().check(G.minLength(1))});const sr=G.object({chainId:G.number(),credentialTypes:G.optional(G.array(G.enum(ar)).check(G.minLength(1))),decimals:G.optional(G.number()),permit2Address:G.optional(q()),splits:G.optional(G.array(G.object({amount:or,recipient:q()})))});G.object({amount:or,currency:q(),description:G.optional(G.string()),externalId:G.optional(G.string()),methodDetails:sr,recipient:q()});const cr=G.object({amount:K(),chainId:G.number(),currency:q(),credentialTypes:G.optional(G.array(G.enum(ar)).check(G.minLength(1))),decimals:G.number(),description:G.optional(G.string()),externalId:G.optional(G.string()),permit2Address:G.optional(q()),recipient:q(),splits:G.optional(G.array(G.object({amount:or,recipient:q()})))}),lr=G.object({from:q(),nonce:J(),signature:Y(),to:q(),type:G.literal(`authorization`),validAfter:or,validBefore:or,value:or}),ur={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 dr(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function fr(e){return j.keccak256(A.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function pr(e){return`eip155:${e}`}function mr(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const hr=vn({name:`evm`,intent:`charge`,schema:{credential:{payload:lr},request:G.pipe(cr,G.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:s,...l})=>({...l,amount:g(e,i).toString(),currency:c(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:c(a)}:{},...s?{splits:s}:{}},recipient:c(o)})))}});function gr(e){return yn(hr,{canHandleChallenge({challenge:t}){return!_r(t)||Xn({challenge:t,config:e})},context:G.object({account:G.optional(G.custom())}),async createCredential({challenge:t,context:n}){if(_r(t))return Yn({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(vr(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=yr(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return dn(un({challenge:t,payload:{from:c(r.address),nonce:fr(t),signature:await r.signTypedData({domain:dr({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:c(r.address),nonce:fr(t),to:c(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:ur}),to:c(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:mr({address:c(r.address),chainId:i.methodDetails.chainId})}))}})}function _r(e){return hn(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function vr(e,t){let n=t.methodDetails.chainId,r=pr(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=>Be(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=c(t.currency);if(!i.some(t=>He(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=br(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>g(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function yr(e,t){let n=e.currencies??e.assets,r=c(t.currency),i=pr(t.methodDetails.chainId),a=n?.find(e=>He(e,r,i)),o=a?Ve(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;let s=Le(r,i)?.transfer;if(s?.type===`eip3009`)return{name:s.name,version:s.version};throw Error(`EVM authorization requires token name and version.`)}function br(e,t){let n=e.currencies??e.assets,r=c(t.currency),i=pr(t.methodDetails.chainId),a=n?.find(e=>He(e,r,i)),o=a?Ve(a,i):void 0;return o?.decimals===void 0?e.decimals===void 0?Le(r,i)?.decimals:e.decimals:o.decimals}function xr(e){return[xr.charge(e)]}(function(e){e.charge=gr,e.assets=Ke,e.chains=qe})(xr||={});var Sr=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 wr(this,e)}},Cr=class extends Sr{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 wr(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=(()=>{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}}})(),Z={mainnet:4217,testnet:42431},Tr={ousd:re(Z.mainnet).address,usdc:c(ae(Z.mainnet).address),pathUsd:ie(Z.mainnet).address},Er={[Z.mainnet]:Tr.usdc,[Z.testnet]:Tr.pathUsd},Dr=Object.freeze({[Z.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[Z.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})});Z.mainnet,Z.testnet;const Or={[Z.mainnet]:`https://rpc.tempo.xyz`,[Z.testnet]:`https://rpc.moderato.tempo.xyz`};function kr(e,t){return X.link(e,t)}function Ar(e){return e.startsWith(`tempo:`)}function jr(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 Mr={mainnet:Or[Z.mainnet],testnet:Or[Z.testnet]};function Nr(e,t={}){return e??(t.network?Mr[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}async function Pr(t={}){let n=Nr(t.rpcUrl,{network:t.network});if(!n)return B;let{getChainId:r}=await import(`viem/actions`),i=await r(e({transport:u(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 Fr(e){return typeof e==`bigint`?e:e.amount}function Ir(e){return e.id!==B.id}async function Lr(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(Fr).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 Rr(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:1e4}function zr(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function Br(e){return new Cr({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 Vr(e){if(e&&zr(e,`secret-tool`))throw Br(e)}function Hr(e,t){return new Promise(n=>{F.execFile(e,t,{timeout:Rr()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function Ur(){let e=R.join(process.env.XDG_CONFIG_HOME||R.join(L.homedir(),`.config`),`mppx`,`default`);return{get(){try{return I.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(t){I.mkdirSync(R.dirname(e),{recursive:!0}),I.writeFileSync(e,t,`utf-8`)},clear(){try{I.unlinkSync(e)}catch{}}}}function Wr(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:Ur().get())}function Gr(e=`main`){let t=`mppx`;return{async list(){let e=L.platform();if(e===`darwin`){let{stdout:e,error:n}=await Hr(`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 Hr(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(Vr(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=L.platform();if(n===`darwin`){let{stdout:n,error:r}=await Hr(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await Hr(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return Vr(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=L.platform();if(r===`darwin`){await Hr(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await Hr(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=F.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),Rr());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(zr(e,`secret-tool`)?Br(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=L.platform();if(n===`darwin`){await Hr(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await Hr(`secret-tool`,[`clear`,`service`,t,`account`,e]);Vr(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function Kr(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=Wr(e),i=await Gr(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function qr(e){return(await Kr(e)).account}function Jr(e){return e}function Yr(){return Jr({method:`evm`,supports:e=>e.method===`evm`&&!hn(e),async setup({challenge:t,options:n}){let r=t.request,i=r.methodDetails,o=i?.chainId,s=o?Xr(o):void 0,c=r.currency,l=await qr(n.account),d=[...Object.values(Me),...Object.values(Ne),...Object.values(Pe),...Object.values(Fe)],f=c??``;if(s&&c)try{let t=e({chain:s,transport:u()}),n=await x(t,{address:c,abi:a,functionName:`symbol`});n&&(f=n)}catch{}return{tokenSymbol:f,tokenDecimals:i?.decimals??6,explorerUrl:s?.blockExplorers?.default?.url,methods:[...xr({account:l,currencies:d})]}}})}function Xr(e){return Object.values(D).find(t=>t.id===e)}function Zr(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 Qr=G.object({customer:G.optional(G.string().check(G.minLength(1))),hooks:G.optional(G.object({inputs:G.object({tax:G.object({calculation:G.string().check(G.minLength(1))})})})),metadata:G.optional(G.record(G.string(),G.string())),receipt_email:G.optional(G.string().check(G.minLength(1)))}),$r=G.custom(e=>typeof e==`function`),ei=G.union([Qr,$r]),ti=vn({name:`stripe`,intent:`charge`,schema:{credential:{payload:G.object({externalId:G.optional(G.string()),spt:G.string()})},request:G.pipe(G.object({amount:K(),currency:G.string(),decimals:G.number(),description:G.optional(G.string()),externalId:G.optional(G.string()),metadata:G.optional(G.record(G.string(),G.string())),networkId:G.string(),paymentIntentOptions:G.optional(ei),paymentMethodTypes:G.array(G.string()).check(G.minLength(1)),recipient:G.optional(G.string())}),G.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:Zr(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});function ni(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return yn(ti,{context:G.object({paymentMethod:G.optional(G.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 dn({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function ri(e){return[ni(e)]}(function(e){e.charge=ni})(ri||={});function ii(){return Jr({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=oi(z.object({paymentMethod:z.string(),secretKey:z.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new Cr({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:[ri.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=ai(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 Cr({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${(await d.json()).error.message}`,exitCode:77})}else throw new Cr({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&&ai(e)?`/test`:``}/payments/${t}`;return X.link(n,t,!0)}}})}function ai(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function oi(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}const si=Symbol.for(`mppx.fetch.skipPayment`);Object.freeze({phase:`unproved`});function ci(e,t,n={}){return async(r,i)=>{let a=new Request(r,i),o=li(a.headers)??n.challenge,{response:s}=await t.send((t,n)=>e(t,{...n,...i?.[si]?{[si]:!0}:{}}),a,{...n,challenge:o});if(s.status===402&&o)for(let e of ui(s))e.method===o.method&&e.intent===o.intent&&await t.challenge(s,{challenge:e},a.url);return s}}function li(e){for(let[,t]of e){let e=fn(t);if(e)try{return sn(e).challenge}catch{}}}function ui(e){try{return Wt(e)}catch{return[]}}const di=Symbol(`mppx.deferredContext`);function fi(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=_i(n)}return t}function pi(e,t){let n=fi(e),r=wi(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[_i(e)]??1,index:t}));return{definition:r,entries:i,header:hi(i),keys:n}}function mi(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)=>Si(e,t))}function hi(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${Oi(n)}`}).join(`, `)}function gi(e,t,n,r){let i=new Map;for(let e of t){let t=_i(e),n=i.get(t);n?n.push(e):i.set(t,[e])}let a=e.flatMap((e,t)=>{let a=i.get(_i(e));if(!a)return[];let o=vi(e,n);return!o||o.q<=0?[]:a.filter(t=>t.canHandleChallenge?.(r===void 0?{challenge:e}:{challenge:e,context:r})??!0).map(n=>({challenge:e,index:t,match:o,method:n}))}).sort((e,t)=>xi(e.challenge)-xi(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n}),o=a.filter(({challenge:e})=>!Ft(e));return o.length===0&&a[0]&&It(a[0].challenge),o}function _i(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function vi(e,t){let n;for(let r of t){if(!yi(e,r))continue;let t={...r,specificity:bi(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 yi(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function bi(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function xi(e){return+!!hn(e)}function Si(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}`);ki(r,`method`),ki(i,`intent`);let a=1;for(let t of Ci(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=Ei(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function Ci(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function wi(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>_i(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]=Ti(t,`payment preference "${e}"`)}return a}function Ti(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return Di(e,t)}function Ei(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 Di(Number(e),t)}function Di(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 Oi(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function ki(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}function Ai(e){let t=``,n=!1,r=!1,i,a=``;function o(t){if(t===``){i!==void 0&&e({data:i,event:a||`message`}),i=void 0,a=``;return}let n=t.indexOf(`:`);if(n===0)return;let r=n===-1?t:t.slice(0,n);if(r!==`data`&&r!==`event`)return;let o=``;n!==-1&&(o=t.slice(t.charCodeAt(n+1)===32?n+2:n+1)),r===`event`?a=o:i=i===void 0?o:i+`
2
2
  `+o}return{feed(e){if(!n&&e&&(n=!0,e.startsWith(``)&&(e=e.slice(1))),r&&e&&(r=!1,e.startsWith(`
3
3
  `)&&(e=e.slice(1))),t+=e,e.indexOf(`
4
4
  `)===-1&&e.indexOf(`\r`)===-1)return;let i=0,a=t.indexOf(`
5
5
  `),s=t.indexOf(`\r`);for(;a!==-1||s!==-1;){let e=a===-1?s:s===-1?a:Math.min(a,s);o(t.slice(i,e)),i=e+1,e===s&&(i===t.length?r=!0:a===i&&i++,s=t.indexOf(`\r`,i)),a!==-1&&a<i&&(a=t.indexOf(`
6
- `,i))}t=t.slice(i)}}}const Ti=[H.authorization,_n,`PAYMENT-RESPONSE`,vn];function Ei(e,t,n){let r=new Headers(e.headers);for(let e of Ti)e===H.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}function Di(e){if(typeof e==`string`)try{let t=JSON.parse(e),n=t?.id;return t?.jsonrpc!==`2.0`||typeof t?.method!=`string`?void 0:typeof n==`string`||typeof n==`number`?n:void 0}catch{return}}function Oi(e){if(typeof e?.body!=`string`)return!1;try{let t=JSON.parse(e.body);return t?.jsonrpc===`2.0`&&t?.method===`tools/call`&&t.params?._meta?.[`mppx/payment-client`]===!0}catch{return!1}}const ki=1048576,Ai=new WeakMap;function ji(e){let t=Di(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 Mi(e){if(!e||typeof e!=`object`)return;let t=e,n=t.id;if(t.jsonrpc!==`2.0`||n!==void 0&&typeof n!=`string`&&typeof n!=`number`)return;let r=`error`in t;if(r!==`result`in t)return r?Number.isInteger(t.error?.code)&&typeof t.error?.message==`string`?e:void 0:n!==void 0&&typeof t.result==`object`?e:void 0}function Ni(e){if(!e||typeof e!=`object`)return;let t=e?.challenges;if(!Array.isArray(t)||t.length===0)return;let n=[];for(let e of t){if(!gt.safeParse(e).success)return;if(It(e))continue;let t=ht.safeParse(e);if(!t.success)return;n.push(t.data)}if(n.length===0)return;let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function Pi(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:Ni(e.error.data):Ni(e.result?._meta?.[`org.paymentauth/payment-required`])}function Fi(e,t){return!e||e.id!==t?[]:Pi(e)?.challenges??[]}async function Ii(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=wi(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=Mi(JSON.parse(e.data))}catch{}});try{for(;;){if(i)return a;let{done:e,value:s}=await t.read();if(e)return o.feed(n.decode()),a;if(r+=s.byteLength,r>ki)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function Li(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=``;try{for(;;){let{done:e,value:a}=await t.read();if(e)return Mi(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>ki)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function Ri(e){let t=Ai.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>ki)){if(t.includes(`application/json`))return Li(e);if(t.includes(`text/event-stream`))return Ii(e)}})();return Ai.set(e,n),n}function zi(){return{getChallenges(e,t){let n=ji(t);return e.status===402||n===void 0?[]:Ri(e).then(e=>Fi(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=Wt(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}function Bi(){return{getChallenges(e){let t=e.headers.get(H.wwwAuthenticate);return e.status!==402||!t||!Et(t)?[]:Ot(e)},setCredential(e,t,n){return Ei(e,n?.challenge?Ft(n.challenge):H.authorization,t)}}}function Vi(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(_n);if(!t)return[];let n=zn(t);return n.accepts.flatMap((e,t)=>{let r=Tn.safeParse(e);if(!r.success)return[];let i=r.data;return Zt(_t({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 Ei(e,vn,t)}}}function Hi(e){return e}function Ui(){let e=[Bi(),Vi(),zi()],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 Hi({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 Wi=new WeakMap;function Gi(e,t){return Wi.set(e,t),e}function Ki(e){return Wi.has(e)}function qi(e,t){return Promise.resolve(Wi.get(e)?.(t))}function Ji(e){return Wi.get(e)}const Yi=new WeakMap,Xi=new WeakMap,Zi=new WeakMap,Qi=new WeakMap;function $i(e,t){return Yi.set(e,t),e}function ea(e){Yi.delete(e)}function ta(e,t,n){Yi.has(e)&&Xi.set(t,n)}function na(e){return Xi.get(e)}function ra(e,t){return Promise.resolve(Yi.get(e)?.(t)??t.response)}function ia(e,t){return Qi.set(e,t),e}function aa(e,t){try{return Qi.get(e)?.(t)}catch{return}}function oa(e,t){Zi.set(e,t)}function sa(e){return Zi.get(e)??Xi.get(e)?.origin}async function ca(e,t){let{attempts:n,signal:r}=t;for(let t=1;;t++){r?.throwIfAborted();try{return await e()}catch(e){if(!(e instanceof cn)||t>=n)throw e;r?.throwIfAborted()}}}function la(e,t,n){if(!ua(e)&&(e.method!==`tempo`||e.intent!==`session`))return;t=typeof t==`function`?t():t;let{realm:r}=e;if(r.toLowerCase()===t.hostname.toLowerCase())return;let i=t.origin.toLowerCase();for(let[e,t]of Object.entries(n??{}))if(t===r&&da(e)===i)return;throw Error(`Refusing to sign Tempo proof for realm ${JSON.stringify(r)} from ${t.origin}. Pin the realm to this origin with \`trustedTempoProofRealms\` if this server is expected to issue it.`)}function ua(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function da(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}const fa=Symbol.for(`mppx.fetch.wrapper`),pa=Symbol.for(`mppx.fetch.identity`),ma=Symbol.for(`mppx.fetch.skipPayment`);function ha(e={}){return{...e,[ma]:!0}}const ga=65536,_a=new WeakMap;async function va(e){if(!e.body)return e;let t=e.clone().body.getReader(),n=[],r=0,i=!1,a=setTimeout(()=>{i=!0,t.cancel().catch(()=>{})},2e3);try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(n.push(a),r+=a.byteLength,r>ga){i=!0;break}}}finally{clearTimeout(a),t.cancel().catch(()=>{})}if(!i)return e;e.body.cancel().catch(()=>{});let o=new Headers(e.headers);o.delete(`content-length`),o.set(`Mppx-Body-Truncated`,`true`);let s=new Response(new Blob(n).slice(0,ga),{headers:o,status:e.status,statusText:e.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{value:e[t]});return s}async function ya(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 ba(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=Ui(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&Ua(e.fetch)),d=e.eventDispatcher??Sa(),f=t??si(a),p=Wa(r),m=async(e,t,n)=>u?u.send((e,n)=>p(e,t?.[ma]?ha(n):n),new Request(e,t),n):{response:await p(e,t),headers:[]},h=async(e,t,r)=>{let g=Ha(e,t?.headers),_=g.has(H.acceptPayment),v=Xa(g,f),y=Ba(e,t,g),b=za(e,t,g,v.header,_,n),x=await m(Ga(b.input),b.init),S=x.response,C=x.headers,w=Va(b.init,await y);if(t?.[ma]||Oi(w)||!await c.isPaymentRequired(S,w))return S;let T=t?.context,{context:E,orderChallenges:ee,...te}=w??{},ne,D,O,k,A;try{for(let n=0;n<i;n++){D=await c.getChallenges(S,w);let f=(await Za(ui(D,a,v.entries,T),ee??s))[0];if(!f){if(await ya(k,{challenges:D,response:S,status:`rejected`}),n>0)return S;throw Error(Mt(`No method found for challenges: ${D.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`,ao(S)))}let g=f.challenge;ne=g,O=f.method,ne.expires&&un(ne.expires,ne.id),await u?.challenge(S,{challenge:g},to(b.input).href);let _=await io(S,b.input,b.input,te);la(g,()=>to(_),l);let y=k,x=vt(g),E=y?.method===f.method&&y?.key===x,j=!1;if(y){let e=await ya(y,{challenges:D,response:S,status:E?`pending`:`rejected`});j=E&&!e}k=j?y:void 0;let M=Da(async n=>{if(n===void 0&&j&&y)return y.promise;j&&y&&(await ya(y,{status:`rejected`}),k=void 0),Ka(e,t)?.throwIfAborted();let r=n??T;if(!Ki(f.method))return ca(()=>Ya(g,f.method,r,no(_)),{attempts:i,signal:Ka(e,t)});let a={origin:to(_).origin,prepare:()=>qi(f.method,{challenge:g,context:r,fetch:u?ni(p,u,{challenge:g}):p,input:_,signal:Ka(e,t)})},o=a.prepare().then(()=>Ya(g,f.method,r,a));return k={context:r,attempt:a,key:n===void 0?x:void 0,method:f.method,promise:o},o}),N=await d.emit(`challenge.received`,Oa({challenge:g,challenges:D,createCredential:M,init:t,input:e,method:f.method,response:S}))??(o?await o(ne,{createCredential:M}):void 0)??await M(),P=k;P&&await P.promise.catch(()=>void 0)!==N&&(await ya(P,{status:`rejected`}),k=void 0);let F=k?k.context:T;Ja(N);let I=qa(N,g);await d.emit(`credential.created`,ka({challenge:g,credential:N,init:t,input:e,method:f.method,response:S}));let L=e=>new rn({cause:e,challenge:g,credential:N,transactionHash:aa(f.method,N)});try{({response:S}=await m(_,{...c.setCredential({...te,headers:b.headers},N,{challenge:g}),redirect:`manual`},{challenge:I,headers:C}))}catch(e){throw A=L(e),e}let R=await c.isPaymentRequired(S,w);if(R||(await ya(P,{response:S,status:S.status>=300&&S.status<400?`pending`:S.ok?`accepted`:`rejected`}),k=void 0),S.ok&&Ca(d,`payment.response`)&&await d.emit(`payment.response`,Aa({challenge:g,credential:N,init:t,input:e,method:f.method,response:S})),!R){if(S.status>=500&&Ca(d,`payment.failed`)){try{S=await va(S)}catch(e){throw A=L(e),S=new Response(null,{headers:S.headers,status:S.status,statusText:S.statusText}),e}await d.emit(`payment.failed`,ja({challenge:g,challenges:D,error:L(),init:t,input:e,method:f.method,response:S}))}return S.ok?ra(f.method,{context:F,challenge:g,credential:N,fetch:p,headers:b.headers,input:_,...r?{refetch:()=>h(Ga(b.input),t,!1)}:{},response:S,signal:Ka(e,t)}):S}}D=void 0;try{D=await c.getChallenges(S,w)}catch{}return await ya(k,{challenges:D,response:S,status:`rejected`}),S}catch(n){throw await ya(k,{challenges:D,response:S,status:`rejected`}),await d.emit(`payment.failed`,ja({challenge:ne,challenges:D,error:A??n,init:t,input:e,method:O,response:S})),n}},g=(e,t)=>h(e,t,!0);return g[fa]=p,u&&(g[pa]=u),g}function xa(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 Sa(){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 wa(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await Ea(e[`*`],t,n),r}case`credential.created`:await Ta(e[`credential.created`],n),await Ea(e[`*`],t,n);return;case`payment.failed`:await Ta(e[`payment.failed`],n),await Ea(e[`*`],t,n);return;case`payment.response`:await Ta(e[`payment.response`],n),await Ea(e[`*`],t,n);return}},on:(t,n)=>{switch(t){case`*`:case`challenge.received`:case`credential.created`:case`payment.failed`:case`payment.response`:return e[t].add(n),()=>e[t].delete(n);default:throw Error(`Unknown client event "${String(t)}".`)}}};return _a.set(t,t=>e[t].size>0||e[`*`].size>0),t}function Ca(e,t){return _a.get(e)?.(t)??!0}async function wa(e,t){try{return await e(t)}catch{return}}async function Ta(e,t){for(let n of e)try{await n(t)}catch{}}async function Ea(e,t,n){await Ta(e,Object.freeze({name:t,payload:n}))}function Da(e){let t;return n=>(t??=e(n),t)}function Oa(e){return Object.freeze({challenge:Ia(e.challenge),challenges:e.challenges.map(e=>Ia(e)),createCredential:e.createCredential,init:Ma(e.init),input:Na(e.input),method:Pa(e.method),response:Fa(e.response)})}function ka(e){return Object.freeze({challenge:Ia(e.challenge),credential:e.credential,init:Ma(e.init),input:Na(e.input),method:Pa(e.method),...e.response===void 0?{}:{response:Fa(e.response)}})}function Aa(e){return Object.freeze({challenge:Ia(e.challenge),credential:e.credential,init:Ma(e.init),input:Na(e.input),method:Pa(e.method),response:Fa(e.response)})}function ja(e){return Object.freeze({...e.challenge?{challenge:Ia(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>Ia(e))}:{},error:e.error,init:Ma(e.init),input:Na(e.input),...e.method?{method:Pa(e.method)}:{},...e.response===void 0?{}:{response:Fa(e.response)}})}function Ma(e){if(e)return Ra({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function Na(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function Pa(e){return Ra(Object.assign({},e))}function Fa(e){if(e instanceof Response)try{return e.clone()}catch{let t=new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText});for(let n of[`redirected`,`type`,`url`])Object.defineProperty(t,n,{value:e[n]});return t}return Ia(e)}function Ia(e){try{return La(structuredClone(e))}catch{return Ra(e)}}function La(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))La(t);return e}function Ra(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function za(e,t,n,r,i,a){let o=!!r&&!i&&Qa(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(H.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function Ba(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 Va(e,t){return t===void 0?e:{...e,body:t}}function Ha(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function Ua(e){return e[pa]}function Wa(e){let t=e;for(;t[fa];)t=t[fa];return t}function Ga(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function Ka(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function qa(e,t){try{let{challenge:n}=Wt(e);return n.id===t.id?t:{...n,...t.header!==void 0&&{header:t.header}}}catch{return t}}function Ja(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
7
- `))throw Error(`Credential header value contains illegal newline characters`)}async function Ya(e,t,n,r){let i=t.context&&n!==void 0?t.context.parse(n):void 0,a=i===void 0?{challenge:e}:{challenge:e,context:i};return r?.origin&&oa(a,r.origin),r&&`prepare`in r&&ta(t,a,r),t.createCredential(a)}function Xa(e,t){let n=e.get(H.acceptPayment);if(!n)return t;try{return{...t,entries:ci(n),header:n}}catch{return t}}async function Za(e,t){return t?t(e):e}function Qa(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=to(e);return t===`same-origin`?!eo()||n.origin===globalThis.location.origin:t.origins.some(e=>$a(n,e))}function $a(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 eo(){return globalThis.location!==void 0}function to(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,eo()?globalThis.location.href:void 0)}function no(e){try{return{origin:to(e).origin}}catch{return}}function ro(e,t){let n=e instanceof Request?e:void 0;if((t.mode??n?.mode)===`no-cors`)throw Error(`Cannot automatically pay a no-cors request: it cannot carry a credential.`);if((t.cache??n?.cache)===`only-if-cached`)throw Error(`Cannot automatically pay an only-if-cached request: its retry cannot reach the server.`)}async function io(e,t,n,r){if(ro(t,r),!e.url)return t;let i=new URL(e.url),a=to(n);if(i.origin!==a.origin)throw Error(`Refusing to send payment credential across redirect from ${a.origin} to ${i.origin}`);let o=(r.method??(t instanceof Request?t.method:`GET`)).toUpperCase();if(e.redirected&&o!==`GET`&&o!==`HEAD`)throw Error(`Cannot automatically pay a redirected ${o} request. Use prepareRequest() to preserve redirect semantics.`);if(t instanceof Request){let n=r.body==null?t.clone():t,i=new Request(n,t.mode===`navigate`&&r.mode===void 0?{...r,mode:`same-origin`}:r);return i.url.split(`#`)[0]===e.url?i:i.body?new Request(e.url,{body:await i.arrayBuffer(),cache:i.cache,credentials:i.credentials,headers:i.headers,integrity:i.integrity,keepalive:i.keepalive,method:i.method,mode:i.mode,redirect:i.redirect,referrer:i.referrer,referrerPolicy:i.referrerPolicy,signal:i.signal}):new Request(e.url,i)}return e.url}function ao(e){return!(e instanceof Response)||e.status!==402?0:jt(e.headers.get(H.wwwAuthenticate))}function oo(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 pe(r)}}function so(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}const co={[z.id]:z,[re.id]:re};function lo(e,t={}){return u(e.url,{fetchFn:e.fetch,fetchOptions:{headers:so(e)},...t})}function uo(r){let{chain:i,getClient:a,remoteFeePayer:o,rpcUrl:s}=r;return a?!i?.serializers&&!o&&!r.requireChain?a:async e=>{let s=await a(e);if(r.requireChain&&(s.chain?.id===void 0||s.chain.id!==e.chainId))throw Error(`Subscription chain mismatch: expected ${e.chainId}, got ${s.chain?.id??`unknown`}.`);let c=s;if(o&&s.transport.key!==`feePayer`){let e=s.request.bind(s),r=fe(n({request:t=>e(t)},{retryCount:0}),lo(o,{retryCount:s.transport.retryCount}))({account:s.account,chain:s.chain,pollingInterval:s.pollingInterval,retryCount:0}),i=t({...r.config,retryCount:0},r.value);c=Object.assign({},s,{request:i.request,transport:{...i.config,...i.value}})}return!i?.serializers||c.chain?.serializers?.transaction?c:Object.assign({},c,{chain:{...i,...e.chainId===void 0?{}:{id:e.chainId},...c.chain,formatters:c.chain?.formatters??i.formatters,prepareTransactionRequest:c.chain?.prepareTransactionRequest??i.prepareTransactionRequest,serializers:c.chain?.serializers?.transaction?c.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?fe(u(r),lo(o)):u(r);return e({chain:co[n]??{...i,id:n},transport:a})}}function fo(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 po(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}const mo=j.slice(A.keccak256(k.fromString(`mpp`),{as:`Hex`}),0,4);function ho(e){let t=A.keccak256(k.fromString(e),{as:`Hex`});return j.toBytes(j.slice(t,0,10))}function go(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(j.toBytes(mo),0),i[4]=1,i.set(ho(t),5),n&&i.set(ho(n),15),i.set(_o(r),25),j.fromBytes(i)}function _o(e){let t=A.keccak256(k.fromString(e),{as:`Hex`});return j.toBytes(j.slice(t,0,7))}function vo(e,t){return ve.resolve(e).toLowerCase()===ve.resolve(t).toLowerCase()}const yo=10000n,bo=[yr.pathUsd,yr.usdc,yr.ousd];async function xo(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t;if(!Number.isFinite(o)||o<0||o>50)throw Error(`Auto-swap slippage must be between 0 and 50 percent.`);if(t.maxAmountIn!==void 0&&t.maxAmountIn<=0n)throw Error(`Auto-swap maxAmountIn must be positive.`);let s=e.chain?.id,c=[];for(let e of a){let t=typeof e==`string`?e:s===void 0?void 0:Oe(e,{chainId:s})?.address;!t||vo(t,i)||c.some(e=>vo(e,t))||c.push(t)}let l=await Promise.allSettled([x(e,{...B.token.getBalance.call(e,{account:n,token:i}),account:null}),...c.map(t=>x(e,{...B.token.getBalance.call(e,{account:n,token:t}),account:null}))]),u=l[0];if(u.status!==`fulfilled`)throw u.reason;let d=u.value;if(d>=r)return;let f=r-d,p=BigInt(Math.round(o*100)),m=t.maxAmountIn??f+f*p/yo;for(let t=0;t<c.length;t++){let n=l[t+1];if(n.status!==`fulfilled`)continue;let r=n.value;if(r<=0n)continue;let a=c[t];try{let t=await B.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:f});if(t<=0n||t>m)continue;let n=t+t*p/yo,o=n<m?n:m;if(r>=o)return[B.token.approve.call(e,{amount:o,spender:le.stablecoinDex,token:a}),B.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:f,maxAmountIn:o})]}catch{}}throw new Co({currency:i})}function So(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...e.fallback===!1?[]:t.filter(t=>!e.tokenIn.some(e=>typeof e==`string`&&vo(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var Co=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}};function wo(e){let t=BigInt(e.amount),n=e.methodDetails?.splits??[],r=n.reduce((e,t)=>e+BigInt(t.amount),0n);if(r>=t)throw Error(`Invalid charge request: split total must be less than total amount.`);let i=t-r;if(i<=0n)throw Error(`Invalid charge request: primary transfer amount must be positive.`);return[{amount:i.toString(),memo:e.methodDetails?.memo,recipient:e.recipient},...n.map(e=>({amount:BigInt(e.amount).toString(),memo:e.memo,recipient:e.recipient}))]}function To(e,t,n){t&&(n&&!n.some(e=>vo(e,t))||e.some(e=>vo(e,t))||e.push(t))}async function Eo(e,t,n){try{return(await B.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function Do(e){let t=e.chain?.feeToken;if(t)return ue.toAddress(t);let n=e.chain?.id;return n?br[n]:void 0}function Oo(e){let t=[];return To(t,yr.pathUsd),To(t,br[e]),t}async function ko(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])To(o,e,n);if(To(o,await B.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),To(o,Do(i),n),!a)for(let e of r??[])To(o,e,n);for(let e of o)if(await Eo(i,t,e))return e;return o[0]}const Ao=m([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]);function jo(e){if(e!==void 0)return xr[e]}function Mo(e){let t=jo(e.chainId);return!!t&&d(e.currency,{strict:!1})&&f(e.currency,t.token)}function No(e){let t=jo(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let r=BigInt(n.amount),a=n.memo;return{calls:[{data:i({abi:se.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:i({abi:Ao,functionName:`swapTo`,args:[t.token,r,e.currency,n.recipient,a]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:r,memo:a,recipient:n.recipient}]}}async function Po(e,t){let n=No(t);if(n)try{return await x(e,B.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await _(e,{account:t.account,calls:n.calls}),n)}catch{return}}const Fo=10n**BigInt(4);function Io(e={}){let{address:t,amount:n,chainId:r=Z.mainnet}=e;if(r!==Z.mainnet)return;let i=new URL(`https://wallet.tempo.xyz/agent?action=fund&intent=mach&chainId=4217`);if(t&&d(t,{strict:!1})&&i.searchParams.set(`address`,c(t)),n!==void 0&&n>0n){let e=(n+Fo-1n)/Fo,t=e%100n,r=(e/100n).toString();i.searchParams.set(`amount`,t===0n?r:`${r}.${t.toString().padStart(2,`0`).replace(/0$/,``)}`)}return i.toString()}async function Lo(e,t){let n=jo(t.chainId);if(!n)return;let r=await x(e,B.token.getBalance.call(e,{account:t.account,token:n.token})).catch(()=>void 0);return typeof r==`bigint`?r:void 0}async function Ro(e,t){let{account:n,amount:r,chainId:i}=t,a=await Lo(e,{account:n,chainId:i});if(a===void 0||a>=r)return;let s=e=>`${o(e,6)} MACH`,c=r-a;return{fundingUrl:Io({address:n,amount:c,chainId:i}),reason:`requested ${s(r)}, available ${s(a)}`,shortfall:c}}async function zo(e,t){let n=await Ro(e,t);if(n)return new ln({fundingUrl:n.fundingUrl,reason:n.reason})}const Bo={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]};function Vo(e){return{name:`MPP`,version:`3`,chainId:e}}function Ho(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function Uo(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:Vo(n),types:Bo,primaryType:`Proof`,message:Ho({account:t,challengeId:r,realm:i})}}function Wo(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const Go=[...se.accountKeychain.filter(e=>e.type===`error`),...se.tip20.filter(e=>e.type===`error`)];function Ko(e){let t=new Set,n=e;for(;typeof n==`object`&&n&&!t.has(n);){t.add(n);let e=n.data;if(Yo(e))return e;let r=e?.data;if(Yo(r))return r;n=n.cause}}function qo(e,t){let n=Ko(e);if(!n)return;let i=(()=>{try{return r({abi:Go,data:n})}catch{return}})();if(i?.errorName===`SpendingLimitExceeded`){let n=t.account.accessKeyAddress;return new sn({accessKey:typeof n==`string`?n:void 0,account:t.account.address,cause:e})}if(i?.errorName===`InsufficientBalance`){let[n,r,a]=i.args;return new ln({cause:e,reason:`${t.account.address} holds ${n} of token ${a}, but the payment requires ${r}`})}}async function Jo(e,t){try{return await t()}catch(t){throw qo(t,e)??t}}function Yo(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{8}/.test(e)}const Xo=7200n,Zo=64n,Qo=s({abi:se.zonePortal,name:`WithdrawalProcessed`});function $o(e){return Number.isInteger(e)&&e>0&&e<4217e5}function es(e,t){return $o(t)?e===!0||(e?.includes(t)??!1):!1}function ts(e){return le.zonePortal(e)}ts(0).slice(0,-16).toLowerCase();function ns(e){if(e>=2**32)return e%2**32;if(e>142431e4&&e<142432e4)return e-142431e4;if(e>4217e5&&e<42171e4)return e-4217e5;throw Error(`Cannot derive a Zone ID from chain ID ${e}. Pass \`zoneId\`.`)}function rs(e){if(e>=2**32)return Math.floor(e/2**32);if(e>142431e4&&e<142432e4)return 42431;if(e>4217e5&&e<42171e4)return 4217}function is(e){return A.keccak256(D.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function as(e,t){let{blockNumber:n,sender:r,transactionHash:i}=t,a=t=>x(e,{abi:se.zoneOutbox,address:le.zoneOutbox,blockNumber:t,functionName:`lastFallbackNonce`}),[o,s]=await Promise.all([a(n-1n),a(n)]);if(s<=o)throw Error(`Zone withdrawal transaction ${i} did not request a withdrawal from the outbox.`);if(s-o>Zo)throw Error(`Zone withdrawal transaction ${i} has ${s-o} candidate sender tags, more than ${Zo}.`);let c=[];for(let e=o+1n;e<=s;e++)c.push(is({fallbackNonce:e,sender:r,transactionHash:i}));return c}async function os(e,t){let{senderTags:n,timeoutMs:r=6e4}=t;if(!Number.isFinite(r)||r<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);if(n.length===0)throw Error(`Zone settlement needs at least one sender tag.`);let i=await v(e,{cacheTime:0}),a=i>Xo?i-Xo:0n,o=Date.now()+r;for(;;){if(a<=i){let[r]=await y(e,{address:t.portal,event:Qo,args:{senderTag:[...n],...t.to?{to:t.to}:{}},fromBlock:a,toBlock:i});if(r?.transactionHash&&r.args.senderTag)return{hash:r.transactionHash,senderTag:r.args.senderTag};a=i+1n}if(Date.now()+500>o)throw Error(`Zone withdrawal ${n.join(` or `)} did not settle on Tempo within ${r}ms.`);await new Promise(e=>setTimeout(e,500)),i=await v(e,{cacheTime:0})}}const ss=[`push`,`pull`],cs=W.object({amount:G(),memo:W.optional(q()),recipient:W.pipe(W.string(),W.transform(e=>e))}),ls=(1n<<64n)-1n,us={dev_second:1n,day:86400n,week:604800n},ds=W.pipe(K(),W.transform(e=>e.toLowerCase())),fs=W.object({accessKeyAddress:ds,keyType:W.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:W.optional(W.pipe(W.string().check(W.regex(/^0x[0-9a-fA-F]{120}$/)),W.transform(e=>e)))}),ps=W.object({accessKey:W.optional(fs),chainId:W.optional(W.number())}),ms=ct(`subscriptionExpires must be a valid date`).check(W.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),hs=W.enum([`dev_second`,`day`,`week`]),gs=W.pipe(W.union([W.string(),W.bigint(),W.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),W.transform(e=>e.toString())).check(W.regex(/^[1-9]\d*$/,`Invalid periodCount`),W.refine(e=>{try{return BigInt(e)<=ls}catch{return!1}},`periodCount exceeds uint64`));function _s(e){return W.refine(e=>{let{amount:t,decimals:n}=e;return g(t,n)>0n},e)}function vs(e){let{periodCount:t,periodUnit:n}=e;try{let e=us[n];return e!==void 0&&BigInt(t)*e<=ls}catch{return!1}}const ys=fn({name:`tempo`,intent:`charge`,schema:{credential:{payload:W.discriminatedUnion(`type`,[W.object({hash:q(),type:W.literal(`hash`)}),W.object({signature:J(),type:W.literal(`transaction`)}),W.object({signature:J(),type:W.literal(`proof`)}),W.object({hash:q(),senderTag:q(),type:W.literal(`zone`),zoneId:W.number().check(W.refine($o,`Invalid Zone ID`))})])},request:W.pipe(W.object({machineTokenEnabled:W.optional(W.boolean()),amount:G(),chainId:W.optional(W.number()),currency:W.string(),decimals:W.number(),description:W.optional(W.string()),externalId:W.optional(W.string()),feePayer:W.optional(W.pipe(W.union([W.boolean(),W.custom()]),W.transform(e=>typeof e==`object`||e))),memo:W.optional(W.never()),recipient:W.optional(W.string()),splits:W.optional(W.array(cs).check(W.minLength(1),W.maxLength(10))),supportedModes:W.optional(W.array(W.enum(ss)).check(W.minLength(1))),zones:W.optional(W.union([W.literal(!0),W.array(W.number().check(W.refine($o,`Invalid Zone ID`))).check(W.minLength(1))]))}).check(W.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=g(e,t),i=n.reduce((e,n)=>e+g(n.amount,t),0n);return n.every(e=>g(e.amount,t)>0n)&&i<r},`Invalid splits`)),W.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,zones:c,...l})=>({...l,amount:g(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0||c!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:g(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),bs=fn({name:`tempo`,intent:`session`,schema:{credential:{payload:W.discriminatedUnion(`action`,[W.object({action:W.literal(`open`),authorizedSigner:W.optional(W.string()),channelId:q(),cumulativeAmount:G(),descriptor:W.optional(W.custom()),signature:J(),transaction:J(),type:W.literal(`transaction`)}),W.object({action:W.literal(`topUp`),additionalDeposit:G(),channelId:q(),descriptor:W.optional(W.custom()),transaction:J(),type:W.literal(`transaction`)}),W.object({action:W.literal(`voucher`),channelId:q(),cumulativeAmount:G(),descriptor:W.optional(W.custom()),signature:J()}),W.object({action:W.literal(`close`),channelId:q(),closeSignature:J(),cumulativeAmount:G(),descriptor:W.optional(W.custom()),signature:J()})])},request:W.pipe(W.object({amount:G(),chainId:W.optional(W.number()),channelId:W.optional(q()),configurableVouchers:W.optional(W.boolean()),currency:W.string(),decimals:W.number(),escrowContract:W.optional(W.string()),feePayer:W.optional(W.pipe(W.union([W.boolean(),W.custom()]),W.transform(e=>typeof e==`object`||e))),feeToken:W.optional(K()),minVoucherDelta:W.optional(G()),operator:W.optional(K()),recipient:W.optional(W.string()),sessionProtocol:W.optional(W.enum([rt.v2,rt.v1])),sessionSnapshot:W.optional(W.custom()),suggestedDeposit:W.optional(G()),unitType:W.string()}).check(W.refine(({amount:e,decimals:t})=>g(e,t)>0n,`Session amount must be greater than 0`)),W.transform(({amount:e,chainId:t,channelId:n,configurableVouchers:r,decimals:i,escrowContract:a,feePayer:o,feeToken:s,minVoucherDelta:c,operator:l,sessionProtocol:u,sessionSnapshot:d,suggestedDeposit:f,...p})=>({...p,amount:g(e,i).toString(),...f?{suggestedDeposit:g(f,i).toString()}:{},methodDetails:{escrowContract:a,...n!==void 0&&{channelId:n},...c!==void 0&&{minVoucherDelta:g(c,i).toString()},...t!==void 0&&{chainId:t},...o!==void 0&&{feePayer:o},...s!==void 0&&{feeToken:s},...l!==void 0&&{operator:l},...r!==void 0&&{configurableVouchers:r},...u!==void 0&&{[nt.sessionProtocol]:u},...d!==void 0&&{[nt.sessionSnapshot]:d}}})))}}),xs=fn({name:`tempo`,intent:`subscription`,schema:{credential:{payload:W.object({signature:J(),type:W.literal(`keyAuthorization`)})},request:W.pipe(W.object({amount:G(),accessKey:W.optional(fs),chainId:W.optional(W.number()),currency:ds,decimals:W.number(),description:W.optional(W.string()),externalId:W.optional(W.string()),methodDetails:W.optional(ps),periodCount:gs,periodUnit:hs,recipient:ds,subscriptionExpires:ms}).check(_s(`Subscription amount must be greater than 0`),W.refine(vs,`Subscription period exceeds uint64`)),W.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:g(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}}),Ss=W.object({account:W.optional(W.custom()),autoSwap:W.optional(W.custom()),feeToken:W.optional(W.custom()),mode:W.optional(W.enum(ss))});function Cs(e={}){let{clientId:t}=e;if((e.maxAmount!==void 0||e.maxAtomicAmount!==void 0)&&e.currencies===void 0)throw Error(`Tempo charge maxAmount and maxAtomicAmount require currencies.`);for(let t of e.currencies??[])zs(e.maxAmount,typeof t==`string`?e.decimals:t.decimals);let n={maxAmount:e.maxAmount,maxAtomicAmount:e.maxAtomicAmount===void 0?void 0:BigInt(e.maxAtomicAmount)},r=uo({chain:z,getClient:e.getClient,rpcUrl:Sr}),i=oo({account:e.account});js(e.zone);let a=new Map,o=pn(ys,{canHandleChallenge({challenge:t}){try{return Bs(e,n,t.request),!0}catch{return!1}},context:Ss,async createCredential(o){let{challenge:s,context:c}=o;Bs(e,n,s.request);let l=s.request.methodDetails?.chainId,u=l??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),d=await r({chainId:u});fo(d,u);let f=u??d.chain?.id;if(po(e.allowedChainIds,f),f===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");l===void 0&&Bs(e,n,s.request,f);let{request:p}=s,{amount:m,methodDetails:h}=p,g=h?.supportedModes??[`pull`,`push`],_=e.zone?.client.chain,v=e.zone?e.zone.zoneId??ns(_?.id??0):void 0,y=_?.sourceId??(_?rs(_.id):void 0),x=c?.mode??e.mode;if(BigInt(m)>0n&&e.zone&&v!==void 0&&y===f&&g.includes(`push`)&&(x===void 0||x===`push`)&&es(h?.zones,v)&&!h?.splits){let r={assertFee:t=>Bs(e,n,p,f,t),challenge:s,clientId:t,client:d,origin:As(sa(o)),pending:a,zone:e.zone,zoneId:v},i=Ds(r);if(i)return Os(r,i);if(s.expires&&un(s.expires,s.id),Ms(s.expires,e.zone.settlementTimeoutMs))return Es(r)}let C=i(d,c),ee=async t=>await e.resolveAccount?.({account:C,chainId:f,operation:t})??C;if(BigInt(m)===0n){let e=await ee({kind:`signPaymentProof`});return Jt({challenge:s,payload:{signature:await E(d,{account:e,...Uo({account:e.address,chainId:f,challengeId:s.id,realm:s.realm})}),type:`proof`},source:Wo({address:e.address,chainId:f})})}let te=p.currency,ne=Mo({chainId:f,currency:te}),D=go({challengeId:s.id,clientId:t,serverId:s.realm}),O=wo({amount:m,methodDetails:{...h,memo:D},recipient:p.recipient}),k=O.map(e=>B.token.transfer.call(d,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:te})),A=So(c?.autoSwap??e.autoSwap,bo),j=h?.machineTokenEnabled===!0?No({chainId:f,currency:te,transfers:O}):void 0,M=C,N,P=!1;if(j){let e=await(async()=>{try{return await ee({calls:j.calls,kind:`executeCalls`})}catch{return}})();e&&(N=await Po(d,{account:e.address,chainId:f,currency:te,transfers:O}),N?M=e:P=!0)}let F;if(!N&&(M=await ee({kind:`executeCalls`,...A?{}:{calls:k}}),F=A?await xo(d,{account:M.address,amountOut:BigInt(m),tokenOut:te,tokenIn:A.tokenIn,slippage:A.slippage,maxAmountIn:A.maxAmountIn}):void 0,P&&!A)){let e=await ws(d,{account:M.address,amount:BigInt(m),chainId:f,currency:te});if(e)throw e}let I=N?.calls??[...F??[],...k],L=Oo(f),R=(c?.feeToken??e.feeToken)||(N||ne?await ko({account:M.address,allowedTokens:L,candidateTokens:L,client:d,prioritizeCandidates:!0}):void 0),z=(()=>{let t=c?.mode??e.mode;if(t){if(!g.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=M.type===`json-rpc`?`push`:`pull`;return g.includes(n)?n:g[0]})(),re=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!s.expires)return e;let t=Math.floor(new Date(s.expires).getTime()/1e3)+1;return Math.min(e,t)})();if(z===`push`){let{receipts:e}=M.type===`local`?{receipts:[await Jo({account:M},()=>w(d,{account:M,calls:I,...R?{feeToken:R}:{},nonceKey:`expiring`,validBefore:re}))]}:await S(d,{account:M,...R?{capabilities:{feeToken:R}}:{},calls:I,experimental_fallback:I.length===1,forceAtomic:I.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return Jt({challenge:s,payload:{hash:t,type:`hash`},source:Wo({address:M.address,chainId:f})})}let ie=()=>{if(h?.feePayer!==!0)return;let e=15e3,t=s.expires?new Date(s.expires).getTime():1/0,n=Date.now();if(!(t-n>=e))throw Error(`Sponsored challenge expires in less than 15 seconds; the fee payer would reject the transaction. Request a new challenge.`);if(!(re*1e3-n>=e))throw Error(`Sponsored transaction preparation took too long: less than 15 seconds of its validity window remain, so the fee payer would reject it.`)};ie();let ae=await Jo({account:M},()=>b(d,{account:M,calls:I,...R?{feeToken:R}:{},nonceKey:`expiring`,validBefore:re}));if(ae.gas=(ae.gas??0n)+5000n,h?.feePayer){let e=ae;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return ie(),Jt({challenge:s,payload:{signature:await T(d,ae),type:`transaction`},source:Wo({address:M.address,chainId:f})})}}),s=new Map,c=async t=>{Bs(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,a=s.get(i);return a||(a=o.createCredential(t).finally(()=>s.delete(i)),s.set(i,a)),a};return ia({...o,createCredential:c},Ts)}async function ws(e,t){let{account:n,amount:r,chainId:i,currency:a}=t,o=await x(e,B.token.getBalance.call(e,{account:n,token:a})).catch(()=>void 0);if(!(typeof o!=`bigint`||o>=r))return zo(e,{account:n,amount:r,chainId:i})}function Ts(e){let t=ys.schema.credential.payload.safeParse(Wt(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`||n.type===`zone`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(ye.serializedType))return;let i=ye.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&ye.serialize(i)===r)return p(r)}function Es(e){let{challenge:t,origin:n,pending:r,zoneId:i}=e,a={sent:!1},o={challenge:t,origin:n,terms:Fs(t,i),waiters:0,withdrawal:Rs(e,a)},s=Ps(t);return r.set(s,o),o.withdrawal.catch(()=>{!a.sent&&r.get(s)===o&&r.delete(s)}),Os(e,o)}function Ds(e){let{challenge:t,pending:n,zoneId:r}=e,i=n.get(Ps(t));if(i)return i;let a=Fs(t,r);if(a!==void 0){for(let[e,t]of n)if(t.terms===a){if(!Ls(t.challenge.expires)){n.delete(e);continue}if(t.redeemedLate)throw new cn({challengeId:t.challenge.id,senderTags:t.senderTags,zoneId:r});if(!(t.waiters>0))return t}}}async function Os(e,t){t.waiters++;try{return await ks(e,t)}finally{t.waiters--}}async function ks(e,t){let{client:n,origin:r,pending:i,zone:a,zoneId:o}=e,{challenge:s}=t,c=s.request.recipient,l=Ps(s);if((l===Ps(e.challenge)?r!==void 0&&t.origin!==void 0&&r!==t.origin:!r||r!==t.origin)||!Ls(s.expires))throw new cn({challengeId:s.id,zoneId:o});let u=await t.withdrawal,d=u.senderTags??await as(a.client,u).catch(e=>{let t=Error(`Zone withdrawal transaction ${u.transactionHash} was sent, but its sender tag could not be read from the Zone. Retry the challenge to resume without withdrawing again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),t}),f;try{f=await os(n,{portal:ts(o),senderTags:d,timeoutMs:Ns(s.expires,a.settlementTimeoutMs),to:c})}catch(e){throw new cn({cause:e,challengeId:s.id,senderTags:d,zoneId:o})}i.get(l)===t&&(Is(s.expires)?(t.redeemedLate=!0,t.senderTags=[f.senderTag]):i.delete(l));let{hash:p,senderTag:m}=f;return Jt({challenge:s,payload:{hash:p,senderTag:m,type:`zone`,zoneId:o}})}function As(e){if(e)try{let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`?void 0:t.origin}catch{return}}function js(e){let t=e?.settlementTimeoutMs;if(t!==void 0&&(!Number.isFinite(t)||t<0))throw Error("`zone.settlementTimeoutMs` must be a finite, non-negative number.");let n=e?.client.chain?.id;if(e?.zoneId===void 0||n===void 0||rs(n)===void 0)return;let r=ns(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function Ms(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+15e3}function Ns(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function Ps(e){return JSON.stringify(e)}function Fs(e,t){let n;try{n=e.opaque===void 0?e.meta:at(e.opaque)}catch{return}let{digest:r,intent:i,method:a,realm:o,request:s}=e;return U({digest:r,intent:i,meta:dn(n),method:a,realm:o,request:s,zoneId:t})}function Is(e){if(!e)return!1;let t=new Date(e).getTime();return!Number.isNaN(t)&&Date.now()>=t}function Ls(e){if(!e)return!0;let t=new Date(e).getTime();return Number.isNaN(t)||Date.now()<t+3e5}async function Rs(e,t){let{assertFee:n,challenge:r,clientId:i,zone:a}=e,o=r.request,s=a.client.account;if(!s)throw Error("`zone.client` requires an account.");let c=BigInt(o.amount),l=o.currency,u=o.recipient,d=go({challengeId:r.id,clientId:i,serverId:r.realm}),f=await B.zone.getWithdrawalFee(a.client);n(f);let[,m]=B.zone.requestWithdrawal.calls({amount:c,fallbackRecipient:s.address,memo:d,to:u,token:l}),g=await b(a.client,{account:s,calls:[B.token.approve.call({amount:c+f,spender:le.zoneOutbox,token:l}),m]}),_=await T(a.client,g);t.sent=!0;let v=p(_),y=await C(a.client,{serializedTransaction:_}).catch(e=>ee(a.client,{hash:v,timeout:15e3}).catch(()=>{let t=Error(`Zone withdrawal outcome is unknown: transaction ${v} may have been sent. Retrying this challenge does not withdraw again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),t}));if(y.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${y.transactionHash} reverted.`);let[x]=h({abi:se.zoneOutbox,eventName:`WithdrawalRequested`,logs:y.logs});return{blockNumber:y.blockNumber,sender:s.address,senderTags:x?[is({fallbackNonce:x.args.fallbackNonce,sender:x.args.sender,transactionHash:y.transactionHash})]:void 0,transactionHash:y.transactionHash}}function zs(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo charge maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo charge maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return g(e,t)}}function Bs(e,t,n,r,i){let{methodDetails:a,recipient:o}=n,s=a?.chainId;if(e.expectedChainId!==void 0&&s!==void 0&&s!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${s}.`);(s!==void 0||e.allowedChainIds?.length===0)&&po(e.allowedChainIds,s);let c=e.currencies?ke(e.currencies,n.currency,{chainId:s??r??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),decimals:e.decimals}):void 0;if(e.currencies&&!c)throw Error(`Tempo charge currency is not allowed: ${n.currency}.`);if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!o||!t.has(o.toLowerCase()))throw Error(`Unexpected primary recipient: ${o}`);let n=a?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}if(t.maxAtomicAmount===void 0&&t.maxAmount===void 0)return;let l=BigInt(n.amount)+(i??0n),u=i===void 0?`amount exceeds`:`amount plus Zone withdrawal fee exceeds`;if(t.maxAtomicAmount!==void 0&&l>t.maxAtomicAmount)throw Error(`Tempo charge ${u} maxAtomicAmount.`);if(t.maxAmount!==void 0&&l>zs(t.maxAmount,c?.decimals))throw Error(`Tempo charge ${u} maxAmount.`)}const Vs=(1n<<96n)-1n;function Hs(e){return e>=0n&&e<=Vs}function Us(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return Hs(t)?t:void 0}function Ws(e){return Gs(e),e}function Gs(e){if(!Hs(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const Ks=new Set([`open`,`topUp`,`voucher`,`close`]);function qs(e){return typeof e==`object`&&!!e}function Js(e){return typeof e==`string`&&Ks.has(e)}function Ys(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!Js(t.action))}function Xs(e,t=`No session credential context available.`){if(!Ys(e))throw Error(t);return e}function Zs(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function Qs(e){return qs(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function $s(e){return qs(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 ec(e){let t=O.toString(e),n=JSON.parse(t);if(!$s(n))throw Error(`Invalid session receipt.`);return n}function tc(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function nc(e){let t=`message`,n=[];for(let r of e.split(`
6
+ `,i))}t=t.slice(i)}}}const ji=[U.authorization,Cn,`PAYMENT-RESPONSE`,wn];function Mi(e,t,n){let r=new Headers(e.headers);for(let e of ji)e===U.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}function Ni(e){if(typeof e==`string`)try{let t=JSON.parse(e),n=t?.id;return t?.jsonrpc!==`2.0`||typeof t?.method!=`string`?void 0:typeof n==`string`||typeof n==`number`?n:void 0}catch{return}}function Pi(e){if(typeof e?.body!=`string`)return!1;try{let t=JSON.parse(e.body);return t?.jsonrpc===`2.0`&&t?.method===`tools/call`&&t.params?._meta?.[`mppx/payment-client`]===!0}catch{return!1}}const Fi=1048576,Ii=new WeakMap;function Li(e){let t=Ni(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 Ri(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 zi(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){if(!kt.safeParse(e).success)return;if(Qt(e))continue;let t=Ot.safeParse(e);if(!t.success)return;n.push(t.data)}if(n.length===0)return;let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function Bi(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:zi(e.error.data):zi(e.result?._meta?.[`org.paymentauth/payment-required`])}function Vi(e,t){return!e||e.id!==t?[]:Bi(e)?.challenges??[]}async function Hi(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=Ai(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=Ri(JSON.parse(e.data))}catch{}});try{for(;;){if(i)return a;let{done:e,value:s}=await t.read();if(e)return o.feed(n.decode()),a;if(r+=s.byteLength,r>Fi)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function Ui(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=``;try{for(;;){let{done:e,value:a}=await t.read();if(e)return Ri(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>Fi)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function Wi(e){let t=Ii.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>Fi)){if(t.includes(`application/json`))return Ui(e);if(t.includes(`text/event-stream`))return Hi(e)}})();return Ii.set(e,n),n}function Gi(){return{getChallenges(e,t){let n=Li(t);return e.status===402||n===void 0?[]:Wi(e).then(e=>Vi(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=sn(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}function Ki(){return{getChallenges(e){let t=e.headers.get(U.wwwAuthenticate);return e.status!==402||!t||!Ht(t)?[]:Wt(e)},setCredential(e,t,n){return Mi(e,n?.challenge?Zt(n.challenge):U.authorization,t)}}}function qi(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(Cn);if(!t)return[];let n=Gn(t);return n.accepts.flatMap((e,t)=>{let r=jn.safeParse(e);if(!r.success)return[];let i=r.data;return mn(At({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 Mi(e,wn,t)}}}function Ji(e){return e}function Yi(){let e=[Ki(),qi(),Gi()],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 Ji({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 Xi=new WeakMap;function Zi(e,t){return Xi.set(e,t),e}function Qi(e){return Xi.has(e)}function $i(e,t){return Promise.resolve(Xi.get(e)?.(t))}function ea(e){return Xi.get(e)}const ta=new WeakMap,na=new WeakMap,ra=new WeakMap,ia=new WeakMap;function aa(e,t){return ta.set(e,t),e}function oa(e){ta.delete(e)}function sa(e,t,n){ta.has(e)&&na.set(t,n)}function ca(e){return na.get(e)}function la(e,t){return Promise.resolve(ta.get(e)?.(t)??t.response)}function ua(e,t){return ia.set(e,t),e}function da(e,t){try{return ia.get(e)?.(t)}catch{return}}function fa(e,t){ra.set(e,t)}function pa(e){return ra.get(e)??na.get(e)?.origin}async function ma(e,t){let{attempts:n,signal:r}=t;for(let t=1;;t++){r?.throwIfAborted();try{return await e()}catch(e){if(!(e instanceof pt)||t>=n)throw e;r?.throwIfAborted()}}}function ha(e,t,n){if(!ga(e)&&(e.method!==`tempo`||e.intent!==`session`))return;t=typeof t==`function`?t():t;let{realm:r}=e;if(r.toLowerCase()===t.hostname.toLowerCase())return;let i=t.origin.toLowerCase();for(let[e,t]of Object.entries(n??{}))if(t===r&&_a(e)===i)return;throw Error(`Refusing to sign Tempo proof for realm ${JSON.stringify(r)} from ${t.origin}. Pin the realm to this origin with \`trustedTempoProofRealms\` if this server is expected to issue it.`)}function ga(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function _a(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}const va=Symbol.for(`mppx.fetch.wrapper`),ya=Symbol.for(`mppx.fetch.identity`),ba=Symbol.for(`mppx.fetch.skipPayment`);function xa(e={}){return{...e,[ba]:!0}}const Sa=65536,Ca=new WeakMap;async function wa(e){if(!e.body)return e;let t=e.clone().body.getReader(),n=[],r=0,i=!1,a=setTimeout(()=>{i=!0,t.cancel().catch(()=>{})},2e3);try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(n.push(a),r+=a.byteLength,r>Sa){i=!0;break}}}finally{clearTimeout(a),t.cancel().catch(()=>{})}if(!i)return e;e.body.cancel().catch(()=>{});let o=new Headers(e.headers);o.delete(`content-length`),o.set(`Mppx-Body-Truncated`,`true`);let s=new Response(new Blob(n).slice(0,Sa),{headers:o,status:e.status,statusText:e.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{value:e[t]});return s}async function Ta(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 Ea(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=Yi(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&Ya(e.fetch)),d=e.eventDispatcher??Oa(),f=t??pi(a),p=Xa(r),m=async(e,t,n)=>u?u.send((e,n)=>p(e,t?.[ba]?xa(n):n),new Request(e,t),n):{response:await p(e,t),headers:[]},h=async(e,t,r)=>{let g=Ja(e,t?.headers),_=g.has(U.acceptPayment),v=no(g,f),y=Ka(e,t,g),b=Ga(e,t,g,v.header,_,n),x=await m(Za(b.input),b.init),S=x.response,C=x.headers,w=qa(b.init,await y);if(t?.[ba]||Pi(w)||!await c.isPaymentRequired(S,w))return S;let T=t?.context,{context:E,orderChallenges:ee,...D}=w??{},te,O,k,A,j;try{for(let n=0;n<i;n++){O=await c.getChallenges(S,w);let f=(await ro(gi(O,a,v.entries,T),ee??s))[0];if(!f){if(await Ta(A,{challenges:O,response:S,status:`rejected`}),n>0)return S;throw Error(Jt(`No method found for challenges: ${O.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`,fo(S)))}let g=f.challenge;te=g,k=f.method,te.expires&&gn(te.expires,te.id),await u?.challenge(S,{challenge:g},so(b.input).href);let _=await uo(S,b.input,b.input,D);ha(g,()=>so(_),l);let y=A,x=po(g),E=y?.method===f.method&&y?.key===x,M=!1;if(y){let e=await Ta(y,{challenges:O,response:S,status:E?`pending`:`rejected`});M=E&&!e}A=M?y:void 0;let N=Na(async n=>{if(n===void 0&&M&&y)return y.promise;M&&y&&(await Ta(y,{status:`rejected`}),A=void 0),Qa(e,t)?.throwIfAborted();let r=n??T;if(!Qi(f.method))return ma(()=>to(g,f.method,r,co(_)),{attempts:i,signal:Qa(e,t)});let a={origin:so(_).origin,prepare:()=>$i(f.method,{challenge:g,context:r,fetch:u?ci(p,u,{challenge:g}):p,input:_,signal:Qa(e,t)})},o=a.prepare().then(()=>to(g,f.method,r,a));return A={context:r,attempt:a,key:n===void 0?x:void 0,method:f.method,promise:o},o}),P=await d.emit(`challenge.received`,Pa({challenge:g,challenges:O,createCredential:N,init:t,input:e,method:f.method,response:S}))??(o?await o(te,{createCredential:N}):void 0)??await N(),F=A;F&&await F.promise.catch(()=>void 0)!==P&&(await Ta(F,{status:`rejected`}),A=void 0);let I=A?A.context:T;eo(P);let L=$a(P,g);await d.emit(`credential.created`,Fa({challenge:g,credential:P,init:t,input:e,method:f.method,response:S}));let R=e=>new ct({cause:e,challenge:g,credential:P,transactionHash:da(f.method,P)});try{({response:S}=await m(_,{...c.setCredential({...D,headers:b.headers},P,{challenge:g}),redirect:`manual`},{challenge:L,headers:C}))}catch(e){throw j=R(e),e}let z=await c.isPaymentRequired(S,w);if(z||(await Ta(F,{response:S,status:S.status>=300&&S.status<400?`pending`:S.ok?`accepted`:`rejected`}),A=void 0),S.ok&&ka(d,`payment.response`)&&await d.emit(`payment.response`,Ia({challenge:g,credential:P,init:t,input:e,method:f.method,response:S})),!z){if(S.status>=500&&ka(d,`payment.failed`)){try{S=await wa(S)}catch(e){throw j=R(e),S=new Response(null,{headers:S.headers,status:S.status,statusText:S.statusText}),e}await d.emit(`payment.failed`,La({challenge:g,challenges:O,error:R(),init:t,input:e,method:f.method,response:S}))}return S.ok?la(f.method,{context:I,challenge:g,credential:P,fetch:p,headers:b.headers,input:_,...r?{refetch:()=>h(Za(b.input),t,!1)}:{},response:S,signal:Qa(e,t)}):S}}O=void 0;try{O=await c.getChallenges(S,w)}catch{}return await Ta(A,{challenges:O,response:S,status:`rejected`}),S}catch(n){throw await Ta(A,{challenges:O,response:S,status:`rejected`}),await d.emit(`payment.failed`,La({challenge:te,challenges:O,error:j??n,init:t,input:e,method:k,response:S})),n}},g=(e,t)=>h(e,t,!0);return g[va]=p,u&&(g[ya]=u),g}function Da(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 Oa(){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 Aa(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await Ma(e[`*`],t,n),r}case`credential.created`:await ja(e[`credential.created`],n),await Ma(e[`*`],t,n);return;case`payment.failed`:await ja(e[`payment.failed`],n),await Ma(e[`*`],t,n);return;case`payment.response`:await ja(e[`payment.response`],n),await Ma(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 Ca.set(t,t=>e[t].size>0||e[`*`].size>0),t}function ka(e,t){return Ca.get(e)?.(t)??!0}async function Aa(e,t){try{return await e(t)}catch{return}}async function ja(e,t){for(let n of e)try{await n(t)}catch{}}async function Ma(e,t,n){await ja(e,Object.freeze({name:t,payload:n}))}function Na(e){let t;return n=>(t??=e(n),t)}function Pa(e){return Object.freeze({challenge:Ha(e.challenge),challenges:e.challenges.map(e=>Ha(e)),createCredential:e.createCredential,init:Ra(e.init),input:za(e.input),method:Ba(e.method),response:Va(e.response)})}function Fa(e){return Object.freeze({challenge:Ha(e.challenge),credential:e.credential,init:Ra(e.init),input:za(e.input),method:Ba(e.method),...e.response===void 0?{}:{response:Va(e.response)}})}function Ia(e){return Object.freeze({challenge:Ha(e.challenge),credential:e.credential,init:Ra(e.init),input:za(e.input),method:Ba(e.method),response:Va(e.response)})}function La(e){return Object.freeze({...e.challenge?{challenge:Ha(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>Ha(e))}:{},error:e.error,init:Ra(e.init),input:za(e.input),...e.method?{method:Ba(e.method)}:{},...e.response===void 0?{}:{response:Va(e.response)}})}function Ra(e){if(e)return Wa({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function za(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function Ba(e){return Wa(Object.assign({},e))}function Va(e){if(e instanceof Response)try{return e.clone()}catch{let t=new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText});for(let n of[`redirected`,`type`,`url`])Object.defineProperty(t,n,{value:e[n]});return t}return Ha(e)}function Ha(e){try{return Ua(structuredClone(e))}catch{return Wa(e)}}function Ua(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Ua(t);return e}function Wa(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function Ga(e,t,n,r,i,a){let o=!!r&&!i&&io(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(U.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function Ka(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 qa(e,t){return t===void 0?e:{...e,body:t}}function Ja(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function Ya(e){return e[ya]}function Xa(e){let t=e;for(;t[va];)t=t[va];return t}function Za(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function Qa(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function $a(e,t){try{let{challenge:n}=sn(e);return n.id===t.id?t:{...n,...t.header!==void 0&&{header:t.header}}}catch{return t}}function eo(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
7
+ `))throw Error(`Credential header value contains illegal newline characters`)}async function to(e,t,n,r){let i=t.context&&n!==void 0?t.context.parse(n):void 0,a=i===void 0?{challenge:e}:{challenge:e,context:i};return r?.origin&&fa(a,r.origin),r&&`prepare`in r&&sa(t,a,r),t.createCredential(a)}function no(e,t){let n=e.get(U.acceptPayment);if(!n)return t;try{return{...t,entries:mi(n),header:n}}catch{return t}}async function ro(e,t){return t?t(e):e}function io(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=so(e);return t===`same-origin`?!oo()||n.origin===globalThis.location.origin:t.origins.some(e=>ao(n,e))}function ao(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 oo(){return globalThis.location!==void 0}function so(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,oo()?globalThis.location.href:void 0)}function co(e){try{return{origin:so(e).origin}}catch{return}}function lo(e,t){let n=e instanceof Request?e:void 0;if((t.mode??n?.mode)===`no-cors`)throw Error(`Cannot automatically pay a no-cors request: it cannot carry a credential.`);if((t.cache??n?.cache)===`only-if-cached`)throw Error(`Cannot automatically pay an only-if-cached request: its retry cannot reach the server.`)}async function uo(e,t,n,r){if(lo(t,r),!e.url)return t;let i=new URL(e.url),a=so(n);if(i.origin!==a.origin)throw Error(`Refusing to send payment credential across redirect from ${a.origin} to ${i.origin}`);let o=(r.method??(t instanceof Request?t.method:`GET`)).toUpperCase();if(e.redirected&&o!==`GET`&&o!==`HEAD`)throw Error(`Cannot automatically pay a redirected ${o} request. Use prepareRequest() to preserve redirect semantics.`);if(t instanceof Request){let n=r.body==null?t.clone():t,i=new Request(n,t.mode===`navigate`&&r.mode===void 0?{...r,mode:`same-origin`}:r);return i.url.split(`#`)[0]===e.url?i:i.body?new Request(e.url,{body:await i.arrayBuffer(),cache:i.cache,credentials:i.credentials,headers:i.headers,integrity:i.integrity,keepalive:i.keepalive,method:i.method,mode:i.mode,redirect:i.redirect,referrer:i.referrer,referrerPolicy:i.referrerPolicy,signal:i.signal}):new Request(e.url,i)}return e.url}function fo(e){return!(e instanceof Response)||e.status!==402?0:qt(e.headers.get(U.wwwAuthenticate))}function po(e){let{description:t,...n}=e;return N.canonicalize(n)}function mo(e={}){let{account:t}=e;return(e,{account:n}={})=>{let r=n??t;if(!r){if(!e.account)throw Error("No `account` provided. Pass `account` to parameters or context.");return e.account}return fe(r)}}function ho(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}const go={[B.id]:B,[ne.id]:ne};function _o(e,t={}){return u(e.url,{fetchFn:e.fetch,fetchOptions:{headers:ho(e)},...t})}function vo(r){let{chain:i,getClient:a,remoteFeePayer:o,rpcUrl:s}=r;return a?!i?.serializers&&!o&&!r.requireChain?a:async e=>{let s=await a(e);if(r.requireChain&&(s.chain?.id===void 0||s.chain.id!==e.chainId))throw Error(`Subscription chain mismatch: expected ${e.chainId}, got ${s.chain?.id??`unknown`}.`);let c=s;if(o&&s.transport.key!==`feePayer`){let e=s.request.bind(s),r=de(n({request:t=>e(t)},{retryCount:0}),_o(o,{retryCount:s.transport.retryCount}))({account:s.account,chain:s.chain,pollingInterval:s.pollingInterval,retryCount:0}),i=t({...r.config,retryCount:0},r.value);c=Object.assign({},s,{request:i.request,transport:{...i.config,...i.value}})}return!i?.serializers||c.chain?.serializers?.transaction?c:Object.assign({},c,{chain:{...i,...e.chainId===void 0?{}:{id:e.chainId},...c.chain,formatters:c.chain?.formatters??i.formatters,prepareTransactionRequest:c.chain?.prepareTransactionRequest??i.prepareTransactionRequest,serializers:c.chain?.serializers?.transaction?c.chain.serializers:i.serializers}})}:({chainId:t})=>{if(!s)throw Error("No `rpcUrl` provided.");let n=t||Number(Object.keys(s)[0]),r=s[n];if(!r)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let a=o?de(u(r),_o(o)):u(r);return e({chain:go[n]??{...i,id:n},transport:a})}}function yo(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 bo(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}const xo=M.slice(j.keccak256(A.fromString(`mpp`),{as:`Hex`}),0,4);function So(e){let t=j.keccak256(A.fromString(e),{as:`Hex`});return M.toBytes(M.slice(t,0,10))}function Co(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(M.toBytes(xo),0),i[4]=1,i.set(So(t),5),n&&i.set(So(n),15),i.set(wo(r),25),M.fromBytes(i)}function wo(e){let t=j.keccak256(A.fromString(e),{as:`Hex`});return M.toBytes(M.slice(t,0,7))}function To(e,t){return _e.resolve(e).toLowerCase()===_e.resolve(t).toLowerCase()}const Eo=10000n,Do=[Tr.pathUsd,Tr.usdc,Tr.ousd];async function Oo(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t;if(!Number.isFinite(o)||o<0||o>50)throw Error(`Auto-swap slippage must be between 0 and 50 percent.`);if(t.maxAmountIn!==void 0&&t.maxAmountIn<=0n)throw Error(`Auto-swap maxAmountIn must be positive.`);let s=e.chain?.id,c=[];for(let e of a){let t=typeof e==`string`?e:s===void 0?void 0:De(e,{chainId:s})?.address;!t||To(t,i)||c.some(e=>To(e,t))||c.push(t)}let l=await Promise.allSettled([x(e,{...V.token.getBalance.call(e,{account:n,token:i}),account:null}),...c.map(t=>x(e,{...V.token.getBalance.call(e,{account:n,token:t}),account:null}))]),u=l[0];if(u.status!==`fulfilled`)throw u.reason;let d=u.value;if(d>=r)return;let f=r-d,p=BigInt(Math.round(o*100)),m=t.maxAmountIn??f+f*p/Eo;for(let t=0;t<c.length;t++){let n=l[t+1];if(n.status!==`fulfilled`)continue;let r=n.value;if(r<=0n)continue;let a=c[t];try{let t=await V.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:f});if(t<=0n||t>m)continue;let n=t+t*p/Eo,o=n<m?n:m;if(r>=o)return[V.token.approve.call(e,{amount:o,spender:ce.stablecoinDex,token:a}),V.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:f,maxAmountIn:o})]}catch{}}throw new Ao({currency:i})}function ko(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...e.fallback===!1?[]:t.filter(t=>!e.tokenIn.some(e=>typeof e==`string`&&To(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var Ao=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}};function jo(e){let t=BigInt(e.amount),n=e.methodDetails?.splits??[],r=n.reduce((e,t)=>e+BigInt(t.amount),0n);if(r>=t)throw Error(`Invalid charge request: split total must be less than total amount.`);let i=t-r;if(i<=0n)throw Error(`Invalid charge request: primary transfer amount must be positive.`);return[{amount:i.toString(),memo:e.methodDetails?.memo,recipient:e.recipient},...n.map(e=>({amount:BigInt(e.amount).toString(),memo:e.memo,recipient:e.recipient}))]}function Mo(e,t,n){t&&(n&&!n.some(e=>To(e,t))||e.some(e=>To(e,t))||e.push(t))}async function No(e,t,n){try{return(await V.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function Po(e){let t=e.chain?.feeToken;if(t)return le.toAddress(t);let n=e.chain?.id;return n?Er[n]:void 0}function Fo(e){let t=[];return Mo(t,Tr.pathUsd),Mo(t,Er[e]),t}async function Io(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])Mo(o,e,n);if(Mo(o,await V.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),Mo(o,Po(i),n),!a)for(let e of r??[])Mo(o,e,n);for(let e of o)if(await No(i,t,e))return e;return o[0]}const Lo=m([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]);function Ro(e){if(e!==void 0)return Dr[e]}function zo(e){let t=Ro(e.chainId);return!!t&&d(e.currency,{strict:!1})&&f(e.currency,t.token)}function Bo(e){let t=Ro(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let r=BigInt(n.amount),a=n.memo;return{calls:[{data:i({abi:oe.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:i({abi:Lo,functionName:`swapTo`,args:[t.token,r,e.currency,n.recipient,a]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:r,memo:a,recipient:n.recipient}]}}async function Vo(e,t){let n=Bo(t);if(n)try{return await x(e,V.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await _(e,{account:t.account,calls:n.calls}),n)}catch{return}}const Ho=10n**BigInt(4);function Uo(e={}){let{address:t,amount:n,chainId:r=Z.mainnet}=e;if(r!==Z.mainnet)return;let i=new URL(`https://wallet.tempo.xyz/agent?action=fund&intent=mach&chainId=4217`);if(t&&d(t,{strict:!1})&&i.searchParams.set(`address`,c(t)),n!==void 0&&n>0n){let e=(n+Ho-1n)/Ho,t=e%100n,r=(e/100n).toString();i.searchParams.set(`amount`,t===0n?r:`${r}.${t.toString().padStart(2,`0`).replace(/0$/,``)}`)}return i.toString()}async function Wo(e,t){let n=Ro(t.chainId);if(!n)return;let r=await x(e,V.token.getBalance.call(e,{account:t.account,token:n.token})).catch(()=>void 0);return typeof r==`bigint`?r:void 0}async function Go(e,t){let{account:n,amount:r,chainId:i}=t,a=await Wo(e,{account:n,chainId:i});if(a===void 0||a>=r)return;let s=e=>`${o(e,6)} MACH`,c=r-a;return{fundingUrl:Uo({address:n,amount:c,chainId:i}),reason:`requested ${s(r)}, available ${s(a)}`,shortfall:c}}async function Ko(e,t){let n=await Go(e,t);if(n)return new mt({fundingUrl:n.fundingUrl,reason:n.reason})}const qo={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]};function Jo(e){return{name:`MPP`,version:`3`,chainId:e}}function Yo(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function Xo(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:Jo(n),types:qo,primaryType:`Proof`,message:Yo({account:t,challengeId:r,realm:i})}}function Zo(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const Qo=[...oe.accountKeychain.filter(e=>e.type===`error`),...oe.tip20.filter(e=>e.type===`error`)];function $o(e){let t=new Set,n=e;for(;typeof n==`object`&&n&&!t.has(n);){t.add(n);let e=n.data;if(ns(e))return e;let r=e?.data;if(ns(r))return r;n=n.cause}}function es(e,t){let n=$o(e);if(!n)return;let i=(()=>{try{return r({abi:Qo,data:n})}catch{return}})();if(i?.errorName===`SpendingLimitExceeded`){let n=t.account.accessKeyAddress;return new ft({accessKey:typeof n==`string`?n:void 0,account:t.account.address,cause:e})}if(i?.errorName===`InsufficientBalance`){let[n,r,a]=i.args;return new mt({cause:e,reason:`${t.account.address} holds ${n} of token ${a}, but the payment requires ${r}`})}}async function ts(e,t){try{return await t()}catch(t){throw es(t,e)??t}}function ns(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{8}/.test(e)}const rs=7200n,is=64n,as=s({abi:oe.zonePortal,name:`WithdrawalProcessed`});function os(e){return Number.isInteger(e)&&e>0&&e<4217e5}function ss(e,t){return os(t)?e===!0||(e?.includes(t)??!1):!1}function cs(e){return ce.zonePortal(e)}cs(0).slice(0,-16).toLowerCase();function ls(e){if(e>=2**32)return e%2**32;if(e>142431e4&&e<142432e4)return e-142431e4;if(e>4217e5&&e<42171e4)return e-4217e5;throw Error(`Cannot derive a Zone ID from chain ID ${e}. Pass \`zoneId\`.`)}function us(e){if(e>=2**32)return Math.floor(e/2**32);if(e>142431e4&&e<142432e4)return 42431;if(e>4217e5&&e<42171e4)return 4217}function ds(e){return j.keccak256(O.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function fs(e,t){let{blockNumber:n,sender:r,transactionHash:i}=t,a=t=>x(e,{abi:oe.zoneOutbox,address:ce.zoneOutbox,blockNumber:t,functionName:`lastFallbackNonce`}),[o,s]=await Promise.all([a(n-1n),a(n)]);if(s<=o)throw Error(`Zone withdrawal transaction ${i} did not request a withdrawal from the outbox.`);if(s-o>is)throw Error(`Zone withdrawal transaction ${i} has ${s-o} candidate sender tags, more than ${is}.`);let c=[];for(let e=o+1n;e<=s;e++)c.push(ds({fallbackNonce:e,sender:r,transactionHash:i}));return c}async function ps(e,t){let{senderTags:n,timeoutMs:r=6e4}=t;if(!Number.isFinite(r)||r<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);if(n.length===0)throw Error(`Zone settlement needs at least one sender tag.`);let i=await v(e,{cacheTime:0}),a=i>rs?i-rs:0n,o=Date.now()+r;for(;;){if(a<=i){let[r]=await y(e,{address:t.portal,event:as,args:{senderTag:[...n],...t.to?{to:t.to}:{}},fromBlock:a,toBlock:i});if(r?.transactionHash&&r.args.senderTag)return{hash:r.transactionHash,senderTag:r.args.senderTag};a=i+1n}if(Date.now()+500>o)throw Error(`Zone withdrawal ${n.join(` or `)} did not settle on Tempo within ${r}ms.`);await new Promise(e=>setTimeout(e,500)),i=await v(e,{cacheTime:0})}}const ms=[`push`,`pull`],hs=G.object({amount:K(),memo:G.optional(J()),recipient:G.pipe(G.string(),G.transform(e=>e))}),gs=(1n<<64n)-1n,_s={dev_second:1n,day:86400n,week:604800n},vs=G.pipe(q(),G.transform(e=>e.toLowerCase())),ys=G.object({accessKeyAddress:vs,keyType:G.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:G.optional(G.pipe(G.string().check(G.regex(/^0x[0-9a-fA-F]{120}$/)),G.transform(e=>e)))}),bs=G.object({accessKey:G.optional(ys),chainId:G.optional(G.number())}),xs=yt(`subscriptionExpires must be a valid date`).check(G.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),Ss=G.enum([`dev_second`,`day`,`week`]),Cs=G.pipe(G.union([G.string(),G.bigint(),G.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),G.transform(e=>e.toString())).check(G.regex(/^[1-9]\d*$/,`Invalid periodCount`),G.refine(e=>{try{return BigInt(e)<=gs}catch{return!1}},`periodCount exceeds uint64`));function ws(e){return G.refine(e=>{let{amount:t,decimals:n}=e;return g(t,n)>0n},e)}function Ts(e){let{periodCount:t,periodUnit:n}=e;try{let e=_s[n];return e!==void 0&&BigInt(t)*e<=gs}catch{return!1}}const Es=vn({name:`tempo`,intent:`charge`,schema:{credential:{payload:G.discriminatedUnion(`type`,[G.object({hash:J(),type:G.literal(`hash`)}),G.object({signature:Y(),type:G.literal(`transaction`)}),G.object({signature:Y(),type:G.literal(`proof`)}),G.object({hash:J(),senderTag:J(),type:G.literal(`zone`),zoneId:G.number().check(G.refine(os,`Invalid Zone ID`))})])},request:G.pipe(G.object({machineTokenEnabled:G.optional(G.boolean()),amount:K(),chainId:G.optional(G.number()),currency:G.string(),decimals:G.number(),description:G.optional(G.string()),externalId:G.optional(G.string()),feePayer:G.optional(G.pipe(G.union([G.boolean(),G.custom()]),G.transform(e=>typeof e==`object`||e))),memo:G.optional(G.never()),recipient:G.optional(G.string()),splits:G.optional(G.array(hs).check(G.minLength(1),G.maxLength(10))),supportedModes:G.optional(G.array(G.enum(ms)).check(G.minLength(1))),zones:G.optional(G.union([G.literal(!0),G.array(G.number().check(G.refine(os,`Invalid Zone ID`))).check(G.minLength(1))]))}).check(G.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=g(e,t),i=n.reduce((e,n)=>e+g(n.amount,t),0n);return n.every(e=>g(e.amount,t)>0n)&&i<r},`Invalid splits`)),G.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,zones:c,...l})=>({...l,amount:g(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0||c!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:g(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),Ds=vn({name:`tempo`,intent:`session`,schema:{credential:{payload:G.discriminatedUnion(`action`,[G.object({action:G.literal(`open`),authorizedSigner:G.optional(G.string()),channelId:J(),cumulativeAmount:K(),descriptor:G.optional(G.custom()),signature:Y(),transaction:Y(),type:G.literal(`transaction`)}),G.object({action:G.literal(`topUp`),additionalDeposit:K(),channelId:J(),descriptor:G.optional(G.custom()),transaction:Y(),type:G.literal(`transaction`)}),G.object({action:G.literal(`voucher`),channelId:J(),cumulativeAmount:K(),descriptor:G.optional(G.custom()),signature:Y()}),G.object({action:G.literal(`close`),channelId:J(),closeSignature:Y(),cumulativeAmount:K(),descriptor:G.optional(G.custom()),signature:Y()})])},request:G.pipe(G.object({amount:K(),chainId:G.optional(G.number()),channelId:G.optional(J()),configurableVouchers:G.optional(G.boolean()),currency:G.string(),decimals:G.number(),escrowContract:G.optional(G.string()),feePayer:G.optional(G.pipe(G.union([G.boolean(),G.custom()]),G.transform(e=>typeof e==`object`||e))),feeToken:G.optional(q()),minVoucherDelta:G.optional(K()),operator:G.optional(q()),recipient:G.optional(G.string()),sessionProtocol:G.optional(G.enum([nt.v2,nt.v1])),sessionSnapshot:G.optional(G.custom()),suggestedDeposit:G.optional(K()),unitType:G.string()}).check(G.refine(({amount:e,decimals:t})=>g(e,t)>0n,`Session amount must be greater than 0`)),G.transform(({amount:e,chainId:t,channelId:n,configurableVouchers:r,decimals:i,escrowContract:a,feePayer:o,feeToken:s,minVoucherDelta:c,operator:l,sessionProtocol:u,sessionSnapshot:d,suggestedDeposit:f,...p})=>({...p,amount:g(e,i).toString(),...f?{suggestedDeposit:g(f,i).toString()}:{},methodDetails:{escrowContract:a,...n!==void 0&&{channelId:n},...c!==void 0&&{minVoucherDelta:g(c,i).toString()},...t!==void 0&&{chainId:t},...o!==void 0&&{feePayer:o},...s!==void 0&&{feeToken:s},...l!==void 0&&{operator:l},...r!==void 0&&{configurableVouchers:r},...u!==void 0&&{[tt.sessionProtocol]:u},...d!==void 0&&{[tt.sessionSnapshot]:d}}})))}}),Os=vn({name:`tempo`,intent:`subscription`,schema:{credential:{payload:G.object({signature:Y(),type:G.literal(`keyAuthorization`)})},request:G.pipe(G.object({amount:K(),accessKey:G.optional(ys),chainId:G.optional(G.number()),currency:vs,decimals:G.number(),description:G.optional(G.string()),externalId:G.optional(G.string()),methodDetails:G.optional(bs),periodCount:Cs,periodUnit:Ss,recipient:vs,subscriptionExpires:xs}).check(ws(`Subscription amount must be greater than 0`),G.refine(Ts,`Subscription period exceeds uint64`)),G.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:g(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}}),ks=G.object({account:G.optional(G.custom()),autoSwap:G.optional(G.custom()),feeToken:G.optional(G.custom()),mode:G.optional(G.enum(ms))});function As(e={}){let{clientId:t}=e;if((e.maxAmount!==void 0||e.maxAtomicAmount!==void 0)&&e.currencies===void 0)throw Error(`Tempo charge maxAmount and maxAtomicAmount require currencies.`);for(let t of e.currencies??[])Ks(e.maxAmount,typeof t==`string`?e.decimals:t.decimals);let n={maxAmount:e.maxAmount,maxAtomicAmount:e.maxAtomicAmount===void 0?void 0:BigInt(e.maxAtomicAmount)},r=vo({chain:B,getClient:e.getClient,rpcUrl:Or}),i=mo({account:e.account});Rs(e.zone);let a=new Map,o=yn(Es,{canHandleChallenge({challenge:t}){try{return qs(e,n,t.request),!0}catch{return!1}},context:ks,async createCredential(o){let{challenge:s,context:c}=o;qs(e,n,s.request);let l=s.request.methodDetails?.chainId,u=l??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),d=await r({chainId:u});yo(d,u);let f=u??d.chain?.id;if(bo(e.allowedChainIds,f),f===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");l===void 0&&qs(e,n,s.request,f);let{request:p}=s,{amount:m,methodDetails:h}=p,g=h?.supportedModes??[`pull`,`push`],_=e.zone?.client.chain,v=e.zone?e.zone.zoneId??ls(_?.id??0):void 0,y=_?.sourceId??(_?us(_.id):void 0),x=c?.mode??e.mode;if(BigInt(m)>0n&&e.zone&&v!==void 0&&y===f&&g.includes(`push`)&&(x===void 0||x===`push`)&&ss(h?.zones,v)&&!h?.splits){let r={assertFee:t=>qs(e,n,p,f,t),challenge:s,clientId:t,client:d,origin:Ls(pa(o)),pending:a,zone:e.zone,zoneId:v},i=Ps(r);if(i)return Fs(r,i);if(s.expires&&gn(s.expires,s.id),zs(s.expires,e.zone.settlementTimeoutMs))return Ns(r)}let C=i(d,c),ee=async t=>await e.resolveAccount?.({account:C,chainId:f,operation:t})??C;if(BigInt(m)===0n){let e=await ee({kind:`signPaymentProof`});return dn({challenge:s,payload:{signature:await E(d,{account:e,...Xo({account:e.address,chainId:f,challengeId:s.id,realm:s.realm})}),type:`proof`},source:Zo({address:e.address,chainId:f})})}let D=p.currency,te=zo({chainId:f,currency:D}),O=Co({challengeId:s.id,clientId:t,serverId:s.realm}),k=jo({amount:m,methodDetails:{...h,memo:O},recipient:p.recipient}),A=k.map(e=>V.token.transfer.call(d,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:D})),j=ko(c?.autoSwap??e.autoSwap,Do),M=h?.machineTokenEnabled===!0?Bo({chainId:f,currency:D,transfers:k}):void 0,N=C,P,F=!1;if(M){let e=await(async()=>{try{return await ee({calls:M.calls,kind:`executeCalls`})}catch{return}})();e&&(P=await Vo(d,{account:e.address,chainId:f,currency:D,transfers:k}),P?N=e:F=!0)}let I;if(!P&&(N=await ee({kind:`executeCalls`,...j?{}:{calls:A}}),I=j?await Oo(d,{account:N.address,amountOut:BigInt(m),tokenOut:D,tokenIn:j.tokenIn,slippage:j.slippage,maxAmountIn:j.maxAmountIn}):void 0,F&&!j)){let e=await js(d,{account:N.address,amount:BigInt(m),chainId:f,currency:D});if(e)throw e}let L=P?.calls??[...I??[],...A],R=Fo(f),z=(c?.feeToken??e.feeToken)||(P||te?await Io({account:N.address,allowedTokens:R,candidateTokens:R,client:d,prioritizeCandidates:!0}):void 0),B=(()=>{let t=c?.mode??e.mode;if(t){if(!g.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=N.type===`json-rpc`?`push`:`pull`;return g.includes(n)?n:g[0]})(),ne=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!s.expires)return e;let t=Math.floor(new Date(s.expires).getTime()/1e3)+1;return Math.min(e,t)})();if(B===`push`){let{receipts:e}=N.type===`local`?{receipts:[await ts({account:N},()=>w(d,{account:N,calls:L,...z?{feeToken:z}:{},nonceKey:`expiring`,validBefore:ne}))]}:await S(d,{account:N,...z?{capabilities:{feeToken:z}}:{},calls:L,experimental_fallback:L.length===1,forceAtomic:L.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return dn({challenge:s,payload:{hash:t,type:`hash`},source:Zo({address:N.address,chainId:f})})}let re=()=>{if(h?.feePayer!==!0)return;let e=15e3,t=s.expires?new Date(s.expires).getTime():1/0,n=Date.now();if(!(t-n>=e))throw Error(`Sponsored challenge expires in less than 15 seconds; the fee payer would reject the transaction. Request a new challenge.`);if(!(ne*1e3-n>=e))throw Error(`Sponsored transaction preparation took too long: less than 15 seconds of its validity window remain, so the fee payer would reject it.`)};re();let ie=await ts({account:N},()=>b(d,{account:N,calls:L,...z?{feeToken:z}:{},nonceKey:`expiring`,validBefore:ne}));if(ie.gas=(ie.gas??0n)+5000n,h?.feePayer){let e=ie;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return re(),dn({challenge:s,payload:{signature:await T(d,ie),type:`transaction`},source:Zo({address:N.address,chainId:f})})}}),s=new Map,c=async t=>{qs(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,a=s.get(i);return a||(a=o.createCredential(t).finally(()=>s.delete(i)),s.set(i,a)),a};return ua({...o,createCredential:c},Ms)}async function js(e,t){let{account:n,amount:r,chainId:i,currency:a}=t,o=await x(e,V.token.getBalance.call(e,{account:n,token:a})).catch(()=>void 0);if(!(typeof o!=`bigint`||o>=r))return Ko(e,{account:n,amount:r,chainId:i})}function Ms(e){let t=Es.schema.credential.payload.safeParse(sn(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`||n.type===`zone`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(ve.serializedType))return;let i=ve.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&ve.serialize(i)===r)return p(r)}function Ns(e){let{challenge:t,origin:n,pending:r,zoneId:i}=e,a={sent:!1},o={challenge:t,origin:n,terms:Hs(t,i),waiters:0,withdrawal:Gs(e,a)},s=Vs(t);return r.set(s,o),o.withdrawal.catch(()=>{!a.sent&&r.get(s)===o&&r.delete(s)}),Fs(e,o)}function Ps(e){let{challenge:t,pending:n,zoneId:r}=e,i=n.get(Vs(t));if(i)return i;let a=Hs(t,r);if(a!==void 0){for(let[e,t]of n)if(t.terms===a){if(!Ws(t.challenge.expires)){n.delete(e);continue}if(t.redeemedLate)throw new pt({challengeId:t.challenge.id,senderTags:t.senderTags,zoneId:r});if(!(t.waiters>0))return t}}}async function Fs(e,t){t.waiters++;try{return await Is(e,t)}finally{t.waiters--}}async function Is(e,t){let{client:n,origin:r,pending:i,zone:a,zoneId:o}=e,{challenge:s}=t,c=s.request.recipient,l=Vs(s);if((l===Vs(e.challenge)?r!==void 0&&t.origin!==void 0&&r!==t.origin:!r||r!==t.origin)||!Ws(s.expires))throw new pt({challengeId:s.id,zoneId:o});let u=await t.withdrawal,d=u.senderTags??await fs(a.client,u).catch(e=>{let t=Error(`Zone withdrawal transaction ${u.transactionHash} was sent, but its sender tag could not be read from the Zone. Retry the challenge to resume without withdrawing again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),t}),f;try{f=await ps(n,{portal:cs(o),senderTags:d,timeoutMs:Bs(s.expires,a.settlementTimeoutMs),to:c})}catch(e){throw new pt({cause:e,challengeId:s.id,senderTags:d,zoneId:o})}i.get(l)===t&&(Us(s.expires)?(t.redeemedLate=!0,t.senderTags=[f.senderTag]):i.delete(l));let{hash:p,senderTag:m}=f;return dn({challenge:s,payload:{hash:p,senderTag:m,type:`zone`,zoneId:o}})}function Ls(e){if(e)try{let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`?void 0:t.origin}catch{return}}function Rs(e){let t=e?.settlementTimeoutMs;if(t!==void 0&&(!Number.isFinite(t)||t<0))throw Error("`zone.settlementTimeoutMs` must be a finite, non-negative number.");let n=e?.client.chain?.id;if(e?.zoneId===void 0||n===void 0||us(n)===void 0)return;let r=ls(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function zs(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+15e3}function Bs(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function Vs(e){return JSON.stringify(e)}function Hs(e,t){let n;try{n=e.opaque===void 0?e.meta:ht(e.opaque)}catch{return}let{digest:r,intent:i,method:a,realm:o,request:s}=e;return gt({digest:r,intent:i,meta:_n(n),method:a,realm:o,request:s,zoneId:t})}function Us(e){if(!e)return!1;let t=new Date(e).getTime();return!Number.isNaN(t)&&Date.now()>=t}function Ws(e){if(!e)return!0;let t=new Date(e).getTime();return Number.isNaN(t)||Date.now()<t+3e5}async function Gs(e,t){let{assertFee:n,challenge:r,clientId:i,zone:a}=e,o=r.request,s=a.client.account;if(!s)throw Error("`zone.client` requires an account.");let c=BigInt(o.amount),l=o.currency,u=o.recipient,d=Co({challengeId:r.id,clientId:i,serverId:r.realm}),f=await V.zone.getWithdrawalFee(a.client);n(f);let[,m]=V.zone.requestWithdrawal.calls({amount:c,fallbackRecipient:s.address,memo:d,to:u,token:l}),g=await b(a.client,{account:s,calls:[V.token.approve.call({amount:c+f,spender:ce.zoneOutbox,token:l}),m]}),_=await T(a.client,g);t.sent=!0;let v=p(_),y=await C(a.client,{serializedTransaction:_}).catch(e=>ee(a.client,{hash:v,timeout:15e3}).catch(()=>{let t=Error(`Zone withdrawal outcome is unknown: transaction ${v} may have been sent. Retrying this challenge does not withdraw again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),t}));if(y.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${y.transactionHash} reverted.`);let[x]=h({abi:oe.zoneOutbox,eventName:`WithdrawalRequested`,logs:y.logs});return{blockNumber:y.blockNumber,sender:s.address,senderTags:x?[ds({fallbackNonce:x.args.fallbackNonce,sender:x.args.sender,transactionHash:y.transactionHash})]:void 0,transactionHash:y.transactionHash}}function Ks(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo charge maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo charge maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return g(e,t)}}function qs(e,t,n,r,i){let{methodDetails:a,recipient:o}=n,s=a?.chainId;if(e.expectedChainId!==void 0&&s!==void 0&&s!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${s}.`);(s!==void 0||e.allowedChainIds?.length===0)&&bo(e.allowedChainIds,s);let c=e.currencies?Oe(e.currencies,n.currency,{chainId:s??r??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),decimals:e.decimals}):void 0;if(e.currencies&&!c)throw Error(`Tempo charge currency is not allowed: ${n.currency}.`);if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!o||!t.has(o.toLowerCase()))throw Error(`Unexpected primary recipient: ${o}`);let n=a?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}if(t.maxAtomicAmount===void 0&&t.maxAmount===void 0)return;let l=BigInt(n.amount)+(i??0n),u=i===void 0?`amount exceeds`:`amount plus Zone withdrawal fee exceeds`;if(t.maxAtomicAmount!==void 0&&l>t.maxAtomicAmount)throw Error(`Tempo charge ${u} maxAtomicAmount.`);if(t.maxAmount!==void 0&&l>Ks(t.maxAmount,c?.decimals))throw Error(`Tempo charge ${u} maxAmount.`)}const Js=(1n<<96n)-1n;function Ys(e){return e>=0n&&e<=Js}function Xs(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return Ys(t)?t:void 0}function Zs(e){return Qs(e),e}function Qs(e){if(!Ys(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const $s=new Set([`open`,`topUp`,`voucher`,`close`]);function ec(e){return typeof e==`object`&&!!e}function tc(e){return typeof e==`string`&&$s.has(e)}function nc(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!tc(t.action))}function rc(e,t=`No session credential context available.`){if(!nc(e))throw Error(t);return e}function ic(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function ac(e){return ec(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function oc(e){return ec(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 sc(e){let t=k.toString(e),n=JSON.parse(t);if(!oc(n))throw Error(`Invalid session receipt.`);return n}function cc(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function lc(e){let t=`message`,n=[];for(let r of e.split(`
8
8
  `))r.startsWith(`event: `)?t=r.slice(7).trim():r.startsWith(`data: `)?n.push(r.slice(6)):r===`data:`&&n.push(``);if(n.length===0)return null;let r=n.join(`
9
- `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=rc(r);return Qs(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=rc(r);return $s(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function rc(e){try{return JSON.parse(e)}catch{return null}}function ic(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function ac(){return JSON.stringify({mpp:`payment-close-request`})}function oc(e){let t=sc(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`&&$s(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`&&Qs(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&$s(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function sc(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}const cc=`0x4d50500000000000000000000000000000000000`;function lc(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function uc(e){let t=D.encode(D.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 A.keccak256(t)}function dc(e){return ye.encodeForSigning(e)}function fc(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function pc(e,t){return A.keccak256(j.concat(dc(e),t.sender))}const mc=[{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`}],hc=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],gc={name:`descriptor`,type:`tuple`,components:mc},_c=[{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:[gc,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[gc,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[gc,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[gc],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[gc],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[gc],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:mc},{name:`state`,type:`tuple`,components:hc}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:hc}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:hc}]},{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:`verifyVoucher`,stateMutability:`view`,inputs:[gc,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[{name:`valid`,type:`bool`}]},{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:`OpeningCommitmentRecorded`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`signer`,type:`address`,indexed:!0},{name:`commitment`,type:`bytes32`}]},{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}]},{type:`error`,name:`RootKeyRetired`,inputs:[{name:`account`,type:`address`}]},{type:`error`,name:`SignerConfigChanged`,inputs:[{name:`signer`,type:`address`}]},{type:`error`,name:`SaltNotSignerCommitment`,inputs:[{name:`signer`,type:`address`},{name:`commitment`,type:`bytes32`}]}];function vc(e){return e.type===`secp256k1`?e.signature.s<=57896044618658097711785492504343953926418782139537452191302581570759080747168n:e.type===`p256`||e.type===`webAuthn`?e.signature.s<=57896044605178124381348723474703786764998477612067880171211129530534256022184n:!0}function yc(e){if(e.type===`configurable`)return{...e,signatures:e.signatures.map(e=>yc(e))};if(vc(e))return e;if(e.type===`secp256k1`){let{r:t,s:n,yParity:r}=e.signature;return{...e,signature:{r:t,s:115792089237316195423570985008687907852837564279074904382605163141518161494337n-n,yParity:+(r===0)}}}return e.type===`p256`||e.type===`webAuthn`?{...e,signature:{...e.signature,s:115792089210356248762697446949407573529996955224135760342422259061068512044369n-e.signature.s}}:e}function bc(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function xc(e){return e===void 0||BigInt(e)===0n}function Sc(e,t){let{account:n,config:r,signatures:i}=e,a=he.getSignPayload({account:n,config:r,payload:t}),o=Number(r.threshold),s,c=0,l;for(let[e,t]of i.entries()){if(!bc(t.type)||!vc(t)||e>0&&c>=o)return!1;let n=V.extractAddress({payload:a,signature:t});if(!V.verify(t,{address:n,payload:a}))return!1;let i=r.owners.find(e=>vo(e.owner,n));if(!i)return!1;let u=Number(i.weight);if(u===0)return!1;let d=BigInt(n);if(s!==void 0&&s>=d)return!1;s=d,c+=u,l=l===void 0?u:Math.min(l,u)}return!(i.length===0||c<o||l!==void 0&&c>=o+l)}function Cc(e,t){let{account:n,commitment:r,payload:i}=t;if(!vo(e.account,n)||BigInt(e.config.version??0n)===0n&&e.config.owners.some(({owner:t})=>vo(t,e.account)))return!1;if(xc(r)){if(BigInt(e.config.version??0n)!==0n||!vo(he.getAddress(e.config),n))return!1}else if(he.getCommitment(e.config).toLowerCase()!==r.toLowerCase())return!1;return Sc(e,i)}function wc(e,t){return{name:`TIP20 Channel Reserve`,version:`1`,chainId:t,verifyingContract:e}}const Tc={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},Ec={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]};function Dc(e,t,n){return l({domain:wc(e,t),types:Ec,primaryType:`CloseAuthorization`,message:n})}function Oc(e,t){return ge.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function kc(e,t,n){return e.toLowerCase()===ge.address.toLowerCase()?Oc(t,n):l({domain:wc(e,t),types:Tc,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function Ac(e,t,n,r){let i=jc(e);return i?Mc(i,t,n,r):!1}function jc(e){let t=V.from(e);if(V.serialize(t).toLowerCase()===e.toLowerCase())return t}function Mc(e,t,n,r){if(e.type===`configurable`)return r.configurable?Cc(e,{account:n,commitment:r.openingCommitment,payload:t}):!1;if(!bc(e.type)||!vc(e)||!xc(r.openingCommitment))return!1;let i=V.extractAddress({payload:t,signature:e});return V.verify(e,{address:i,payload:t})&&vo(i,n)}function Nc(e){return e.source===`configurable`}function Pc(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function Fc(e,t){return ce.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function Ic(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===ge.address.toLowerCase())try{return await Fc(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return E(e,{account:t,domain:wc(r,i),types:Tc,primaryType:`Voucher`,message:n})})(),o=V.from(a);if(!bc(o.type)&&o.type!==`configurable`)throw Error(`TIP-1034 vouchers require a TIP-1020 primitive or TIP-1166 configurable account signature; received "${o.type}".`);return V.serialize(yc(o))}async function Lc(e,t,n,r,i){let a=Pc(t)?await t.sign({hash:Dc(r,i,n),raw:!0}):await E(e,{account:t,domain:wc(r,i),types:Ec,primaryType:`CloseAuthorization`,message:n}),o=V.from(a);if(!bc(o.type)&&o.type!==`configurable`)throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive or TIP-1166 configurable account signature; received "${o.type}".`);return V.serialize(yc(o))}function Rc(e,t,n,r,i={}){try{let a=kc(e,t,n);return Ac(n.signature,a,r,i)}catch{return!1}}function zc(e){return typeof e==`object`&&!!e}function Bc(e){return typeof e==`string`&&d(e,{strict:!1})?e:void 0}function Vc(e){return Bc(e.accessKeyAddress)}function Hc(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(j.random(8))%e)}function Uc(e){return Vc(e)??e.address}function Wc(e){return Gc(e)!==void 0}function Gc(e){let t=Vc(e);if(t===void 0)return Nc(e)?e:void 0;let n=e.delegate;if(n&&Nc(n)&&n.address.toLowerCase()===t.toLowerCase())return n}async function Kc(e,t){let n=Gc(t);if(!n)return j.random(32);let{config:r}=n,i=await B.accounts.getConfigCommitment(e,{account:n.address}),a=r?he.getCommitment(r):void 0;if(BigInt(i)!==0n){if(a&&a.toLowerCase()!==i.toLowerCase())throw Error(`Configurable account ${n.address} holds a config whose commitment ${a} does not match its on-chain commitment ${i}. Use the account's current config.`);return i}if(!a||BigInt(r.version??0n)!==0n)throw Error(`Configurable account ${n.address} is not registered, so it needs its version-zero config to open a channel.`);return a}function qc(e,t){let n=Ko(e);if(n)try{let i=r({abi:_c,data:n});if(i.errorName!==`SignerConfigChanged`&&i.errorName!==`RootKeyRetired`)return;let[a]=i.args;return a.toLowerCase()===t.signer.toLowerCase()?new on({cause:e,channelId:t.channelId,reason:i.errorName,signer:a}):void 0}catch{return}}async function Jc(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return Jo({account:n},()=>b(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}}))}async function Yc(e,t){return await T(e,t)}function Xc(e,t,n=!1){let r=e.request.methodDetails,i=zc(r)?Bc(r.escrowContract)??Bc(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!Qc(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!Qc(i,a)?i:a}function Zc(e,t,n,r){return Jt({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${t.descriptor?.payer??r.address}`})}function Qc(e,t){return e.toLowerCase()===t.toLowerCase()}function $c(e,t){let n=Gc(e);if(!n?.config)return;let{config:r}=n;if(he.getCommitment(r).toLowerCase()!==t.salt.toLowerCase()&&(BigInt(r.version??0n)!==0n||he.getAddress(r).toLowerCase()!==n.address.toLowerCase()))throw Error(`Configurable account ${n.address} holds a config that does not match the channel's opening commitment (salt ${t.salt}), so it cannot sign a voucher the channel settles. Sign with the config the channel opened with, or close the channel and open a new one.`)}async function el(e,t,n,r,i,a=cc){let o=uc({...n,chainId:i,escrow:a}),s=Ws(r);$c(t,n);let c=await Ic(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function tl(e,t,n,r,i,a=cc){let o=await el(e,t,n,r,i,a),s=await Lc(e,t,{channelId:o.channelId,cumulativeAmount:Ws(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function nl(e,t,n){let r=Uc(t),a=n.escrow??`0x4d50500000000000000000000000000000000000`,o=n.operator??`0x0000000000000000000000000000000000000000`,s=n.salt??await Kc(e,t),c=Ws(n.deposit),l=Ws(n.initialAmount),u=i({abi:_c,functionName:`open`,args:[n.payee,o,n.token,c,s,r]}),d=await Yc(e,await Jc(e,{account:t,calls:[...n.prefixCalls??[],{to:a,data:u}],feePayer:n.feePayer,feeToken:n.feeToken??n.token,validAfter:Hc()})),f=de.deserialize(d),p={authorizedSigner:r,expiringNonceHash:pc(fc({...n.feePayer?{feePayer:!0}:{},transaction:f}),{sender:t.address}),operator:o,payee:n.payee,payer:t.address,salt:s,token:n.token},m=uc({...p,chainId:n.chainId,escrow:a});return{action:`open`,type:`transaction`,channelId:m,transaction:d,signature:await Ic(e,t,{channelId:m,cumulativeAmount:l},a,n.chainId),descriptor:p,cumulativeAmount:l.toString(),authorizedSigner:p.authorizedSigner}}async function rl(e,t,n,r,a,o,s=cc,c=[],l=n.token){let u=uc({...n,chainId:a,escrow:s}),d=Ws(r);return{action:`topUp`,type:`transaction`,channelId:u,transaction:await Yc(e,await Jc(e,{account:t,calls:[...c,{to:s,data:i({abi:_c,functionName:`topUp`,args:[n,d]})}],feePayer:o,feeToken:l,validAfter:Hc()}).catch(e=>{throw qc(e,{channelId:u,signer:lc(n)})??e})),descriptor:n,additionalDeposit:d.toString()}}function il(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Q(e){return il({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function al(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Q(t),t)},delete(t){e.delete(t)}}}const ol=new WeakMap,sl=new WeakMap;function cl(e,t){sl.set(e,sl.get(t)??t)}async function ll(e,t,n){let r=ol.get(e);r||(r=new Map,ol.set(e,r));let i=(r.get(t)??Promise.resolve()).catch(()=>{}).then(n);r.set(t,i);try{return await i}finally{r.get(t)===i&&r.delete(t)}}function ul(e,t,n){return ll(sl.get(e)??e,`funding:${t}`,n)}async function dl(e,t){await ll(e,`write:${Q(t)}`,async()=>{let n=await e.get(Q(t));if(n?.origin!==void 0){if(t.origin!==void 0&&t.origin!==n.origin)throw Error(`SessionManager: stored channel origin mismatch`);t.origin=n.origin}if(n?.uncertainTopUp){if(n.channelId!==t.channelId)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);t.uncertainTopUp=!0}await e.set(t)})}async function fl(e,t){await ll(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}const pl=2n**96n-1n;function ml(e){if(e<0n||e>pl)throw new Y({reason:`amount exceeds uint96 range`})}async function hl(e,t,n=cc){let{cumulativeAmount:r,descriptor:i,signature:a}=t;return x(e,{address:n,abi:_c,functionName:`verifyVoucher`,args:[vl(i),r,a]})}async function gl(e,t,n=cc,r){return _l(await x(e,{address:n,abi:_c,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function _l(e){return ml(e.settled),ml(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}function vl(e){return{payer:e.payer,payee:e.payee,operator:e.operator,token:e.token,salt:e.salt,authorizedSigner:e.authorizedSigner,expiringNonceHash:e.expiringNonceHash}}const yl=W.custom(e=>typeof e==`string`&&d(e,{strict:!1})),bl=W.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),xl=W.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),Sl=W.object({authorizedSigner:yl,expiringNonceHash:bl,operator:yl,payee:yl,payer:yl,salt:bl,token:yl}),Cl=mn(W.object({acceptedCumulative:W.string(),chainId:W.number(),channelId:bl,closeRequestedAt:W.optional(W.string()),deposit:W.string(),descriptor:Sl,escrow:yl,highestVoucher:W.optional(W.object({channelId:bl,cumulativeAmount:W.string(),signature:xl})),requiredCumulative:W.string(),settled:W.string(),spent:W.string(),units:W.optional(W.number())}));function wl(e){return Cl.encode(e)}function Tl(e){return Cl.decode(e)}const El={status:`idle`};function Dl(e){return{status:`active`,...e}}function Ol(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:jl(e.challengeId,t.snapshot),effects:[]}:$(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Wl({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:Ml(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:$(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:ql(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?Al({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:Ml(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:Ml(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 kl(e,t){let n=Ol(e.state,t);return e.state=n.state,n}function Al(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 jl(e,t){return Dl({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function Ml(e,t,n,r){return Dl({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 Nl(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function Pl(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`);Nl({cumulativeAmount:i,maxVoucherCumulative:n}),Nl({cumulativeAmount:a,maxVoucherCumulative:n})}function Fl(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;Pl({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function Il(e,t){return typeof e==`bigint`?e:g(e,t)}function Ll(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(zl(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 Rl(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;Nl({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 zl(e,t){Nl({cumulativeAmount:e,maxVoucherCumulative:t??null})}function Bl(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 Vl(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function Hl(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!Hs(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>Vl({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function Ul(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=Us(r),s=Us(a.spent);return o===void 0||s===void 0||!Hs(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function Wl(e){return Dl({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 Gl(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:El}}function Kl(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=Fl({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&kl(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function ql(e,t){return Dl({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function Jl(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=Us(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 Yl(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 Ol(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function Xl(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 Zl(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 Ql(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(ac()),e.waitForCloseReady()))(),a=BigInt(i.spent);Hl({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=>Ul({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(ic(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}function $l(e){return`cumulativeAmount`in e}function eu(e){if($l(e))return BigInt(e.cumulativeAmount)}async function tu(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await dl(e.store,t):await fl(e.store,Q(t)),e.notifyUpdate(t)}async function nu(e,t,n){let r=eu(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 tu(e,i))}const ru=W.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),iu=W.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),au=W.object({account:W.optional(W.custom()),autoSwap:W.optional(W.custom()),action:W.optional(W.enum([`open`,`topUp`,`voucher`,`close`])),channelId:W.optional(iu),cumulativeAmount:W.optional(G()),cumulativeAmountRaw:W.optional(W.string()),transaction:W.optional(ru),descriptor:W.optional(W.custom()),additionalDeposit:W.optional(G()),additionalDepositRaw:W.optional(W.string()),depositRaw:W.optional(W.string())});function ou(e){return e?.action!==void 0}function su(e){return ou(e)&&e.descriptor!==void 0}function cu(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 g(i,t)}function lu(e,t,n,r){let i=cu(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function uu(e){return typeof e==`object`&&!!e}function du(e){return typeof e==`string`&&d(e,{strict:!1})?e:void 0}function fu(e){let t=e.request.methodDetails;return uu(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:du(t.escrowContract),escrow:du(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:du(t.feeToken),operator:du(t.operator),configurableVouchers:typeof t.configurableVouchers==`boolean`?t.configurableVouchers:void 0,sessionSnapshot:it(t,nt.sessionSnapshot)}:{}}function pu(e,t){if(typeof e==`string`&&d(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function mu(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function hu(e){return typeof e==`string`?e:void 0}async function gu(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=fu(n);(o.chainId!==void 0||i?.length===0)&&po(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});fo(c,s);let l=s??c.chain?.id;if(po(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=Xc(n,r,t),d=pu(n.request.recipient,`recipient`),f=pu(n.request.currency,`currency`);return{amount:mu(n.request.amount),challenge:n,chainId:l,client:c,...o.configurableVouchers===void 0?{}:{configurableVouchers:o.configurableVouchers},escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:il({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:hu(n.request.suggestedDeposit),token:f}}async function _u(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=gl}=e,o=uc({...r,chainId:i.chainId,escrow:i.escrow});vu({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 vu(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(!Qc(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!Qc(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!Qc(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!Qc(lc(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function yu(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function bu(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=cu(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function xu(e){let{account:t,client:n,readChannelState:r,snapshot:i,verifyVoucherOnChain:a=hl}=e,o=i.highestVoucher;if(!o)throw Error(`session snapshot is missing its highest signed voucher`);if(o.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let s=BigInt(i.acceptedCumulative),c=BigInt(o.cumulativeAmount),l=BigInt(i.requiredCumulative),u=BigInt(i.deposit),d=BigInt(i.settled),f=BigInt(i.spent);if(c!==s)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(f>s)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(d>u)throw Error(`session snapshot settled amount exceeds deposit`);let p={channelId:o.channelId,cumulativeAmount:c,signature:o.signature},m=lc(i.descriptor),h=Wc(t);if(!(Rc(i.escrow,i.chainId,p,m,h?{configurable:!0,openingCommitment:i.descriptor.salt}:{})||h&&await a(n,{descriptor:i.descriptor,cumulativeAmount:c,signature:p.signature},i.escrow).catch(()=>!1)))throw Error(`session snapshot highest voucher signature is invalid`);let g=await _u({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:Uc(t),token:i.descriptor.token},readChannelState:r}),_=[s,l,g.state.settled].reduce((e,t)=>t>e?t:e,0n);if(_>g.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:g.channelId,cumulativeAmount:_,deposit:g.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:f}}function Su(e,t){return Qc(e.address,t.payer)?Qc(Uc(e),lc(t)):!1}function Cu(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(ou(r)){if(!su(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=yu({context:r,snapshot:o.snapshot});return!n&&s&&Su(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&Su(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 wu(e,t,n=!1){switch(e.type){case`open`:return Du(e,t,n);case`recover`:return Ou(e,t);case`voucher`:return ku(e,t);case`manual`:return Au(e,t,n)}}async function Tu(e,t){if(e)return await xo(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function Eu(e,t){let{account:n,amount:r,chainId:i,client:a,token:o}=t;if(e||!Mo({chainId:i,currency:o}))return;let s=await zo(a,{account:n,amount:r,chainId:i});if(s)throw s}async function Du(e,t,n){let{account:r,resolved:i}=e;if(Wc(r)&&i.configurableVouchers!==!0)throw new an({signer:r.address});let a=Ll({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw});await Eu(n,{account:r.address,amount:a,chainId:i.chainId,client:i.client,token:i.token});let o=await nl(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 Tu(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await tu(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function Ou(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await _u({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:Uc(n),token:o.token}}),l=bu({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`);zl(l,a);let u=await el(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await tu(t,{...d?.channelId===c.channelId&&d.uncertainTopUp?{uncertainTopUp:!0}:{},channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function ku(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;zl(a,e.maxDeposit);let o=await el(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await tu(t,r),o}async function Au(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=uc({...s,chainId:o.chainId,escrow:o.escrow});vu({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:Uc(r),token:o.token});let l=await ju({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await nu(t,o.key,l),l}async function ju(e,t){switch(e.context.action){case`open`:return Mu(e);case`topUp`:return Nu(e,t);case`voucher`:return Pu(e);case`close`:return Fu(e)}}async function Mu(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=lu(r,i,`cumulativeAmount`,`open`),c=await el(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 Nu(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=lu(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:(await Eu(t,{account:n.address,amount:c,chainId:s.chainId,client:s.client,token:s.token}),rl(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await Tu(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken))}function Pu(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return el(a.client,t,i,lu(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function Fu(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return tl(a.client,t,i,lu(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}const Iu={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function Lu(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=Iu.CLOSED,r=null}if(a.type===`open`&&(i=Iu.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 Ru(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function zu(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=Il(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 Bu(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:ql(s,u)}:i?{channel:u,state:Wl({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function Vu(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=Ru(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,headers:e.headers,channelId:e.expectedChannelId,deposit:t.deposit,requiredCumulative:t.requiredCumulative,...e.signal?{signal:e.signal}:{}});let n=e.getChannel();if(!n||n.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`missing-channel`};let r=n.cumulativeAmount>t.requiredCumulative?n.cumulativeAmount:Ws(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function Hu(e){return e.method===et.tempo&&e.intent===tt.session}function Uu(e){return Hu(e)&&it(e.request.methodDetails,nt.sessionProtocol)===rt.v2}function Wu(e){return it(e.request.methodDetails,nt.sessionSnapshot)}function Gu(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return Ei({...t,redirect:`manual`,headers:{...xa(i),...xa(t?.headers)}},Ft(r),n)}function Ku(e){return e instanceof Request||typeof e==`object`&&!!e&&!(e instanceof URL)&&typeof e.url==`string`&&typeof e.method==`string`&&typeof e.clone==`function`}function qu(e){try{let t=typeof location>`u`?void 0:location.href,n=Ku(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function Ju(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function Yu(e){let t=await e.text().catch(()=>``);if(!t)return``;if(!e.headers.get(`Content-Type`)?.includes(`application/problem+json`))return t;try{return JSON.parse(t).detail??t}catch{return t}}var Xu=class extends Error{constructor(e){let t=e instanceof Error||e instanceof DOMException?e.message:String(e);super(`${t}; payment outcome unknown`),this.name=`UncertainFundingError`}};async function Zu(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);if(t.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let r=await Qu({challenge:e.challenge,context:{action:`topUp`,...e.autoSwap===void 0?{}:{autoSwap:e.autoSwap},channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,headers:e.headers,input:e.input,signal:e.signal}).catch(async n=>{throw n instanceof Xu&&(t.uncertainTopUp=!0,await e.onUncertainFunding?.(t)),n});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(H.paymentReceipt);return i?ec(i):void 0}async function Qu(e){let t=async t=>{e.signal?.throwIfAborted();let n=await e.createSessionCredential(t,e.context);e.signal?.throwIfAborted();let r=new AbortController,i=()=>r.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,i,{once:!0});let a=setTimeout(()=>r.abort(new DOMException(`Session management request timed out; payment outcome unknown`,`TimeoutError`)),3e4),o,s=new Promise((e,t)=>{o=()=>t(r.signal.reason),r.signal.addEventListener(`abort`,o,{once:!0})});try{return await Promise.race([e.fetch(qu(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:Sd(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new Xu(t):t}finally{clearTimeout(a),e.signal?.removeEventListener(`abort`,i),r.signal.removeEventListener(`abort`,o)}},n=await t(e.challenge);if(n.status!==402)return n;let r=Ot(n).find(Uu);return r?t(r):n}async function $u(e){let t=ed({channel:e.getChannel(),response:e.response});if(!t)return;let{channel:n,challenge:r,snapshot:i}=t;e.setChallenge(r);let a=BigInt(i.requiredCumulative),o=n.cumulativeAmount;await e.topUpIfNeeded({challenge:r,input:e.input,headers:e.init?.headers,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a,signal:e.init?.signal??(e.input instanceof Request?e.input.signal:void 0)});let s=e.getChannel();if(!s?.descriptor||s.channelId!==i.channelId)return;let c=s.cumulativeAmount>a?s.cumulativeAmount:a,l=()=>e.restoreCumulative(i.channelId,o),u;try{let t=await e.createSessionCredential(r,{action:`voucher`,channelId:i.channelId,descriptor:s.descriptor,cumulativeAmountRaw:c.toString()});u=await e.fetch(e.input,Gu(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(H.paymentReceipt)&&await l(),u}function ed(e){let t=Ot(e.response).find(Uu);if(!t)return;let n=Wu(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function td(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=Ku(e.lastUrl)?e.lastUrl:void 0,i=r?{cache:r.cache,credentials:r.credentials,integrity:r.integrity,keepalive:r.keepalive,mode:r.mode===`navigate`?`same-origin`:r.mode,referrer:r.referrer,referrerPolicy:r.referrerPolicy}:void 0,a=async(a,o=!1)=>{t=a,n=(o?e.resolveSignedCloseAmount?.(a):void 0)??e.signedCloseAmount;let s=await e.createSessionCredential(a,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(r?qu(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:Sd(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=Ot(o).find(Uu);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await Yu(o),t=o.headers.get(H.wwwAuthenticate)??``;throw Error(`Close request failed with status ${o.status}${e?`: ${e}`:``}${t?` [${H.wwwAuthenticate}: ${t}]`:``}`)}let s=o.headers.get(H.paymentReceipt);if(!s)return;let c=ec(s);if(!c.txHash||!j.validate(c.txHash,{strict:!0})||j.size(c.txHash)!==32||!Ul({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:0n,receipt:c}))throw Error(`Session close response included a mismatched payment receipt.`);return c}async function nd(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...xa(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!tc(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),rd(e,c,{onReceipt:r,signal:o},n,s.headers)}function rd(e,t,n,r,i){if(!tc(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return id({onNeedVoucher:t=>ld({challenge:a,driver:r,headers:i,input:e,signal:n?.signal},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*id(e){for await(let t of ad(e))t.data!==void 0&&(yield t.data)}async function*ad(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=od(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=nc(i.replace(/\r\n|\r/g,`
10
- `));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,e.signal);break;case`payment-receipt`:e.onReceipt(s.data)}}if(a)break}}finally{e.signal?.removeEventListener(`abort`,a),i||await t.cancel().catch(()=>void 0),t.releaseLock()}}function od(e,t){for(let n=0;n<e.length;n++){let r=sd(e,n,t);if(!r)continue;let i=sd(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function sd(e,t,n){return e[t]===`
9
+ `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=uc(r);return ac(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=uc(r);return oc(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function uc(e){try{return JSON.parse(e)}catch{return null}}function dc(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function fc(){return JSON.stringify({mpp:`payment-close-request`})}function pc(e){let t=mc(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`&&oc(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`&&ac(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&oc(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function mc(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}const hc=`0x4d50500000000000000000000000000000000000`;function gc(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function _c(e){let t=O.encode(O.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 j.keccak256(t)}function vc(e){return ve.encodeForSigning(e)}function yc(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function bc(e,t){return j.keccak256(M.concat(vc(e),t.sender))}const xc=[{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`}],Sc=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],Cc={name:`descriptor`,type:`tuple`,components:xc},wc=[{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:[Cc,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[Cc,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[Cc,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[Cc],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[Cc],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[Cc],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:xc},{name:`state`,type:`tuple`,components:Sc}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:Sc}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:Sc}]},{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:`verifyVoucher`,stateMutability:`view`,inputs:[Cc,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[{name:`valid`,type:`bool`}]},{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:`OpeningCommitmentRecorded`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`signer`,type:`address`,indexed:!0},{name:`commitment`,type:`bytes32`}]},{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}]},{type:`error`,name:`RootKeyRetired`,inputs:[{name:`account`,type:`address`}]},{type:`error`,name:`SignerConfigChanged`,inputs:[{name:`signer`,type:`address`}]},{type:`error`,name:`SaltNotSignerCommitment`,inputs:[{name:`signer`,type:`address`},{name:`commitment`,type:`bytes32`}]}];function Tc(e){return e.type===`secp256k1`?e.signature.s<=57896044618658097711785492504343953926418782139537452191302581570759080747168n:e.type===`p256`||e.type===`webAuthn`?e.signature.s<=57896044605178124381348723474703786764998477612067880171211129530534256022184n:!0}function Ec(e){if(e.type===`configurable`)return{...e,signatures:e.signatures.map(e=>Ec(e))};if(Tc(e))return e;if(e.type===`secp256k1`){let{r:t,s:n,yParity:r}=e.signature;return{...e,signature:{r:t,s:115792089237316195423570985008687907852837564279074904382605163141518161494337n-n,yParity:+(r===0)}}}return e.type===`p256`||e.type===`webAuthn`?{...e,signature:{...e.signature,s:115792089210356248762697446949407573529996955224135760342422259061068512044369n-e.signature.s}}:e}function Dc(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function Oc(e){return e===void 0||BigInt(e)===0n}function kc(e,t){let{account:n,config:r,signatures:i}=e,a=me.getSignPayload({account:n,config:r,payload:t}),o=Number(r.threshold),s,c=0,l;for(let[e,t]of i.entries()){if(!Dc(t.type)||!Tc(t)||e>0&&c>=o)return!1;let n=H.extractAddress({payload:a,signature:t});if(!H.verify(t,{address:n,payload:a}))return!1;let i=r.owners.find(e=>To(e.owner,n));if(!i)return!1;let u=Number(i.weight);if(u===0)return!1;let d=BigInt(n);if(s!==void 0&&s>=d)return!1;s=d,c+=u,l=l===void 0?u:Math.min(l,u)}return!(i.length===0||c<o||l!==void 0&&c>=o+l)}function Ac(e,t){let{account:n,commitment:r,payload:i}=t;if(!To(e.account,n)||BigInt(e.config.version??0n)===0n&&e.config.owners.some(({owner:t})=>To(t,e.account)))return!1;if(Oc(r)){if(BigInt(e.config.version??0n)!==0n||!To(me.getAddress(e.config),n))return!1}else if(me.getCommitment(e.config).toLowerCase()!==r.toLowerCase())return!1;return kc(e,i)}function jc(e,t){return{name:`TIP20 Channel Reserve`,version:`1`,chainId:t,verifyingContract:e}}const Mc={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},Nc={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]};function Pc(e,t,n){return l({domain:jc(e,t),types:Nc,primaryType:`CloseAuthorization`,message:n})}function Fc(e,t){return he.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function Ic(e,t,n){return e.toLowerCase()===he.address.toLowerCase()?Fc(t,n):l({domain:jc(e,t),types:Mc,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function Lc(e,t,n,r){let i=Rc(e);return i?zc(i,t,n,r):!1}function Rc(e){let t=H.from(e);if(H.serialize(t).toLowerCase()===e.toLowerCase())return t}function zc(e,t,n,r){if(e.type===`configurable`)return r.configurable?Ac(e,{account:n,commitment:r.openingCommitment,payload:t}):!1;if(!Dc(e.type)||!Tc(e)||!Oc(r.openingCommitment))return!1;let i=H.extractAddress({payload:t,signature:e});return H.verify(e,{address:i,payload:t})&&To(i,n)}function Bc(e){return e.source===`configurable`}function Vc(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function Hc(e,t){return se.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function Uc(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===he.address.toLowerCase())try{return await Hc(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return E(e,{account:t,domain:jc(r,i),types:Mc,primaryType:`Voucher`,message:n})})(),o=H.from(a);if(!Dc(o.type)&&o.type!==`configurable`)throw Error(`TIP-1034 vouchers require a TIP-1020 primitive or TIP-1166 configurable account signature; received "${o.type}".`);return H.serialize(Ec(o))}async function Wc(e,t,n,r,i){let a=Vc(t)?await t.sign({hash:Pc(r,i,n),raw:!0}):await E(e,{account:t,domain:jc(r,i),types:Nc,primaryType:`CloseAuthorization`,message:n}),o=H.from(a);if(!Dc(o.type)&&o.type!==`configurable`)throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive or TIP-1166 configurable account signature; received "${o.type}".`);return H.serialize(Ec(o))}function Gc(e,t,n,r,i={}){try{let a=Ic(e,t,n);return Lc(n.signature,a,r,i)}catch{return!1}}function Kc(e){return typeof e==`object`&&!!e}function qc(e){return typeof e==`string`&&d(e,{strict:!1})?e:void 0}function Jc(e){return qc(e.accessKeyAddress)}function Yc(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(M.random(8))%e)}function Xc(e){return Jc(e)??e.address}function Zc(e){return Qc(e)!==void 0}function Qc(e){let t=Jc(e);if(t===void 0)return Bc(e)?e:void 0;let n=e.delegate;if(n&&Bc(n)&&n.address.toLowerCase()===t.toLowerCase())return n}async function $c(e,t){let n=Qc(t);if(!n)return M.random(32);let{config:r}=n,i=await V.accounts.getConfigCommitment(e,{account:n.address}),a=r?me.getCommitment(r):void 0;if(BigInt(i)!==0n){if(a&&a.toLowerCase()!==i.toLowerCase())throw Error(`Configurable account ${n.address} holds a config whose commitment ${a} does not match its on-chain commitment ${i}. Use the account's current config.`);return i}if(!a||BigInt(r.version??0n)!==0n)throw Error(`Configurable account ${n.address} is not registered, so it needs its version-zero config to open a channel.`);return a}function el(e,t){let n=$o(e);if(n)try{let i=r({abi:wc,data:n});if(i.errorName!==`SignerConfigChanged`&&i.errorName!==`RootKeyRetired`)return;let[a]=i.args;return a.toLowerCase()===t.signer.toLowerCase()?new dt({cause:e,channelId:t.channelId,reason:i.errorName,signer:a}):void 0}catch{return}}async function tl(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return ts({account:n},()=>b(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}}))}async function nl(e,t){return await T(e,t)}function rl(e,t,n=!1){let r=e.request.methodDetails,i=Kc(r)?qc(r.escrowContract)??qc(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!al(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!al(i,a)?i:a}function il(e,t,n,r){return dn({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${t.descriptor?.payer??r.address}`})}function al(e,t){return e.toLowerCase()===t.toLowerCase()}function ol(e,t){let n=Qc(e);if(!n?.config)return;let{config:r}=n;if(me.getCommitment(r).toLowerCase()!==t.salt.toLowerCase()&&(BigInt(r.version??0n)!==0n||me.getAddress(r).toLowerCase()!==n.address.toLowerCase()))throw Error(`Configurable account ${n.address} holds a config that does not match the channel's opening commitment (salt ${t.salt}), so it cannot sign a voucher the channel settles. Sign with the config the channel opened with, or close the channel and open a new one.`)}async function sl(e,t,n,r,i,a=hc){let o=_c({...n,chainId:i,escrow:a}),s=Zs(r);ol(t,n);let c=await Uc(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function cl(e,t,n,r,i,a=hc){let o=await sl(e,t,n,r,i,a),s=await Wc(e,t,{channelId:o.channelId,cumulativeAmount:Zs(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function ll(e,t,n){let r=Xc(t),a=n.escrow??`0x4d50500000000000000000000000000000000000`,o=n.operator??`0x0000000000000000000000000000000000000000`,s=n.salt??await $c(e,t),c=Zs(n.deposit),l=Zs(n.initialAmount),u=i({abi:wc,functionName:`open`,args:[n.payee,o,n.token,c,s,r]}),d=await nl(e,await tl(e,{account:t,calls:[...n.prefixCalls??[],{to:a,data:u}],feePayer:n.feePayer,feeToken:n.feeToken??n.token,validAfter:Yc()})),f=ue.deserialize(d),p={authorizedSigner:r,expiringNonceHash:bc(yc({...n.feePayer?{feePayer:!0}:{},transaction:f}),{sender:t.address}),operator:o,payee:n.payee,payer:t.address,salt:s,token:n.token},m=_c({...p,chainId:n.chainId,escrow:a});return{action:`open`,type:`transaction`,channelId:m,transaction:d,signature:await Uc(e,t,{channelId:m,cumulativeAmount:l},a,n.chainId),descriptor:p,cumulativeAmount:l.toString(),authorizedSigner:p.authorizedSigner}}async function ul(e,t,n,r,a,o,s=hc,c=[],l=n.token){let u=_c({...n,chainId:a,escrow:s}),d=Zs(r);return{action:`topUp`,type:`transaction`,channelId:u,transaction:await nl(e,await tl(e,{account:t,calls:[...c,{to:s,data:i({abi:wc,functionName:`topUp`,args:[n,d]})}],feePayer:o,feeToken:l,validAfter:Yc()}).catch(e=>{throw el(e,{channelId:u,signer:gc(n)})??e})),descriptor:n,additionalDeposit:d.toString()}}function dl(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Q(e){return dl({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function fl(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Q(t),t)},delete(t){e.delete(t)}}}const pl=new WeakMap,ml=new WeakMap;function hl(e,t){ml.set(e,ml.get(t)??t)}async function gl(e,t,n){let r=pl.get(e);r||(r=new Map,pl.set(e,r));let i=(r.get(t)??Promise.resolve()).catch(()=>{}).then(n);r.set(t,i);try{return await i}finally{r.get(t)===i&&r.delete(t)}}function _l(e,t,n){return gl(ml.get(e)??e,`funding:${t}`,n)}async function vl(e,t){await gl(e,`write:${Q(t)}`,async()=>{let n=await e.get(Q(t));if(n?.origin!==void 0){if(t.origin!==void 0&&t.origin!==n.origin)throw Error(`SessionManager: stored channel origin mismatch`);t.origin=n.origin}if(n?.uncertainTopUp){if(n.channelId!==t.channelId)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);t.uncertainTopUp=!0}await e.set(t)})}async function yl(e,t){await gl(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}const bl=2n**96n-1n;function xl(e){if(e<0n||e>bl)throw new W({reason:`amount exceeds uint96 range`})}async function Sl(e,t,n=hc){let{cumulativeAmount:r,descriptor:i,signature:a}=t;return x(e,{address:n,abi:wc,functionName:`verifyVoucher`,args:[Tl(i),r,a]})}async function Cl(e,t,n=hc,r){return wl(await x(e,{address:n,abi:wc,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function wl(e){return xl(e.settled),xl(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}function Tl(e){return{payer:e.payer,payee:e.payee,operator:e.operator,token:e.token,salt:e.salt,authorizedSigner:e.authorizedSigner,expiringNonceHash:e.expiringNonceHash}}const El=G.custom(e=>typeof e==`string`&&d(e,{strict:!1})),Dl=G.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),Ol=G.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),kl=G.object({authorizedSigner:El,expiringNonceHash:Dl,operator:El,payee:El,payer:El,salt:Dl,token:El}),Al=bn(G.object({acceptedCumulative:G.string(),chainId:G.number(),channelId:Dl,closeRequestedAt:G.optional(G.string()),deposit:G.string(),descriptor:kl,escrow:El,highestVoucher:G.optional(G.object({channelId:Dl,cumulativeAmount:G.string(),signature:Ol})),requiredCumulative:G.string(),settled:G.string(),spent:G.string(),units:G.optional(G.number())}));function jl(e){return Al.encode(e)}function Ml(e){return Al.decode(e)}const Nl={status:`idle`};function Pl(e){return{status:`active`,...e}}function Fl(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:Rl(e.challengeId,t.snapshot),effects:[]}:$(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Zl({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:zl(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:$(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:eu(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?Ll({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:zl(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:zl(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 Il(e,t){let n=Fl(e.state,t);return e.state=n.state,n}function Ll(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 Rl(e,t){return Pl({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function zl(e,t,n,r){return Pl({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 Bl(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function Vl(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`);Bl({cumulativeAmount:i,maxVoucherCumulative:n}),Bl({cumulativeAmount:a,maxVoucherCumulative:n})}function Hl(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;Vl({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function Ul(e,t){return typeof e==`bigint`?e:g(e,t)}function Wl(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(Kl(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 Gl(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;Bl({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 Kl(e,t){Bl({cumulativeAmount:e,maxVoucherCumulative:t??null})}function ql(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 Jl(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function Yl(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!Ys(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>Jl({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function Xl(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=Xs(r),s=Xs(a.spent);return o===void 0||s===void 0||!Ys(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function Zl(e){return Pl({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 Ql(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:Nl}}function $l(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=Hl({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&Il(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function eu(e,t){return Pl({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function tu(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=Xs(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 nu(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 Fl(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function ru(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 iu(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 au(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(fc()),e.waitForCloseReady()))(),a=BigInt(i.spent);Yl({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=>Xl({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(dc(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}function ou(e){return`cumulativeAmount`in e}function su(e){if(ou(e))return BigInt(e.cumulativeAmount)}async function cu(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await vl(e.store,t):await yl(e.store,Q(t)),e.notifyUpdate(t)}async function lu(e,t,n){let r=su(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 cu(e,i))}const uu=G.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),du=G.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),fu=G.object({account:G.optional(G.custom()),autoSwap:G.optional(G.custom()),action:G.optional(G.enum([`open`,`topUp`,`voucher`,`close`])),channelId:G.optional(du),cumulativeAmount:G.optional(K()),cumulativeAmountRaw:G.optional(G.string()),transaction:G.optional(uu),descriptor:G.optional(G.custom()),additionalDeposit:G.optional(K()),additionalDepositRaw:G.optional(G.string()),depositRaw:G.optional(G.string())});function pu(e){return e?.action!==void 0}function mu(e){return pu(e)&&e.descriptor!==void 0}function hu(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 g(i,t)}function gu(e,t,n,r){let i=hu(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function _u(e){return typeof e==`object`&&!!e}function vu(e){return typeof e==`string`&&d(e,{strict:!1})?e:void 0}function yu(e){let t=e.request.methodDetails;return _u(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:vu(t.escrowContract),escrow:vu(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:vu(t.feeToken),operator:vu(t.operator),configurableVouchers:typeof t.configurableVouchers==`boolean`?t.configurableVouchers:void 0,sessionSnapshot:rt(t,tt.sessionSnapshot)}:{}}function bu(e,t){if(typeof e==`string`&&d(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function xu(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function Su(e){return typeof e==`string`?e:void 0}async function Cu(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=yu(n);(o.chainId!==void 0||i?.length===0)&&bo(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});yo(c,s);let l=s??c.chain?.id;if(bo(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=rl(n,r,t),d=bu(n.request.recipient,`recipient`),f=bu(n.request.currency,`currency`);return{amount:xu(n.request.amount),challenge:n,chainId:l,client:c,...o.configurableVouchers===void 0?{}:{configurableVouchers:o.configurableVouchers},escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:dl({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:Su(n.request.suggestedDeposit),token:f}}async function wu(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=Cl}=e,o=_c({...r,chainId:i.chainId,escrow:i.escrow});Tu({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 Tu(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(!al(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!al(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!al(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!al(gc(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function Eu(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function Du(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=hu(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function Ou(e){let{account:t,client:n,readChannelState:r,snapshot:i,verifyVoucherOnChain:a=Sl}=e,o=i.highestVoucher;if(!o)throw Error(`session snapshot is missing its highest signed voucher`);if(o.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let s=BigInt(i.acceptedCumulative),c=BigInt(o.cumulativeAmount),l=BigInt(i.requiredCumulative),u=BigInt(i.deposit),d=BigInt(i.settled),f=BigInt(i.spent);if(c!==s)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(f>s)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(d>u)throw Error(`session snapshot settled amount exceeds deposit`);let p={channelId:o.channelId,cumulativeAmount:c,signature:o.signature},m=gc(i.descriptor),h=Zc(t);if(!(Gc(i.escrow,i.chainId,p,m,h?{configurable:!0,openingCommitment:i.descriptor.salt}:{})||h&&await a(n,{descriptor:i.descriptor,cumulativeAmount:c,signature:p.signature},i.escrow).catch(()=>!1)))throw Error(`session snapshot highest voucher signature is invalid`);let g=await wu({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:Xc(t),token:i.descriptor.token},readChannelState:r}),_=[s,l,g.state.settled].reduce((e,t)=>t>e?t:e,0n);if(_>g.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:g.channelId,cumulativeAmount:_,deposit:g.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:f}}function ku(e,t){return al(e.address,t.payer)?al(Xc(e),gc(t)):!1}function Au(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(pu(r)){if(!mu(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=Eu({context:r,snapshot:o.snapshot});return!n&&s&&ku(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&ku(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 ju(e,t,n=!1){switch(e.type){case`open`:return Pu(e,t,n);case`recover`:return Fu(e,t);case`voucher`:return Iu(e,t);case`manual`:return Lu(e,t,n)}}async function Mu(e,t){if(e)return await Oo(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function Nu(e,t){let{account:n,amount:r,chainId:i,client:a,token:o}=t;if(e||!zo({chainId:i,currency:o}))return;let s=await Ko(a,{account:n,amount:r,chainId:i});if(s)throw s}async function Pu(e,t,n){let{account:r,resolved:i}=e;if(Zc(r)&&i.configurableVouchers!==!0)throw new ut({signer:r.address});let a=Wl({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw});await Nu(n,{account:r.address,amount:a,chainId:i.chainId,client:i.client,token:i.token});let o=await ll(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 Mu(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await cu(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function Fu(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await wu({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:Xc(n),token:o.token}}),l=Du({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`);Kl(l,a);let u=await sl(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await cu(t,{...d?.channelId===c.channelId&&d.uncertainTopUp?{uncertainTopUp:!0}:{},channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function Iu(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;Kl(a,e.maxDeposit);let o=await sl(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await cu(t,r),o}async function Lu(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=_c({...s,chainId:o.chainId,escrow:o.escrow});Tu({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:Xc(r),token:o.token});let l=await Ru({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await lu(t,o.key,l),l}async function Ru(e,t){switch(e.context.action){case`open`:return zu(e);case`topUp`:return Bu(e,t);case`voucher`:return Vu(e);case`close`:return Hu(e)}}async function zu(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=gu(r,i,`cumulativeAmount`,`open`),c=await sl(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 Bu(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=gu(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:(await Nu(t,{account:n.address,amount:c,chainId:s.chainId,client:s.client,token:s.token}),ul(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await Mu(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken))}function Vu(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return sl(a.client,t,i,gu(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function Hu(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return cl(a.client,t,i,gu(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}const Uu={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function Wu(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=Uu.CLOSED,r=null}if(a.type===`open`&&(i=Uu.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 Gu(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function Ku(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=Ul(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 qu(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:eu(s,u)}:i?{channel:u,state:Zl({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function Ju(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=Gu(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,headers:e.headers,channelId:e.expectedChannelId,deposit:t.deposit,requiredCumulative:t.requiredCumulative,...e.signal?{signal:e.signal}:{}});let n=e.getChannel();if(!n||n.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`missing-channel`};let r=n.cumulativeAmount>t.requiredCumulative?n.cumulativeAmount:Zs(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function Yu(e){return e.method===$e.tempo&&e.intent===et.session}function Xu(e){return Yu(e)&&rt(e.request.methodDetails,tt.sessionProtocol)===nt.v2}function Zu(e){return rt(e.request.methodDetails,tt.sessionSnapshot)}function Qu(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return Mi({...t,redirect:`manual`,headers:{...Da(i),...Da(t?.headers)}},Zt(r),n)}function $u(e){return e instanceof Request||typeof e==`object`&&!!e&&!(e instanceof URL)&&typeof e.url==`string`&&typeof e.method==`string`&&typeof e.clone==`function`}function ed(e){try{let t=typeof location>`u`?void 0:location.href,n=$u(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function td(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function nd(e){let t=await e.text().catch(()=>``);if(!t)return``;if(!e.headers.get(`Content-Type`)?.includes(`application/problem+json`))return t;try{return JSON.parse(t).detail??t}catch{return t}}var rd=class extends Error{constructor(e){let t=e instanceof Error||e instanceof DOMException?e.message:String(e);super(`${t}; payment outcome unknown`),this.name=`UncertainFundingError`}};async function id(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);if(t.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let r=await ad({challenge:e.challenge,context:{action:`topUp`,...e.autoSwap===void 0?{}:{autoSwap:e.autoSwap},channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,headers:e.headers,input:e.input,signal:e.signal}).catch(async n=>{throw n instanceof rd&&(t.uncertainTopUp=!0,await e.onUncertainFunding?.(t)),n});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(U.paymentReceipt);return i?sc(i):void 0}async function ad(e){let t=async t=>{e.signal?.throwIfAborted();let n=await e.createSessionCredential(t,e.context);e.signal?.throwIfAborted();let r=new AbortController,i=()=>r.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,i,{once:!0});let a=setTimeout(()=>r.abort(new DOMException(`Session management request timed out; payment outcome unknown`,`TimeoutError`)),3e4),o,s=new Promise((e,t)=>{o=()=>t(r.signal.reason),r.signal.addEventListener(`abort`,o,{once:!0})});try{return await Promise.race([e.fetch(ed(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:kd(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new rd(t):t}finally{clearTimeout(a),e.signal?.removeEventListener(`abort`,i),r.signal.removeEventListener(`abort`,o)}},n=await t(e.challenge);if(n.status!==402)return n;let r=Wt(n).find(Xu);return r?t(r):n}async function od(e){let t=sd({channel:e.getChannel(),response:e.response});if(!t)return;let{channel:n,challenge:r,snapshot:i}=t;e.setChallenge(r);let a=BigInt(i.requiredCumulative),o=n.cumulativeAmount;await e.topUpIfNeeded({challenge:r,input:e.input,headers:e.init?.headers,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a,signal:e.init?.signal??(e.input instanceof Request?e.input.signal:void 0)});let s=e.getChannel();if(!s?.descriptor||s.channelId!==i.channelId)return;let c=s.cumulativeAmount>a?s.cumulativeAmount:a,l=()=>e.restoreCumulative(i.channelId,o),u;try{let t=await e.createSessionCredential(r,{action:`voucher`,channelId:i.channelId,descriptor:s.descriptor,cumulativeAmountRaw:c.toString()});u=await e.fetch(e.input,Qu(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(U.paymentReceipt)&&await l(),u}function sd(e){let t=Wt(e.response).find(Xu);if(!t)return;let n=Zu(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function cd(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=$u(e.lastUrl)?e.lastUrl:void 0,i=r?{cache:r.cache,credentials:r.credentials,integrity:r.integrity,keepalive:r.keepalive,mode:r.mode===`navigate`?`same-origin`:r.mode,referrer:r.referrer,referrerPolicy:r.referrerPolicy}:void 0,a=async(a,o=!1)=>{t=a,n=(o?e.resolveSignedCloseAmount?.(a):void 0)??e.signedCloseAmount;let s=await e.createSessionCredential(a,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(r?ed(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:kd(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=Wt(o).find(Xu);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await nd(o),t=o.headers.get(U.wwwAuthenticate)??``;throw Error(`Close request failed with status ${o.status}${e?`: ${e}`:``}${t?` [${U.wwwAuthenticate}: ${t}]`:``}`)}let s=o.headers.get(U.paymentReceipt);if(!s)return;let c=sc(s);if(!c.txHash||!M.validate(c.txHash,{strict:!0})||M.size(c.txHash)!==32||!Xl({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:0n,receipt:c}))throw Error(`Session close response included a mismatched payment receipt.`);return c}async function ld(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...Da(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!cc(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),ud(e,c,{onReceipt:r,signal:o},n,s.headers)}function ud(e,t,n,r,i){if(!cc(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return dd({onNeedVoucher:t=>gd({challenge:a,driver:r,headers:i,input:e,signal:n?.signal},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*dd(e){for await(let t of fd(e))t.data!==void 0&&(yield t.data)}async function*fd(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=pd(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=lc(i.replace(/\r\n|\r/g,`
10
+ `));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,e.signal);break;case`payment-receipt`:e.onReceipt(s.data)}}if(a)break}}finally{e.signal?.removeEventListener(`abort`,a),i||await t.cancel().catch(()=>void 0),t.releaseLock()}}function pd(e,t){for(let n=0;n<e.length;n++){let r=md(e,n,t);if(!r)continue;let i=md(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function md(e,t,n){return e[t]===`
11
11
  `?1:e[t]===`\r`?e[t+1]===`
12
- `?2:t+1===e.length&&!n?0:1:0}function cd(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=ad({...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 ld(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await Vu({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,headers:e.headers,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await Qu({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,headers:e.headers,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function ud(e){let t=new URL(e.input.toString()),n=Ju(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=Ot(r).find(Uu);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 dd(e){e.signal?.throwIfAborted();let t=await ud(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function fd(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:Wt(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:Zs(t)}}function pd(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function md(e){if(!pd(e))return`received mismatched payment-close-ready frame`;let t=Us(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 hd(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!pd(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!Ul({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function gd(e){let{challenge:t,credential:n,options:r,WebSocket:i,wsUrl:a}=e,o=r?.signal;o?.throwIfAborted();let s=new i(a,r?.protocols),c=fd({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=Lu(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===Iu.CONNECTING||s.readyState===Iu.OPEN)&&s.close(3008,t)},d=()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),s.close()};s.addEventListener(`close`,t=>{o?.removeEventListener(`abort`,d),c.socket=null,c.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),l.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),s.addEventListener(`error`,()=>{l.emit(`error`,{type:`error`})}),s.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await vd({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await _d(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(ic(n)),await e.waitForReceipt(),l.socket}function _d(e,t,n,r){return new Promise((i,a)=>{let o=()=>{e.removeEventListener(`open`,s),e.removeEventListener(`error`,c),e.removeEventListener(`close`,c),r?.removeEventListener(`abort`,l)},s=()=>{o(),t(`open`,{type:`open`}),i()},c=()=>{o(),a(Error(`WebSocket connection to ${n} failed to open.`))},l=()=>{o(),a(r?.reason)};e.addEventListener(`open`,s,{once:!0}),e.addEventListener(`error`,c,{once:!0}),e.addEventListener(`close`,c,{once:!0}),r?.addEventListener(`abort`,l,{once:!0}),r?.aborted&&l()})}async function vd(e){let t=oc(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`:yd(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 bd(e,t.data);return;case`payment-receipt`:xd(e,t.data);return}}function yd(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=md({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 bd(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 Vu({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(ic(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function xd(e,t){let n=hd({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,expectedCloseAmount:e.socketState.expectedCloseAmount,receipt:t});if(n){e.failSocketFlow(n);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleReceipt(t)}function Sd(e,t,n,r){let i=Ft(e),a=new Headers;if(i.toLowerCase()!==H.authorization.toLowerCase()){let e=new Headers(r).get(H.authorization)??(n instanceof Request?n.headers.get(H.authorization):null);e&&!e.startsWith(`${$e.payment} `)&&a.set(H.authorization,e)}return a.set(i,t),a}const Cd=new WeakMap;async function wd(e,t){let n=Cd.get(e)??new Map;Cd.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 Td(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function Ed(e,t,n){try{let r=e.response?.headers.get(H.paymentReceipt);if(r){let e=ec(r);if(e.challengeId===t.id&&Td(n,e))return!0}}catch{}return e.challenges?.some(e=>Uu(e)?Td(n,Wu(e)):!1)??!1}function Dd(e){let{allowedChainIds:t,currencies:n,decimals:r,expectedRecipients:i,maxAmount:a,maxAtomicAmount:o}=e;if((a!==void 0||o!==void 0)&&n===void 0)throw Error(`Tempo session maxAmount and maxAtomicAmount require currencies.`);for(let e of n??[])Od(a,typeof e==`string`?r:e.decimals);return{chainId:t?.length===1?t[0]:void 0,currencies:n,decimals:r,expectedRecipients:i?new Set(i.map(e=>e.toLowerCase())):void 0,maxAmount:a,maxAtomicAmount:o===void 0?void 0:BigInt(o)}}function Od(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo session maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo session maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return g(e,t)}}function kd(e,t,n){let r=e.currencies?ke(e.currencies,t.currency,{chainId:t.methodDetails?.chainId??n??e.chainId,decimals:e.decimals}):void 0;if(e.currencies&&!r)throw Error(`Tempo session currency is not allowed: ${t.currency}.`);if(e.expectedRecipients&&(!t.recipient||!e.expectedRecipients.has(t.recipient.toLowerCase())))throw Error(`Unexpected session recipient: ${t.recipient}`);let i=BigInt(t.amount);if(e.maxAtomicAmount!==void 0&&i>e.maxAtomicAmount)throw Error(`Tempo session amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0&&i>Od(e.maxAmount,r?.decimals))throw Error(`Tempo session amount exceeds maxAmount.`)}function Ad(e,t){try{return kd(e,t),!0}catch{return!1}}function jd(e){return typeof e==`object`&&!!e&&e.action===`close`}function Md(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:f}=e,p=Dd(e),m=uo({chain:ne,getClient:c,rpcUrl:Sr}),h=oo({account:t}),_=(e,t)=>{let n=(p.currencies?ke(p.currencies,e.currency,{chainId:e.methodDetails?.chainId??t??p.chainId,decimals:a}):void 0)?.decimals??a??6;return{decimals:n,maxDeposit:l===void 0?void 0:g(l,n),topUpAmount:u===void 0?void 0:g(u,n)}};l!==void 0&&g(l,6),u!==void 0&&g(u,6);let v=e.origin===void 0?void 0:new URL(e.origin);if(v&&![`http:`,`https:`].includes(v.protocol))throw Error(`Session origins require HTTP or HTTPS`);let y=i??al(),b={store:y,notifyUpdate:e=>d?.(e)},x=async(e,t,n)=>{let r=h(e.client,t),i=t?.action?t.descriptor:n?.descriptor??yu({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:lc(i)}:{}}})??r},S=async(e,t,n)=>{let{decimals:r,maxDeposit:i}=_(e.challenge.request,e.chainId);return Cu({account:await x(e,t,n),entry:n,context:t,decimals:r,maxDeposit:i,resolved:e})},C=pn(bs,{canHandleChallenge:({challenge:e,context:t})=>Uu(e)&&(jd(t)||t===ai||Ad(p,e.request)),context:au,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&kd(p,t.request);let a=await gu({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m});i?.action!==`close`&&t.request.methodDetails?.chainId===void 0&&kd(p,t.request,a.chainId);let c=na(e),l=sa(e)??v?.origin;if(l!==void 0&&(l===`null`||![`http:`,`https:`].includes(new URL(l).protocol)))throw Error(`Session payments require an HTTP or HTTPS origin`);if(v&&l!==v.origin)throw Error(`Session channel origin mismatch`);let u={...b,origin:l},d=()=>{};try{let e=!ou(i)&&i?.descriptor===void 0;e&&(d=await wd(y,a.key),c&&(await y.get(a.key))?.opened&&await c.prepare());let n=await y.get(a.key);if(n&&n.origin!==l)throw Error(`Session channel origin mismatch`);if(l&&!n&&a.snapshot&&!i?.descriptor&&!v)throw Error(`Session snapshot recovery requires an explicitly configured origin or descriptor`);let o=await S(a,i,n);if(!e&&c&&o.type===`open`){d=await wd(y,a.key);let e=await y.get(a.key);if(e&&e.origin!==l)throw Error(`Session channel origin mismatch`);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await y.get(a.key)),o=await S(a,i,n))}let s,f=c&&o.type===`open`?{store:{get:e=>y.get(e),async set(e){s=l?{...e,origin:l}:e},delete:e=>y.delete(e)},notifyUpdate(){}}:u,p=await Zc(t,await wu(o,f,So(i?.autoSwap??r,bo)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||Ed(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await y.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await dl(y,e),b.notifyUpdate(e))}return!0}finally{d()}}}else d();return p}catch(e){throw d(),e}}});function w(e,t,n){let r={challenge:e,context:t};return oa(r,Nd(n)),C.createCredential(r)}let T=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>ul(y,Q(n),async()=>{s?.throwIfAborted();let c=await y.get(Q(n));if(c?.channelId===n.channelId&&(n=c),n.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let l=n.deposit>r?n.deposit:r,{maxDeposit:u,topUpAmount:d}=_(t.request,n.chainId),f=Rl({deposit:l,maxDeposit:u,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:d});f>0n&&await Zu({autoSwap:e,additionalDeposit:f,challenge:t,channel:n,channelId:n.channelId,createSessionCredential:(e,t)=>w(e,t,a),onUncertainFunding:async e=>{let t=await y.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await dl(y,n),b.notifyUpdate(n)},fetch:i,input:a,signal:s});let p=l+f;if(p===n.deposit)return;let m=await y.get(Q(n)),h=m?.channelId.toLowerCase()===n.channelId.toLowerCase()?m:n,g={...h,deposit:h.deposit>p?h.deposit:p};await dl(y,g),b.notifyUpdate(g)});return Gi(C,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!Uu(e))return;let c=t===void 0?void 0:au.parse(t);if(ou(c))return;kd(p,e.request);let l=await gu({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),u=await y.get(l.key);if(!u?.opened)return;let d=Nd(i);if(u.origin!==d)throw Error(`Session channel origin mismatch`);let f=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,h=u.cumulativeAmount+Zs(e),g=f?BigInt(f.requiredCumulative):h,_=g>h?g:h,v=f?BigInt(f.deposit):u.deposit,b=v>u.deposit?v:u.deposit;_<=b&&b===u.deposit||!Su(await x(l,c,u),u.descriptor)||await T({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:b,fetch:r,input:i,requiredCumulative:_,signal:a})}),$i(C,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!Uu(e))return u;if(!tc(u))return Xs(Wt(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await gu({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,p=await y.get(f),h={assertVoucherWithinLocalLimit:t=>zl(t,_(e.request,p?.chainId).maxDeposit),createSessionCredential:(e,t)=>w(e,t,c),fetch:i,getChannel:()=>p??null,async topUpIfNeeded({deposit:n,requiredCumulative:r,signal:a}){p&&await T({autoSwap:t===void 0?void 0:au.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return cd({onNeedVoucher:(t,n)=>ld({challenge:e,driver:h,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function Nd(e){let t=new URL(e instanceof Request?e.url:e,globalThis.location===void 0?void 0:globalThis.location.href);if(![`http:`,`https:`].includes(t.protocol))throw Error(`Session payments require an HTTP or HTTPS origin`);return t.origin}const Pd=new WeakMap;function Fd(e,t){Pd.set(e,t)}function Id(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 Ld(e){let t=Id(`close-ready`),n=Id(`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 Rd(e){return e.method===et.tempo&&e.intent===tt.charge}function zd(e){if(!Rd(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Bd(e,t,n){if(!n)return t;let r={...xa(Ku(e)?e.headers:void 0),...xa(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===H.paymentSession.toLowerCase())?t:{...t,headers:{...r,[H.paymentSession]:n}}}function Vd(e,t){return e===void 0?t:{...au.parse(e),...t}}function Hd(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:g(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:g(e.topUpAmount,t),WebSocket:n}}function Ud(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&po(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=Hd(e),i;function a(e){let t=new URL(Ku(e)?e.url:String(e),typeof location>`u`?void 0:location.href);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`SessionManager: session payments require an HTTP origin`);let n=t.origin;if(i!==void 0&&i!==n)throw Error(`SessionManager: session payment origin mismatch`);return i=n,n}let o=Ua(r.fetch),s=Wa(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??(Ku(e)?e.redirect:void 0))===`manual`?`manual`:`error`});if(r.url&&new URL(r.url).origin!==n)throw Error(`SessionManager: session response origin mismatch`);return r};let c=r.fetch;o&&(r.fetch=ni(c,o));let l=uo({chain:ne,getClient:e.client?()=>e.client:e.getClient,rpcUrl:Sr}),u=oo({account:e.account}),d=Gl(),f=e.credentialContext===void 0?void 0:Vd(e.credentialContext,{}),p=Ld({getSocketSession:()=>d.socketSession}),m=e.channelStore??al(),h=new Set,g;async function _(e){let t=await m.get(e);if(t?.opened&&!h.has(t.channelId)){if(t.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return t}}let v=e=>{if(e.origin!==void 0&&e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return e.origin=i,dl(m,e)},y={async get(e){let t=await _(e);return t&&g&&(g.seenExisting.add(e),!g.committed&&!g.created.has(e)&&(g.resumed??=t)),t},async set(e){let t=Q(e);e.opened&&h.delete(e.channelId),g?.trackCreates&&!g.seenExisting.has(t)&&g.created.set(t,e),await v(e)},delete:e=>fl(m,e)};cl(y,m);async function b(e){let t=Q(e),n=await m.get(t);if(e.uncertainTopUp||n?.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);h.add(e.channelId),g?.seenExisting.delete(t),g?.resumed===e&&(g.resumed=void 0),await Promise.resolve(fl(m,t)).catch(()=>void 0)}async function x(){let e=g;if(e?.created.size){for(let[t,n]of e.created){let e=await m.get(t);if(n.uncertainTopUp||e?.channelId===n.channelId&&e.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before discarding the channel.`);h.add(n.channelId),await Promise.resolve(fl(m,t)).catch(()=>void 0)}e.created.clear(),await se(e.committed??e.previous)}}function S(e){let t=it(e.request.methodDetails,nt.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=g;if(!n?.created.size||!d.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&d.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=Xl({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function C(e){return kl(d,e)}function w(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function T(e){let t=g,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit&&!e.uncertainTopUp||(t.resumed=void 0,t.committed=Xl({channel:d.channel,spent:d.spent,state:d.state}))}let E=Md({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:y,onChannelUpdate(e){e.channelId!==d.channel?.channelId&&(d.spent=0n),d.channel=e,d.lastChallenge&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}}),ee=Ji(E);ee&&Gi(E,e=>re(()=>Promise.resolve(ee(e)),e.signal)),ea(E);let te=Cs({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),D=ba({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[E],onChallenge:async(e,t)=>{if(!Hu(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&vt(e)===vt(d.lastChallenge);n&&n.challengesReceived++,!i&&(S(e)||(n?.created.size?await x():r&&await se(n.committed??n.previous)),d.lastChallenge=e,C({type:`challengeReceived`,challengeId:e.id}))}});function O(e,t){let n={challenge:e,context:Vd(f,t)};return i&&oa(n,i),E.createCredential(n)}function k(e){Kl({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:d})}function A(e=d.state.status===`active`?d.state.units:0){!d.channel||!d.lastChallenge||d.state.status!==`active`&&d.state.status!==`withdrawable`&&d.state.status!==`closeRequested`&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:d.channel,spent:d.spent.toString(),units:e})}async function j(t){let r=t.headers.get(H.paymentSessionSnapshot);if(!r)return;let i=Tl(r);po(e.allowedChainIds,i.chainId),Xc({request:{methodDetails:{escrow:i.escrow}}},e.escrow,n);let a=await l({chainId:i.chainId});fo(a,i.chainId);let o=u(a),{entry:s,spent:c}=await xu({account:await e.resolveAccount?.({account:o,chainId:i.chainId,operation:{authority:lc(i.descriptor),kind:`authorizePaymentChannel`}})??o,client:a,snapshot:i});return L(s.cumulativeAmount),await Promise.resolve(y.set(s)).catch(()=>void 0),d.channel=s,d.spent=c,s}async function M(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=Ku(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=Ku(t)?t.url:t,l={...s,method:`HEAD`,headers:{...xa(i),...xa(n?.headers),[H.acceptPayment]:`${et.tempo}/${tt.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await j(t);let n=Ot(t).find(Rd);if(!n||!zd(n))return;let i=new URL(String(c),typeof location<`u`?location.href:void 0);if(t.url&&new URL(t.url).origin!==i.origin)return;la(n,i,e.trustedTempoProofRealms);let a=await te.createCredential({challenge:n,context:{}}),o=await r.fetch(c,Ei({...l,redirect:`manual`},Ft(n),a));return o.ok?await j(o):void 0}catch{return}}function N(e,t){let n=d.socketSession;return Jl({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:d.channel?.channelId===t?d.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:d.spent,tickCost:n?.tickCost})}function P(e,t){let n=Wu(t);if(!n)return;if(uc({...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 F(e,t){let n=P(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(d.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>d.spent&&(d.spent=i),n}function I(e,t=e.challenge,n=!1){let r=(n?F(e,t):P(e.channel,t))?.acceptedCumulative??N(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return L(r),r.toString()}function L(e){Nl({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let R,z;async function re(e,t){if(z)throw z;for(;;){let e=R;if(!e)break;if(!t)await e;else{t.throwIfAborted();let n;try{await Promise.race([e,new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0})})])}finally{t.removeEventListener(`abort`,n)}}}if(t?.throwIfAborted(),z)throw z;let n=e();R=n;try{return await n}catch(e){throw e instanceof Xu&&(z=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{R===n&&(R=void 0)}}async function ie(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return ul(m,Q(d.channel),async()=>{let{knownDeposit:t,...n}=e,i=d.channel?await y.get(Q(d.channel)):void 0;if(i?.channelId===e.channelId&&i.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let a=await Zu({...n,channel:d.channel,createSessionCredential:O,fetch:r.fetch,onUncertainFunding:async e=>{let t=await y.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};d.channel?.channelId===e.channelId&&(d.channel=n),await y.set(n),T(n)}});k(a);let o=d.channel,s=Bu({additionalDeposit:e.additionalDeposit,channel:d.channel,channelId:e.channelId,challengeId:d.lastChallenge?.id,currentState:d.state,knownDeposit:t,receipt:a,spent:d.spent});if(s?.channel&&d.lastChallenge){let e=s.channel;for(;;){await y.set(e);let t=d.channel;if(t===o)break;if(!t)return a;let n=s.channel;e=t.channelId===n.channelId?{...t,deposit:t.deposit>n.deposit?t.deposit:n.deposit,cumulativeAmount:t.cumulativeAmount>n.cumulativeAmount?t.cumulativeAmount:n.cumulativeAmount}:t,o=t}if(e.channelId!==s.channel.channelId)return a;d.channel=e,C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}return a})}async function ae(e){return re(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=Rl({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 ie({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function oe(e,t){let n=Yl({channel:d.channel,channelId:e,challengeId:d.lastChallenge?.id,cumulativeAmount:t,spent:d.spent,state:d.state});n&&d.channel&&(C({type:`activated`,challengeId:n.challengeId,entry:d.channel,spent:n.spent,units:n.units}),await v(d.channel))}async function se(e){let t=Zl(e,d.channel);d.channel=t.channel,d.spent=t.spent,d.state=t.state,d.channel?.opened&&await v(d.channel)}function ce(e,t=!0){let n=e.headers.get(H.paymentReceipt),r=n?ec(n):null;return t&&k(r),Object.assign(e,{receipt:r,challenge:d.lastChallenge,channelId:d.channel?.channelId??null,cumulative:d.channel?.cumulativeAmount??0n})}async function B(e,t){if(t?.[ma])return ce(await r.fetch(e,ha(t)),!1);if(g)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);a(e),d.lastUrl=e,d.lastHeaders=t?.headers;let n=Xl({channel:d.channel,spent:d.spent,state:d.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};g=i;try{await M(e,t),i.trackCreates=!0;let a=Bd(e,t,d.channel?.opened?d.channel.channelId:void 0);f&&(a={...a,context:f});let o=!n.channel?.opened;async function s(){let n=i.resumed;return!o||!n?!1:(o=!1,await b(n),a=Bd(e,t,void 0),!0)}for(;;){let t;try{t=await D(e,a)}catch(e){if(i.created.size?await x():await se(i.committed??n),await s())continue;throw e}let o=ce(t),c=!1;if(o.status===402){let t=await $u({input:e,init:a,response:o,createSessionCredential:O,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:oe,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:ae});t&&(c=!0,o=ce(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await x():await se(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function le(e){let t=await td({createSessionCredential:O,fetch:r.fetch,getMinimumSpent:()=>d.spent,headers:d.lastHeaders,lastUrl:d.lastUrl,resolveSignedCloseAmount:t=>I(e,t,!0),signedCloseAmount:I(e),setChallenge(e){d.lastChallenge=e},target:e});return t&&(A(),C({type:`closeStarted`}),C({type:`closed`,receipt:t})),t}let ue={createSessionCredential:O,doFetch:B,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:L,acceptReceipt(e){k(e)},topUpIfNeeded:ae},de={get channelId(){return d.channel?.channelId},get cumulative(){return d.channel?.cumulativeAmount??0n},get opened(){return d.channel?.opened??!1},get state(){return d.state},fetch:B,async topUp(e){let t=zu({amount:e,assertVoucherWithinLocalLimit:L,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return re(async()=>{if(d.channel?.channelId!==t.channelId||d.lastChallenge!==t.challenge||d.lastUrl!==t.input)throw Error(`Session changed while waiting to top up`);let n=zu({amount:e,assertVoucherWithinLocalLimit:L,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return ie({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){if(t?.[ma])throw Error(`SessionManager.sse requires payment; use fetch for unpaid streams.`);return nd(e,t,ue)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=Ju(e);a(n);let i=t?.signal?{signal:t.signal}:void 0;await M(n,i);let o=d.channel?.opened?d.channel.channelId:void 0,{challenge:s,credential:c,httpUrl:l,wsUrl:u}=await dd({async createSessionCredential(e,i){return d.lastChallenge=e,await qi(E,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),O(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){d.lastUrl=e.toString()},probeInit:Bd(n,i,o),signal:t?.signal});return d.lastChallenge=s,gd({challenge:s,credential:c,httpUrl:l,WebSocket:r.WebSocket,wsUrl:u,options:t,createSessionCredential:O,getChannel:()=>d.channel,setSocketSession(e){d.socketSession=e},async refreshChallenge(){let e=await ud({fetch:r.fetch,input:l,probeInit:Bd(l,i,d.channel?.opened?d.channel.channelId:void 0),signal:t?.signal});return d.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:L,acceptReceipt:k,rejectCloseReady:p.rejectCloseReady,rejectReceipt:p.rejectReceipt,settleCloseReady:p.settleCloseReady,settleReceipt:p.settleReceipt,topUpIfNeeded:ae,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=Bl({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===Iu.OPEN){let r=await Ql({activeSocket:n,createSessionCredential:O,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return A(),C({type:`closeStarted`}),C({type:`closed`,receipt:r}),r}return le(t)}};return Fd(de,{consumeSseResponse(e,t,n){let r=a(e);if(t.url&&new URL(t.url).origin!==r)throw Error(`SessionManager: session response origin mismatch`);return rd(e,t,n,ue)},rehydrate({channel:e,challenge:t,input:n,spent:r}){let i=a(n);if(e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!Hu(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.`);L(e.cumulativeAmount);let o=P(e,t),s=o&&o.spent>r?o.spent:r;d.lastUrl=n,d.lastChallenge=t,d.channel=e,d.spent=s,C({type:`challengeReceived`,challengeId:t.id}),C({type:`activated`,challengeId:t.id,entry:e,spent:s.toString(),units:0})}}),de}(function(e){e.serializeSnapshot=wl,e.deserializeSnapshot=Tl})(Ud||={});const Wd=(1n<<64n)-1n,Gd={dev_second:1n,day:86400n,week:604800n};function Kd(e){return e instanceof Date?e:new Date(e)}function qd(e){let t=e.getTime();if(!Number.isFinite(t))throw new Y({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new Y({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new Y({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function Jd(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new Y({reason:`periodCount is invalid`});let t=Gd[e.periodUnit];if(t===void 0)throw new Y({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>Wd)throw new Y({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new Y({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function Yd(e){let{challengeExpires:t,request:n}=e;Jd(n);let r=qd(Kd(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new Y({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function Xd(e){return[{address:uf(e.currency,`currency`),selector:`0x95777d59`,recipients:[uf(e.recipient,`recipient`)]}]}function Zd(e){try{let t=j.fromBytes(O.toBytes(e));if(j.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new Y({reason:`challenge id must encode 32 bytes`})}}async function Qd(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=ef({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:_e.getSignPayload(o)}),c=V.from(s);if(c.type===`keychain`||c.type===`configurable`)throw new Y({reason:`keyAuthorization must use a primitive signature`});return _e.from(o,{signature:V.serialize(yc(c))})}function $d(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new Y({reason:`invalid keyAuthorization payload`});let o=tf(i.signature),s=nf(o);if(rf({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==Zd(n))throw new Y({reason:`keyAuthorization challenge mismatch`});return af(o,a),sf(of(o),a),cf(o.scopes,a),{authorization:o,source:{address:lf(o,s),chainId:r}}}function ef(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return _e.from({address:uf(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:qd(Kd(i.subscriptionExpires)),limits:[{token:uf(i.currency,`currency`),limit:BigInt(i.amount),period:Jd(i)}],scopes:Xd(i),type:t.keyType,witness:Zd(n)})}function tf(e){try{return _e.deserialize(e)}catch(e){throw e instanceof _e.InvalidSignatureTypeError?new Y({reason:`keyAuthorization must use a primitive signature`}):new Y({reason:`invalid keyAuthorization payload`})}}function nf(e){let t=e.signature;if(!t)throw new Y({reason:`keyAuthorization must use a primitive signature`});return t}function rf(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new Y({reason:`keyAuthorization chainId mismatch`});if(t){if(!f(n.address,uf(t.accessKeyAddress,`accessKeyAddress`)))throw new Y({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new Y({reason:`keyAuthorization key type mismatch`})}}function af(e,t){if(Yd({request:t}),e.expiry!==qd(Kd(t.subscriptionExpires)))throw new Y({reason:`keyAuthorization expiry mismatch`})}function of(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new Y({reason:`keyAuthorization must contain exactly one token limit`});return t}function sf(e,t){if(!f(e.token,uf(t.currency,`currency`)))throw new Y({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new Y({reason:`keyAuthorization amount mismatch`});if(e.period!==Jd(t))throw new Y({reason:`keyAuthorization period mismatch`})}function cf(e,t){if(!e||e.length!==1)throw new Y({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=uf(t.currency,`currency`),r=uf(t.recipient,`recipient`),i=new Set;for(let t of e){if(!f(t.address,n))throw new Y({reason:`keyAuthorization call target mismatch`});let e=df(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new Y({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new Y({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!f(t.recipients[0],r))throw new Y({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new Y({reason:`keyAuthorization must allow transferWithMemo`})}function lf(e,t){let n=_e.getSignPayload(e);try{let e=V.extractAddress({payload:n,signature:t});if(!vc(t)||!V.verify(t,{address:e,payload:n}))throw new Y({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof Y?e:new Y({reason:`keyAuthorization signature is invalid`})}}function uf(e,t){if(!d(e))throw new Y({reason:`${t} must be an address`});return e.toLowerCase()}function df(e){return typeof e==`string`?e.toLowerCase():``}const ff=W.object({accessKey:W.optional(W.custom()),account:W.optional(W.custom())});function pf(e={}){let t=uo({chain:z,requireChain:!0,getClient:e.getClient,rpcUrl:Sr}),n=oo({account:e.account});return pn(xs,{context:ff,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??Z.testnet,o=await t({chainId:a});if(o.chain?.id!==a)throw Error(`Subscription chain mismatch: expected ${a}, got ${o.chain?.id??`unknown`}.`);let 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.");hf(r.request),await e.validateRequest?.(r.request);let l=await mf(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=$d({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:_e.serialize(l),type:`keyAuthorization`},request:r.request});if(!f(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return Jt({challenge:r,payload:{signature:_e.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function mf(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await Qd({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:qd(Kd(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:j.fromNumber(BigInt(o.amount)),period:Jd(o)}],scopes:Xd(o),witness:Zd(i)}]});return _e.fromRpc(c.keyAuthorization)}function hf(e){Jd(e),qd(Kd(e.subscriptionExpires))}const gf=Object.assign(Md,{manager:Ud});function _f(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[Cs(e),gf(n)]}(function(e){e.charge=Cs,e.common=_f,e.session=gf,e.subscription=pf})(_f||={});const vf=R.union([R.boolean(),R.literal(`true`).transform(()=>!0),R.literal(`false`).transform(()=>!1)]);async function yf(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}const bf=R.object({allowCustomEscrow:R.optional(vf),autoSwap:R.optional(vf),channel:R.optional(R.coerce.string()),deposit:R.optional(R.union([R.string(),R.number()])),payWith:R.optional(R.string()),slippage:R.optional(R.coerce.number()),tokenIn:R.optional(R.string())}),xf=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`];function Sf(){let t;return Hr({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,s=o.currency,c=Of(i),l=Mf({autoSwap:c.autoSwap??r.autoSwap,payWith:c.payWith??r.payWith,slippage:c.slippage??r.slippage,tokenIn:c.tokenIn}),d=s??``,f=o.decimals??6,p,m,h,g=!1,_=process.env.MPPX_PRIVATE_KEY?.trim()||(wr(a)?void 0:await zr(a).get());if(!_&&wr(a)&&Vf()){g=!0;let t=zf(a);if(t){let i=Dr(r.rpcUrl,{network:r.network});h=e({chain:await Or({network:r.network,rpcUrl:i}),transport:u(i)}),Af({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let a=s?await jr(h,s,t.wallet_address).catch(()=>void 0):void 0;d=a?.symbol??s??``,f=a?.decimals??o.decimals??6}}else if(_)m=me(_);else{let e=Uf();if(e){let t=await zr(e).get();t&&(m=me(t))}if(!m)throw r.account?new _r({code:`ACCOUNT_NOT_FOUND`,message:`Account "${a}" not found.`,exitCode:69}):new _r({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!g&&m){let t=Dr(r.rpcUrl,{network:r.network});h=e({chain:await Or({network:r.network,rpcUrl:t}),transport:u(t)}),Af({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let i=s?await jr(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 Hf(t)}};if(!m||!h)throw new _r({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let v=_f({account:m,...c.allowCustomEscrow===void 0?{}:{allowCustomEscrow:c.allowCustomEscrow},getClient:()=>h,...l===void 0?{}:{autoSwap:l},maxDeposit:(()=>{if(n.intent!==`session`)return;let e=n.request.suggestedDeposit,t=(c.deposit===void 0?void 0:String(c.deposit))??e??(Ar(h.chain)?`10`:void 0);if(!t)throw new _r({code:`MISSING_DEPOSIT`,message:`Session payment requires a deposit. Use -M deposit=<amount> or connect to testnet.`,exitCode:2});return t})()}),y=(()=>{if(!c.channel)return;let e=c.channel,t=Pf(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 Ic(h,m,c,i,a);return Jt({challenge:n,payload:{action:o,channelId:e,...o===`close`?{closeSignature:await Lc(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=Wt(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?` ${X.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
12
+ `?2:t+1===e.length&&!n?0:1:0}function hd(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=fd({...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 gd(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await Ju({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,headers:e.headers,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await ad({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,headers:e.headers,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function _d(e){let t=new URL(e.input.toString()),n=td(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=Wt(r).find(Xu);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 vd(e){e.signal?.throwIfAborted();let t=await _d(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function yd(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:sn(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:ic(t)}}function bd(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function xd(e){if(!bd(e))return`received mismatched payment-close-ready frame`;let t=Xs(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 Sd(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!bd(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!Xl({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function Cd(e){let{challenge:t,credential:n,options:r,WebSocket:i,wsUrl:a}=e,o=r?.signal;o?.throwIfAborted();let s=new i(a,r?.protocols),c=yd({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=Wu(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===Uu.CONNECTING||s.readyState===Uu.OPEN)&&s.close(3008,t)},d=()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),s.close()};s.addEventListener(`close`,t=>{o?.removeEventListener(`abort`,d),c.socket=null,c.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),l.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),s.addEventListener(`error`,()=>{l.emit(`error`,{type:`error`})}),s.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await Td({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await wd(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(dc(n)),await e.waitForReceipt(),l.socket}function wd(e,t,n,r){return new Promise((i,a)=>{let o=()=>{e.removeEventListener(`open`,s),e.removeEventListener(`error`,c),e.removeEventListener(`close`,c),r?.removeEventListener(`abort`,l)},s=()=>{o(),t(`open`,{type:`open`}),i()},c=()=>{o(),a(Error(`WebSocket connection to ${n} failed to open.`))},l=()=>{o(),a(r?.reason)};e.addEventListener(`open`,s,{once:!0}),e.addEventListener(`error`,c,{once:!0}),e.addEventListener(`close`,c,{once:!0}),r?.addEventListener(`abort`,l,{once:!0}),r?.aborted&&l()})}async function Td(e){let t=pc(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`:Ed(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 Dd(e,t.data);return;case`payment-receipt`:Od(e,t.data);return}}function Ed(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=xd({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 Dd(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 Ju({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(dc(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function Od(e,t){let n=Sd({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,expectedCloseAmount:e.socketState.expectedCloseAmount,receipt:t});if(n){e.failSocketFlow(n);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleReceipt(t)}function kd(e,t,n,r){let i=Zt(e),a=new Headers;if(i.toLowerCase()!==U.authorization.toLowerCase()){let e=new Headers(r).get(U.authorization)??(n instanceof Request?n.headers.get(U.authorization):null);e&&!e.startsWith(`${Qe.payment} `)&&a.set(U.authorization,e)}return a.set(i,t),a}const Ad=new WeakMap;async function jd(e,t){let n=Ad.get(e)??new Map;Ad.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 Md(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function Nd(e,t,n){try{let r=e.response?.headers.get(U.paymentReceipt);if(r){let e=sc(r);if(e.challengeId===t.id&&Md(n,e))return!0}}catch{}return e.challenges?.some(e=>Xu(e)?Md(n,Zu(e)):!1)??!1}function Pd(e){let{allowedChainIds:t,currencies:n,decimals:r,expectedRecipients:i,maxAmount:a,maxAtomicAmount:o}=e;if((a!==void 0||o!==void 0)&&n===void 0)throw Error(`Tempo session maxAmount and maxAtomicAmount require currencies.`);for(let e of n??[])Fd(a,typeof e==`string`?r:e.decimals);return{chainId:t?.length===1?t[0]:void 0,currencies:n,decimals:r,expectedRecipients:i?new Set(i.map(e=>e.toLowerCase())):void 0,maxAmount:a,maxAtomicAmount:o===void 0?void 0:BigInt(o)}}function Fd(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo session maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo session maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return g(e,t)}}function Id(e,t,n){let r=e.currencies?Oe(e.currencies,t.currency,{chainId:t.methodDetails?.chainId??n??e.chainId,decimals:e.decimals}):void 0;if(e.currencies&&!r)throw Error(`Tempo session currency is not allowed: ${t.currency}.`);if(e.expectedRecipients&&(!t.recipient||!e.expectedRecipients.has(t.recipient.toLowerCase())))throw Error(`Unexpected session recipient: ${t.recipient}`);let i=BigInt(t.amount);if(e.maxAtomicAmount!==void 0&&i>e.maxAtomicAmount)throw Error(`Tempo session amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0&&i>Fd(e.maxAmount,r?.decimals))throw Error(`Tempo session amount exceeds maxAmount.`)}function Ld(e,t){try{return Id(e,t),!0}catch{return!1}}function Rd(e){return typeof e==`object`&&!!e&&e.action===`close`}function zd(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:f}=e,p=Pd(e),m=vo({chain:te,getClient:c,rpcUrl:Or}),h=mo({account:t}),_=(e,t)=>{let n=(p.currencies?Oe(p.currencies,e.currency,{chainId:e.methodDetails?.chainId??t??p.chainId,decimals:a}):void 0)?.decimals??a??6;return{decimals:n,maxDeposit:l===void 0?void 0:g(l,n),topUpAmount:u===void 0?void 0:g(u,n)}};l!==void 0&&g(l,6),u!==void 0&&g(u,6);let v=e.origin===void 0?void 0:new URL(e.origin);if(v&&![`http:`,`https:`].includes(v.protocol))throw Error(`Session origins require HTTP or HTTPS`);let y=i??fl(),b={store:y,notifyUpdate:e=>d?.(e)},x=async(e,t,n)=>{let r=h(e.client,t),i=t?.action?t.descriptor:n?.descriptor??Eu({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:gc(i)}:{}}})??r},S=async(e,t,n)=>{let{decimals:r,maxDeposit:i}=_(e.challenge.request,e.chainId);return Au({account:await x(e,t,n),entry:n,context:t,decimals:r,maxDeposit:i,resolved:e})},C=yn(Ds,{canHandleChallenge:({challenge:e,context:t})=>Xu(e)&&(Rd(t)||t===di||Ld(p,e.request)),context:fu,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&Id(p,t.request);let a=await Cu({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m});i?.action!==`close`&&t.request.methodDetails?.chainId===void 0&&Id(p,t.request,a.chainId);let c=ca(e),l=pa(e)??v?.origin;if(l!==void 0&&(l===`null`||![`http:`,`https:`].includes(new URL(l).protocol)))throw Error(`Session payments require an HTTP or HTTPS origin`);if(v&&l!==v.origin)throw Error(`Session channel origin mismatch`);let u={...b,origin:l},d=()=>{};try{let e=!pu(i)&&i?.descriptor===void 0;e&&(d=await jd(y,a.key),c&&(await y.get(a.key))?.opened&&await c.prepare());let n=await y.get(a.key);if(n&&n.origin!==l)throw Error(`Session channel origin mismatch`);if(l&&!n&&a.snapshot&&!i?.descriptor&&!v)throw Error(`Session snapshot recovery requires an explicitly configured origin or descriptor`);let o=await S(a,i,n);if(!e&&c&&o.type===`open`){d=await jd(y,a.key);let e=await y.get(a.key);if(e&&e.origin!==l)throw Error(`Session channel origin mismatch`);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await y.get(a.key)),o=await S(a,i,n))}let s,f=c&&o.type===`open`?{store:{get:e=>y.get(e),async set(e){s=l?{...e,origin:l}:e},delete:e=>y.delete(e)},notifyUpdate(){}}:u,p=await il(t,await ju(o,f,ko(i?.autoSwap??r,Do)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||Nd(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await y.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await vl(y,e),b.notifyUpdate(e))}return!0}finally{d()}}}else d();return p}catch(e){throw d(),e}}});function w(e,t,n){let r={challenge:e,context:t};return fa(r,Bd(n)),C.createCredential(r)}let T=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>_l(y,Q(n),async()=>{s?.throwIfAborted();let c=await y.get(Q(n));if(c?.channelId===n.channelId&&(n=c),n.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let l=n.deposit>r?n.deposit:r,{maxDeposit:u,topUpAmount:d}=_(t.request,n.chainId),f=Gl({deposit:l,maxDeposit:u,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:d});f>0n&&await id({autoSwap:e,additionalDeposit:f,challenge:t,channel:n,channelId:n.channelId,createSessionCredential:(e,t)=>w(e,t,a),onUncertainFunding:async e=>{let t=await y.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await vl(y,n),b.notifyUpdate(n)},fetch:i,input:a,signal:s});let p=l+f;if(p===n.deposit)return;let m=await y.get(Q(n)),h=m?.channelId.toLowerCase()===n.channelId.toLowerCase()?m:n,g={...h,deposit:h.deposit>p?h.deposit:p};await vl(y,g),b.notifyUpdate(g)});return Zi(C,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!Xu(e))return;let c=t===void 0?void 0:fu.parse(t);if(pu(c))return;Id(p,e.request);let l=await Cu({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),u=await y.get(l.key);if(!u?.opened)return;let d=Bd(i);if(u.origin!==d)throw Error(`Session channel origin mismatch`);let f=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,h=u.cumulativeAmount+ic(e),g=f?BigInt(f.requiredCumulative):h,_=g>h?g:h,v=f?BigInt(f.deposit):u.deposit,b=v>u.deposit?v:u.deposit;_<=b&&b===u.deposit||!ku(await x(l,c,u),u.descriptor)||await T({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:b,fetch:r,input:i,requiredCumulative:_,signal:a})}),aa(C,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!Xu(e))return u;if(!cc(u))return rc(sn(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await Cu({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,p=await y.get(f),h={assertVoucherWithinLocalLimit:t=>Kl(t,_(e.request,p?.chainId).maxDeposit),createSessionCredential:(e,t)=>w(e,t,c),fetch:i,getChannel:()=>p??null,async topUpIfNeeded({deposit:n,requiredCumulative:r,signal:a}){p&&await T({autoSwap:t===void 0?void 0:fu.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return hd({onNeedVoucher:(t,n)=>gd({challenge:e,driver:h,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function Bd(e){let t=new URL(e instanceof Request?e.url:e,globalThis.location===void 0?void 0:globalThis.location.href);if(![`http:`,`https:`].includes(t.protocol))throw Error(`Session payments require an HTTP or HTTPS origin`);return t.origin}const Vd=new WeakMap;function Hd(e,t){Vd.set(e,t)}function Ud(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 Wd(e){let t=Ud(`close-ready`),n=Ud(`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 Gd(e){return e.method===$e.tempo&&e.intent===et.charge}function Kd(e){if(!Gd(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function qd(e,t,n){if(!n)return t;let r={...Da($u(e)?e.headers:void 0),...Da(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===U.paymentSession.toLowerCase())?t:{...t,headers:{...r,[U.paymentSession]:n}}}function Jd(e,t){return e===void 0?t:{...fu.parse(e),...t}}function Yd(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:g(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:g(e.topUpAmount,t),WebSocket:n}}function Xd(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&bo(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=Yd(e),i;function a(e){let t=new URL($u(e)?e.url:String(e),typeof location>`u`?void 0:location.href);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`SessionManager: session payments require an HTTP origin`);let n=t.origin;if(i!==void 0&&i!==n)throw Error(`SessionManager: session payment origin mismatch`);return i=n,n}let o=Ya(r.fetch),s=Xa(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??($u(e)?e.redirect:void 0))===`manual`?`manual`:`error`});if(r.url&&new URL(r.url).origin!==n)throw Error(`SessionManager: session response origin mismatch`);return r};let c=r.fetch;o&&(r.fetch=ci(c,o));let l=vo({chain:te,getClient:e.client?()=>e.client:e.getClient,rpcUrl:Or}),u=mo({account:e.account}),d=Ql(),f=e.credentialContext===void 0?void 0:Jd(e.credentialContext,{}),p=Wd({getSocketSession:()=>d.socketSession}),m=e.channelStore??fl(),h=new Set,g;async function _(e){let t=await m.get(e);if(t?.opened&&!h.has(t.channelId)){if(t.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return t}}let v=e=>{if(e.origin!==void 0&&e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return e.origin=i,vl(m,e)},y={async get(e){let t=await _(e);return t&&g&&(g.seenExisting.add(e),!g.committed&&!g.created.has(e)&&(g.resumed??=t)),t},async set(e){let t=Q(e);e.opened&&h.delete(e.channelId),g?.trackCreates&&!g.seenExisting.has(t)&&g.created.set(t,e),await v(e)},delete:e=>yl(m,e)};hl(y,m);async function b(e){let t=Q(e),n=await m.get(t);if(e.uncertainTopUp||n?.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);h.add(e.channelId),g?.seenExisting.delete(t),g?.resumed===e&&(g.resumed=void 0),await Promise.resolve(yl(m,t)).catch(()=>void 0)}async function x(){let e=g;if(e?.created.size){for(let[t,n]of e.created){let e=await m.get(t);if(n.uncertainTopUp||e?.channelId===n.channelId&&e.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before discarding the channel.`);h.add(n.channelId),await Promise.resolve(yl(m,t)).catch(()=>void 0)}e.created.clear(),await oe(e.committed??e.previous)}}function S(e){let t=rt(e.request.methodDetails,tt.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=g;if(!n?.created.size||!d.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&d.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=ru({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function C(e){return Il(d,e)}function w(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function T(e){let t=g,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit&&!e.uncertainTopUp||(t.resumed=void 0,t.committed=ru({channel:d.channel,spent:d.spent,state:d.state}))}let E=zd({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:y,onChannelUpdate(e){e.channelId!==d.channel?.channelId&&(d.spent=0n),d.channel=e,d.lastChallenge&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}}),ee=ea(E);ee&&Zi(E,e=>ne(()=>Promise.resolve(ee(e)),e.signal)),oa(E);let D=As({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),O=Ea({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[E],onChallenge:async(e,t)=>{if(!Yu(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&po(e)===po(d.lastChallenge);n&&n.challengesReceived++,!i&&(S(e)||(n?.created.size?await x():r&&await oe(n.committed??n.previous)),d.lastChallenge=e,C({type:`challengeReceived`,challengeId:e.id}))}});function k(e,t){let n={challenge:e,context:Jd(f,t)};return i&&fa(n,i),E.createCredential(n)}function A(e){$l({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:d})}function j(e=d.state.status===`active`?d.state.units:0){!d.channel||!d.lastChallenge||d.state.status!==`active`&&d.state.status!==`withdrawable`&&d.state.status!==`closeRequested`&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:d.channel,spent:d.spent.toString(),units:e})}async function M(t){let r=t.headers.get(U.paymentSessionSnapshot);if(!r)return;let i=Ml(r);bo(e.allowedChainIds,i.chainId),rl({request:{methodDetails:{escrow:i.escrow}}},e.escrow,n);let a=await l({chainId:i.chainId});yo(a,i.chainId);let o=u(a),{entry:s,spent:c}=await Ou({account:await e.resolveAccount?.({account:o,chainId:i.chainId,operation:{authority:gc(i.descriptor),kind:`authorizePaymentChannel`}})??o,client:a,snapshot:i});return R(s.cumulativeAmount),await Promise.resolve(y.set(s)).catch(()=>void 0),d.channel=s,d.spent=c,s}async function N(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=$u(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=$u(t)?t.url:t,l={...s,method:`HEAD`,headers:{...Da(i),...Da(n?.headers),[U.acceptPayment]:`${$e.tempo}/${et.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await M(t);let n=Wt(t).find(Gd);if(!n||!Kd(n))return;let i=new URL(String(c),typeof location<`u`?location.href:void 0);if(t.url&&new URL(t.url).origin!==i.origin)return;ha(n,i,e.trustedTempoProofRealms);let a=await D.createCredential({challenge:n,context:{}}),o=await r.fetch(c,Mi({...l,redirect:`manual`},Zt(n),a));return o.ok?await M(o):void 0}catch{return}}function P(e,t){let n=d.socketSession;return tu({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:d.channel?.channelId===t?d.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:d.spent,tickCost:n?.tickCost})}function F(e,t){let n=Zu(t);if(!n)return;if(_c({...n.descriptor,chainId:n.chainId,escrow:n.escrow}).toLowerCase()!==n.channelId.toLowerCase())throw Error(`close snapshot descriptor does not match its channel ID`);if(n.channelId.toLowerCase()!==e.channelId.toLowerCase())throw Error(`close snapshot channel ID does not match local session`);if(n.chainId!==e.chainId||n.escrow.toLowerCase()!==e.escrow.toLowerCase())throw Error(`close snapshot payment scope does not match local session`);let r=BigInt(n.acceptedCumulative),i=BigInt(n.spent);if(r<0n||i<0n)throw Error(`close snapshot amounts must not be negative`);if(i>r)throw Error(`close snapshot spent exceeds accepted cumulative amount`);if(r>e.cumulativeAmount)throw Error(`close snapshot accepted cumulative exceeds local voucher state`);return{acceptedCumulative:r,spent:i}}function I(e,t){let n=F(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(d.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>d.spent&&(d.spent=i),n}function L(e,t=e.challenge,n=!1){let r=(n?I(e,t):F(e.channel,t))?.acceptedCumulative??P(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return R(r),r.toString()}function R(e){Bl({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let z,B;async function ne(e,t){if(B)throw B;for(;;){let e=z;if(!e)break;if(!t)await e;else{t.throwIfAborted();let n;try{await Promise.race([e,new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0})})])}finally{t.removeEventListener(`abort`,n)}}}if(t?.throwIfAborted(),B)throw B;let n=e();z=n;try{return await n}catch(e){throw e instanceof rd&&(B=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{z===n&&(z=void 0)}}async function re(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return _l(m,Q(d.channel),async()=>{let{knownDeposit:t,...n}=e,i=d.channel?await y.get(Q(d.channel)):void 0;if(i?.channelId===e.channelId&&i.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let a=await id({...n,channel:d.channel,createSessionCredential:k,fetch:r.fetch,onUncertainFunding:async e=>{let t=await y.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};d.channel?.channelId===e.channelId&&(d.channel=n),await y.set(n),T(n)}});A(a);let o=d.channel,s=qu({additionalDeposit:e.additionalDeposit,channel:d.channel,channelId:e.channelId,challengeId:d.lastChallenge?.id,currentState:d.state,knownDeposit:t,receipt:a,spent:d.spent});if(s?.channel&&d.lastChallenge){let e=s.channel;for(;;){await y.set(e);let t=d.channel;if(t===o)break;if(!t)return a;let n=s.channel;e=t.channelId===n.channelId?{...t,deposit:t.deposit>n.deposit?t.deposit:n.deposit,cumulativeAmount:t.cumulativeAmount>n.cumulativeAmount?t.cumulativeAmount:n.cumulativeAmount}:t,o=t}if(e.channelId!==s.channel.channelId)return a;d.channel=e,C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}return a})}async function ie(e){return ne(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=Gl({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 re({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function ae(e,t){let n=nu({channel:d.channel,channelId:e,challengeId:d.lastChallenge?.id,cumulativeAmount:t,spent:d.spent,state:d.state});n&&d.channel&&(C({type:`activated`,challengeId:n.challengeId,entry:d.channel,spent:n.spent,units:n.units}),await v(d.channel))}async function oe(e){let t=iu(e,d.channel);d.channel=t.channel,d.spent=t.spent,d.state=t.state,d.channel?.opened&&await v(d.channel)}function se(e,t=!0){let n=e.headers.get(U.paymentReceipt),r=n?sc(n):null;return t&&A(r),Object.assign(e,{receipt:r,challenge:d.lastChallenge,channelId:d.channel?.channelId??null,cumulative:d.channel?.cumulativeAmount??0n})}async function V(e,t){if(t?.[ba])return se(await r.fetch(e,xa(t)),!1);if(g)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);a(e),d.lastUrl=e,d.lastHeaders=t?.headers;let n=ru({channel:d.channel,spent:d.spent,state:d.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};g=i;try{await N(e,t),i.trackCreates=!0;let a=qd(e,t,d.channel?.opened?d.channel.channelId:void 0);f&&(a={...a,context:f});let o=!n.channel?.opened;async function s(){let n=i.resumed;return!o||!n?!1:(o=!1,await b(n),a=qd(e,t,void 0),!0)}for(;;){let t;try{t=await O(e,a)}catch(e){if(i.created.size?await x():await oe(i.committed??n),await s())continue;throw e}let o=se(t),c=!1;if(o.status===402){let t=await od({input:e,init:a,response:o,createSessionCredential:k,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:ae,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:ie});t&&(c=!0,o=se(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await x():await oe(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function ce(e){let t=await cd({createSessionCredential:k,fetch:r.fetch,getMinimumSpent:()=>d.spent,headers:d.lastHeaders,lastUrl:d.lastUrl,resolveSignedCloseAmount:t=>L(e,t,!0),signedCloseAmount:L(e),setChallenge(e){d.lastChallenge=e},target:e});return t&&(j(),C({type:`closeStarted`}),C({type:`closed`,receipt:t})),t}let le={createSessionCredential:k,doFetch:V,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:R,acceptReceipt(e){A(e)},topUpIfNeeded:ie},ue={get channelId(){return d.channel?.channelId},get cumulative(){return d.channel?.cumulativeAmount??0n},get opened(){return d.channel?.opened??!1},get state(){return d.state},fetch:V,async topUp(e){let t=Ku({amount:e,assertVoucherWithinLocalLimit:R,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return ne(async()=>{if(d.channel?.channelId!==t.channelId||d.lastChallenge!==t.challenge||d.lastUrl!==t.input)throw Error(`Session changed while waiting to top up`);let n=Ku({amount:e,assertVoucherWithinLocalLimit:R,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return re({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){if(t?.[ba])throw Error(`SessionManager.sse requires payment; use fetch for unpaid streams.`);return ld(e,t,le)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=td(e);a(n);let i=t?.signal?{signal:t.signal}:void 0;await N(n,i);let o=d.channel?.opened?d.channel.channelId:void 0,{challenge:s,credential:c,httpUrl:l,wsUrl:u}=await vd({async createSessionCredential(e,i){return d.lastChallenge=e,await $i(E,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),k(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){d.lastUrl=e.toString()},probeInit:qd(n,i,o),signal:t?.signal});return d.lastChallenge=s,Cd({challenge:s,credential:c,httpUrl:l,WebSocket:r.WebSocket,wsUrl:u,options:t,createSessionCredential:k,getChannel:()=>d.channel,setSocketSession(e){d.socketSession=e},async refreshChallenge(){let e=await _d({fetch:r.fetch,input:l,probeInit:qd(l,i,d.channel?.opened?d.channel.channelId:void 0),signal:t?.signal});return d.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:R,acceptReceipt:A,rejectCloseReady:p.rejectCloseReady,rejectReceipt:p.rejectReceipt,settleCloseReady:p.settleCloseReady,settleReceipt:p.settleReceipt,topUpIfNeeded:ie,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=ql({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===Uu.OPEN){let r=await au({activeSocket:n,createSessionCredential:k,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return j(),C({type:`closeStarted`}),C({type:`closed`,receipt:r}),r}return ce(t)}};return Hd(ue,{consumeSseResponse(e,t,n){let r=a(e);if(t.url&&new URL(t.url).origin!==r)throw Error(`SessionManager: session response origin mismatch`);return ud(e,t,n,le)},rehydrate({channel:e,challenge:t,input:n,spent:r}){let i=a(n);if(e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!Yu(t))throw Error(`Cannot restore session: challenge is not tempo/session.`);if(r<0n)throw Error(`Cannot restore session: spent must not be negative.`);if(r>e.cumulativeAmount)throw Error(`Cannot restore session: spent exceeds local voucher state.`);R(e.cumulativeAmount);let o=F(e,t),s=o&&o.spent>r?o.spent:r;d.lastUrl=n,d.lastChallenge=t,d.channel=e,d.spent=s,C({type:`challengeReceived`,challengeId:t.id}),C({type:`activated`,challengeId:t.id,entry:e,spent:s.toString(),units:0})}}),ue}(function(e){e.serializeSnapshot=jl,e.deserializeSnapshot=Ml})(Xd||={});const Zd=(1n<<64n)-1n,Qd={dev_second:1n,day:86400n,week:604800n};function $d(e){return e instanceof Date?e:new Date(e)}function ef(e){let t=e.getTime();if(!Number.isFinite(t))throw new W({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new W({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new W({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function tf(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new W({reason:`periodCount is invalid`});let t=Qd[e.periodUnit];if(t===void 0)throw new W({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>Zd)throw new W({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new W({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function nf(e){let{challengeExpires:t,request:n}=e;tf(n);let r=ef($d(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new W({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function rf(e){return[{address:_f(e.currency,`currency`),selector:`0x95777d59`,recipients:[_f(e.recipient,`recipient`)]}]}function af(e){try{let t=M.fromBytes(k.toBytes(e));if(M.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new W({reason:`challenge id must encode 32 bytes`})}}async function of(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=cf({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:ge.getSignPayload(o)}),c=H.from(s);if(c.type===`keychain`||c.type===`configurable`)throw new W({reason:`keyAuthorization must use a primitive signature`});return ge.from(o,{signature:H.serialize(Ec(c))})}function sf(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new W({reason:`invalid keyAuthorization payload`});let o=lf(i.signature),s=uf(o);if(df({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==af(n))throw new W({reason:`keyAuthorization challenge mismatch`});return ff(o,a),mf(pf(o),a),hf(o.scopes,a),{authorization:o,source:{address:gf(o,s),chainId:r}}}function cf(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return ge.from({address:_f(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:ef($d(i.subscriptionExpires)),limits:[{token:_f(i.currency,`currency`),limit:BigInt(i.amount),period:tf(i)}],scopes:rf(i),type:t.keyType,witness:af(n)})}function lf(e){try{return ge.deserialize(e)}catch(e){throw e instanceof ge.InvalidSignatureTypeError?new W({reason:`keyAuthorization must use a primitive signature`}):new W({reason:`invalid keyAuthorization payload`})}}function uf(e){let t=e.signature;if(!t)throw new W({reason:`keyAuthorization must use a primitive signature`});return t}function df(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new W({reason:`keyAuthorization chainId mismatch`});if(t){if(!f(n.address,_f(t.accessKeyAddress,`accessKeyAddress`)))throw new W({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new W({reason:`keyAuthorization key type mismatch`})}}function ff(e,t){if(nf({request:t}),e.expiry!==ef($d(t.subscriptionExpires)))throw new W({reason:`keyAuthorization expiry mismatch`})}function pf(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new W({reason:`keyAuthorization must contain exactly one token limit`});return t}function mf(e,t){if(!f(e.token,_f(t.currency,`currency`)))throw new W({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new W({reason:`keyAuthorization amount mismatch`});if(e.period!==tf(t))throw new W({reason:`keyAuthorization period mismatch`})}function hf(e,t){if(!e||e.length!==1)throw new W({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=_f(t.currency,`currency`),r=_f(t.recipient,`recipient`),i=new Set;for(let t of e){if(!f(t.address,n))throw new W({reason:`keyAuthorization call target mismatch`});let e=vf(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new W({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new W({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!f(t.recipients[0],r))throw new W({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new W({reason:`keyAuthorization must allow transferWithMemo`})}function gf(e,t){let n=ge.getSignPayload(e);try{let e=H.extractAddress({payload:n,signature:t});if(!Tc(t)||!H.verify(t,{address:e,payload:n}))throw new W({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof W?e:new W({reason:`keyAuthorization signature is invalid`})}}function _f(e,t){if(!d(e))throw new W({reason:`${t} must be an address`});return e.toLowerCase()}function vf(e){return typeof e==`string`?e.toLowerCase():``}const yf=G.object({accessKey:G.optional(G.custom()),account:G.optional(G.custom())});function bf(e={}){let t=vo({chain:B,requireChain:!0,getClient:e.getClient,rpcUrl:Or}),n=mo({account:e.account});return yn(Os,{context:yf,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??Z.testnet,o=await t({chainId:a});if(o.chain?.id!==a)throw Error(`Subscription chain mismatch: expected ${a}, got ${o.chain?.id??`unknown`}.`);let 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.");Sf(r.request),await e.validateRequest?.(r.request);let l=await xf(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=sf({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:ge.serialize(l),type:`keyAuthorization`},request:r.request});if(!f(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return dn({challenge:r,payload:{signature:ge.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function xf(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await of({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:ef($d(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:M.fromNumber(BigInt(o.amount)),period:tf(o)}],scopes:rf(o),witness:af(i)}]});return ge.fromRpc(c.keyAuthorization)}function Sf(e){tf(e),ef($d(e.subscriptionExpires))}const Cf=Object.assign(zd,{manager:Xd});function wf(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[As(e),Cf(n)]}(function(e){e.charge=As,e.common=wf,e.session=Cf,e.subscription=bf})(wf||={});const Tf=z.union([z.boolean(),z.literal(`true`).transform(()=>!0),z.literal(`false`).transform(()=>!1)]);async function Ef(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}const Df=z.object({allowCustomEscrow:z.optional(Tf),autoSwap:z.optional(Tf),channel:z.optional(z.coerce.string()),deposit:z.optional(z.union([z.string(),z.number()])),payWith:z.optional(z.string()),slippage:z.optional(z.coerce.number()),tokenIn:z.optional(z.string())}),Of=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`];function kf(){let t;return Jr({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:n,options:r,methodOpts:i}){let a=Wr(r.account),o=n.request,s=o.currency,c=Ff(i),l=zf({autoSwap:c.autoSwap??r.autoSwap,payWith:c.payWith??r.payWith,slippage:c.slippage??r.slippage,tokenIn:c.tokenIn}),d=s??``,f=o.decimals??6,p,m,h,g=!1,_=process.env.MPPX_PRIVATE_KEY?.trim()||(Ar(a)?void 0:await Gr(a).get());if(!_&&Ar(a)&&Jf()){g=!0;let t=Kf(a);if(t){let i=Nr(r.rpcUrl,{network:r.network});h=e({chain:await Pr({network:r.network,rpcUrl:i}),transport:u(i)}),Lf({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let a=s?await Lr(h,s,t.wallet_address).catch(()=>void 0):void 0;d=a?.symbol??s??``,f=a?.decimals??o.decimals??6}}else if(_)m=pe(_);else{let e=Xf();if(e){let t=await Gr(e).get();t&&(m=pe(t))}if(!m)throw r.account?new Cr({code:`ACCOUNT_NOT_FOUND`,message:`Account "${a}" not found.`,exitCode:69}):new Cr({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!g&&m){let t=Nr(r.rpcUrl,{network:r.network});h=e({chain:await Pr({network:r.network,rpcUrl:t}),transport:u(t)}),Lf({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let i=s?await Lr(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 Yf(t)}};if(!m||!h)throw new Cr({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let v=wf({account:m,...c.allowCustomEscrow===void 0?{}:{allowCustomEscrow:c.allowCustomEscrow},getClient:()=>h,...l===void 0?{}:{autoSwap:l},maxDeposit:(()=>{if(n.intent!==`session`)return;let e=n.request.suggestedDeposit,t=(c.deposit===void 0?void 0:String(c.deposit))??e??(Ir(h.chain)?`10`:void 0);if(!t)throw new Cr({code:`MISSING_DEPOSIT`,message:`Session payment requires a deposit. Use -M deposit=<amount> or connect to testnet.`,exitCode:2});return t})()}),y=(()=>{if(!c.channel)return;let e=c.channel,t=Vf(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 Uc(h,m,c,i,a);return dn({challenge:n,payload:{action:o,channelId:e,...o===`close`?{closeSignature:await Wc(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=sn(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?` ${X.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
13
13
  `}${X.dim(`Channel opened ${h.payload.channelId}`)}${t}\n`)}else m(`${l?``:`
14
- `}${X.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let C=i;C.ok&&!C.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let w=C.headers.get(H.paymentReceipt);if(w)try{let e=JSON.parse(O.toString(w));wf(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&Ff(v,S),s>=1&&Cf(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
15
- `})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await Tf(C,{challenge:n,channelId:v,escrowContract:y,chainId:b,cumulativeAmount:S,tickCost:x,fetchUrl:a,fetchInit:o,session:t,info:m,verbose:s,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this}):(await yf(C),v&&y&&b&&(l&&m(`
16
- `),l&&!await e.confirm(`Close channel?`,!0)?s>=1&&m(`${X.dim(`Kept channel open.`)}\n`):await Ef({channelId:v,cumulativeAmount:S,escrowContract:y,chainId:b,fetchUrl:a,fetchInit:o,session:t,info:m,verbose:s,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,confirmEnabled:l}))),!0},formatReceiptField(e,t){(e===`reference`||e===`txHash`)&&typeof t==`string`&&t.startsWith(`0x`)}})}function Cf(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(`(${Tr(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,Cr(`${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(`
17
- `)}function wf(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 Tf(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 Df():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:{[H.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{Cf(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
14
+ `}${X.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let C=i;C.ok&&!C.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let w=C.headers.get(U.paymentReceipt);if(w)try{let e=JSON.parse(k.toString(w));jf(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&Hf(v,S),s>=1&&Af(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
15
+ `})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await Mf(C,{challenge:n,channelId:v,escrowContract:y,chainId:b,cumulativeAmount:S,tickCost:x,fetchUrl:a,fetchInit:o,session:t,info:m,verbose:s,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this}):(await Ef(C),v&&y&&b&&(l&&m(`
16
+ `),l&&!await e.confirm(`Close channel?`,!0)?s>=1&&m(`${X.dim(`Kept channel open.`)}\n`):await Nf({channelId:v,cumulativeAmount:S,escrowContract:y,chainId:b,fetchUrl:a,fetchInit:o,session:t,info:m,verbose:s,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,confirmEnabled:l}))),!0},formatReceiptField(e,t){(e===`reference`||e===`txHash`)&&typeof t==`string`&&t.startsWith(`0x`)}})}function Af(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(`(${jr(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,kr(`${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(`
17
+ `)}function jf(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 Mf(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 Pf():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:{[U.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{Af(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
18
18
 
19
19
  `})}catch{}o=``;continue}if(e.length===0)u(`
20
20
  `);else try{let t=JSON.parse(e);u(t.token??t.choices?.[0]?.delta?.content??e)}catch{u(e)}o=``}}};for(;;){let{done:e,value:t}=await r.read();if(e)break;a+=i.decode(t,{stream:!0});let n=a.split(`
21
- `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await Ef({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 Ef(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:{...xa(e.fetchInit.headers),Authorization:t}});if(n.ok){if(If(e.channelId),e.verbose>=1){let t=n.headers.get(H.paymentReceipt),r;if(t)try{let e=JSON.parse(O.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${X.dim(Cr(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${X.dim(`Channel closed.`)} ${X.dim(`Spent ${Tr(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 Df(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 Of(e){return kf(bf,e,xf)}function kf(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 Af(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 _r({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function jf(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function Mf(e){let t=jf(e.tokenIn)??jf(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 Nf(){return L.join(process.env.XDG_CONFIG_HOME||L.join(I.homedir(),`.config`),`mppx`,`channels`)}function Pf(e){try{let t=F.readFileSync(L.join(Nf(),e),`utf-8`).trim();return t?BigInt(t):void 0}catch{return}}function Ff(e,t){let n=Nf();F.mkdirSync(n,{recursive:!0}),F.writeFileSync(L.join(n,e),t.toString(),`utf-8`)}function If(e){try{F.unlinkSync(L.join(Nf(),e))}catch{}}function Lf(){return I.platform()===`darwin`?L.join(I.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):L.join(process.env.XDG_DATA_HOME||L.join(I.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function Rf(){try{let e=F.readFileSync(Lf(),`utf-8`),t=[],n;for(let r of e.split(`
22
- `)){let e=r.trim();if(e===`[[keys]]`){n?.wallet_address&&t.push(n),n={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!n)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?n.wallet_type=o:a===`wallet_address`?n.wallet_address=o:a===`chain_id`&&(n.chain_id=Number.parseInt(o,10))}return n?.wallet_address&&t.push(n),t}catch{return[]}}function zf(e){let t=Rf();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 Bf;function Vf(){if(Bf!==void 0)return Bf;try{P.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),Bf=!0}catch{Bf=!1}return Bf}async function Hf(e){return new Promise((t,n)=>{P.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 Uf(){let e=Lr();if(wr(e.get())&&!Vf()&&I.platform()===`darwin`)try{let t=P.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 Wf=[...Object.entries(Ne),...Object.entries(Pe),...Object.entries(Fe),...Object.entries(Ie)];function Gf(){return Hr({method:`evm`,supports:Kf,async setup({challenge:e,options:t}){let n=e.request,r=n.network?qf(Ge(n.network)):void 0,i=n.network&&n.asset?Wf.find(([,e])=>Ue(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`?je({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await Vr(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...hr({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function Kf(e){if(!Qt(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 qf(e){return Object.values(te).find(t=>t.id===e)}export{Hr as createPlugin,Ur as evm,Qr as stripe,Sf as tempo,Gf as x402};
21
+ `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await Nf({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 Nf(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:{...Da(e.fetchInit.headers),Authorization:t}});if(n.ok){if(Uf(e.channelId),e.verbose>=1){let t=n.headers.get(U.paymentReceipt),r;if(t)try{let e=JSON.parse(k.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${X.dim(kr(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${X.dim(`Channel closed.`)} ${X.dim(`Spent ${jr(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 Pf(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 Ff(e){return If(Df,e,Of)}function If(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 Lf(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 Cr({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function Rf(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function zf(e){let t=Rf(e.tokenIn)??Rf(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 Bf(){return R.join(process.env.XDG_CONFIG_HOME||R.join(L.homedir(),`.config`),`mppx`,`channels`)}function Vf(e){try{let t=I.readFileSync(R.join(Bf(),e),`utf-8`).trim();return t?BigInt(t):void 0}catch{return}}function Hf(e,t){let n=Bf();I.mkdirSync(n,{recursive:!0}),I.writeFileSync(R.join(n,e),t.toString(),`utf-8`)}function Uf(e){try{I.unlinkSync(R.join(Bf(),e))}catch{}}function Wf(){return L.platform()===`darwin`?R.join(L.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):R.join(process.env.XDG_DATA_HOME||R.join(L.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function Gf(){try{let e=I.readFileSync(Wf(),`utf-8`),t=[],n;for(let r of e.split(`
22
+ `)){let e=r.trim();if(e===`[[keys]]`){n?.wallet_address&&t.push(n),n={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!n)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?n.wallet_type=o:a===`wallet_address`?n.wallet_address=o:a===`chain_id`&&(n.chain_id=Number.parseInt(o,10))}return n?.wallet_address&&t.push(n),t}catch{return[]}}function Kf(e){let t=Gf();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 qf;function Jf(){if(qf!==void 0)return qf;try{F.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),qf=!0}catch{qf=!1}return qf}async function Yf(e){return new Promise((t,n)=>{F.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 Xf(){let e=Ur();if(Ar(e.get())&&!Jf()&&L.platform()===`darwin`)try{let t=F.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 Zf=[...Object.entries(Me),...Object.entries(Ne),...Object.entries(Pe),...Object.entries(Fe)];function Qf(){return Jr({method:`evm`,supports:$f,async setup({challenge:e,options:t}){let n=e.request,r=n.network?ep(We(n.network)):void 0,i=n.network&&n.asset?Zf.find(([,e])=>He(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`?Ae({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await qr(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...xr({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function $f(e){if(!hn(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 ep(e){return Object.values(D).find(t=>t.id===e)}export{Jr as createPlugin,Yr as evm,ii as stripe,kf as tempo,Qf as x402};