mppx 0.19.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,22 +1,22 @@
1
- import{createClient as e,createTransport as t,custom as n,encodeFunctionData as r,erc20Abi as i,formatUnits as a,getAbiItem as o,getAddress as s,hashTypedData as c,http as l,isAddress as u,isAddressEqual as d,keccak256 as f,parseAbi as p,parseEventLogs as m,parseUnits as h}from"viem";import{call as g,getBlockNumber as _,getLogs as v,prepareTransactionRequest as y,readContract as b,sendCallsSync as x,sendRawTransactionSync as S,sendTransactionSync as C,signTransaction as w,signTypedData as ee,waitForTransactionReceipt as T}from"viem/actions";import*as te from"viem/chains";import{tempo as ne}from"viem/chains";import{AbiParameters as E,Base64 as D,Bytes as O,Hash as k,Hex as A,Json as j}from"ox";import*as M from"zod/mini";import*as N from"node:child_process";import*as P from"node:fs";import*as F from"node:os";import*as I from"node:path";import{z as L}from"zod";import"node:readline";import{tempo as R,tempoModerato as 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 z,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{Channel as he,KeyAuthorization as ge,SignatureEnvelope as B,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:He(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:Ve(t.chainId),transfer:Ue(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`}})};function Ie(e){return typeof e!=`object`||!e?!1:e[ke]===!0}const Le=Ee;function Re(e){return typeof e==`string`}function ze(e,t){if(Ie(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:He(t)});if(n)return{address:n.address,decimals:n.decimals,name:n.name}}function Be(e,t,n){let r=ze(e,n);return r?s(r.address)===s(t):!1}function Ve(e){return`eip155:${e}`}function He(e){return Number(e.slice(7))}function Ue(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 We=Ce({base:()=>Me,baseSepolia:()=>Ne,celo:()=>Pe,celoSepolia:()=>Fe,define:()=>Ae,fromToken:()=>je,isAsset:()=>Ie,isRawAddress:()=>Re,isToken:()=>Le,matches:()=>Be,resolve:()=>ze,toChainId:()=>He,toNetwork:()=>Ve}),Ge=Ce({base:()=>Ke,baseSepolia:()=>qe,celo:()=>Je,celoSepolia:()=>Ye});const Ke=8453,qe=84532,Je=42220,Ye=11142220,V={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},Xe={payment:`Payment`},Ze={evm:`evm`,stripe:`stripe`,tempo:`tempo`},Qe={charge:`charge`,session:`session`,subscription:`subscription`},$e={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},et={v1:`v1`,v2:`v2`};function tt(e,t){if(!(!e||typeof e!=`object`))return e[t]}function nt(e){let t=D.toString(e);return JSON.parse(t)}function H(e){let t=j.canonicalize(e);return D.fromString(t,{pad:!1,url:!0})}var U=Ce({address:()=>G,amount:()=>W,datetime:()=>it,datetimeInput:()=>at,hash:()=>K,period:()=>ct,signature:()=>q,toDate:()=>ot,toDatetimeString:()=>st,unwrapOptional:()=>lt});import*as rt from"zod/mini";Te(U,rt);function W(){return M.string().check(M.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function it(){return M.string().check(M.regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,`Invalid ISO 8601 datetime`))}function at(e=`Invalid ISO 8601 datetime`){return M.pipe(M.union([it(),M.custom(e=>e instanceof Date)]),M.transform(ot)).check(M.refine(e=>Number.isFinite(e.getTime()),e))}function ot(e){return e instanceof Date?e:new Date(e)}function st(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function G(){return M.string().check(M.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function K(){return M.string().check(M.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function ct(){return M.string().check(M.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function q(){return M.string().check(M.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function lt(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}const ut=U.object({description:U.optional(U.string()),digest:U.optional(U.string().check(U.regex(/^sha-256=/,`Invalid digest format`))),expires:U.optional(it()),header:U.optional(U.string().check(U.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,`Invalid HTTP header name`))),id:U.string().check(U.minLength(1)),intent:U.string(),method:U.string(),meta:U.optional(U.record(U.string(),U.string())),opaque:U.optional(U.string()),realm:U.string(),request:U.record(U.string(),U.unknown())});function dt(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=Et(o)?void 0:o,f=e.expires?st(e.expires):void 0,p=e.opaque??(i===void 0?void 0:H(i)),m=u?Dt({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return ut.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 ft(e){let t=[J(`id`,e.id),J(`realm`,e.realm),J(`method`,e.method),J(`intent`,e.intent),J(`request`,H(e.request))];e.description!==void 0&&t.push(J(`description`,e.description)),e.digest!==void 0&&t.push(J(`digest`,e.digest)),e.expires!==void 0&&t.push(J(`expires`,e.expires));let n=e.header;return n!==void 0&&!Et(n)&&t.push(J(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(J(`opaque`,H(e.meta))):t.push(J(`opaque`,e.opaque)),`${Xe.payment} ${t.join(`, `)}`}function J(e,t){if(/[\r\n]/.test(t))throw Error(`Invalid quoted-string value.`);return`${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`}function pt(e,t){let n=mt(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=ht(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>16384)throw Error(`Request parameter too large.`);if(a.method&&!/^[a-z][a-z0-9:_-]*$/.test(a.method))throw Error(`Invalid method: "${a.method}". Must be lowercase per spec.`);return dt({...a,request:nt(r),...i&&{opaque:i}},t)}function mt(e){let t=Xe.payment,[n]=bt(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 ht(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]=gt(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function gt(e,t){if(e[t]===`"`)return _t(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function _t(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 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 yt(e){return bt(e,Xe.payment).length>0||e.split(`,`).some(e=>e.trim().toLowerCase()===Xe.payment.toLowerCase())}function bt(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 xt(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return St(e.headers,t)}function St(e,t){let n=e.get(V.wwwAuthenticate);if(!n)throw Error(`Missing ${V.wwwAuthenticate} header.`);return Ct(n,t)}function Ct(e,t){let n=bt(e,Xe.payment);if(n.length===0)throw Error(`No Payment schemes found.`);return n.map((r,i)=>{let a=i+1<n.length?n[i+1]:e.length;return pt(e.slice(r,a).replace(/,\s*$/,``),t)})}function wt(e){let t=[e.realm,e.method,e.intent,H(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!Et(n)&&t.push(n),t.push(e.opaque??(e.meta?H(e.meta):``)),t.join(`|`)}function Tt(e){return e.header??V.authorization}function Et(e){return e?.toLowerCase()===V.authorization.toLowerCase()}function Dt(e,t){let n=wt(e),r=O.fromString(t.secretKey),i=O.fromString(n),a=k.hmac256(r,i,{as:`Bytes`});return D.fromBytes(a,{url:!0,pad:!1})}const Ot=65536;var kt=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},At=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function jt(e){if(e.length>Ot)throw new At;let t=e.match(RegExp(`^${Xe.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new kt;try{let e=D.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=Mt(r);return{challenge:ut.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:nt(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new At}}function Mt(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!Nt(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:H(e)}}function Nt(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function Pt(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function Ft(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:H(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:H(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=D.fromString(s,{pad:!1,url:!0});return`${Xe.payment} ${c}`}function It(e){return e.length>Ot?null:e.split(`,`).map(e=>e.trim()).find(e=>RegExp(`^${Xe.payment}\\s+`,`i`).test(e))??null}function Lt(e,t){return t?`${e} Add funds at ${t}`:e}var Rt=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}}}},zt=class extends Rt{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 Rt{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,fundingUrl:n,reason:r}=e;super(Lt(r?`Payment verification failed: ${r}.`:`Payment verification failed.`,n),{details:t,fundingUrl:n})}},Bt=class extends Rt{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.`)}},Vt=class extends Rt{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}},Ht=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??`with sender tag ${i.join(` or `)}`;super(`Zone ${r} withdrawal ${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})}},Ut=class extends Rt{name=`InsufficientBalanceError`;title=`Insufficient Balance`;status=402;type=`https://paymentauth.org/problems/session/insufficient-balance`;constructor(e={}){let{fundingUrl:t,reason:n}=e;super(Lt(n?`Insufficient balance: ${n}.`:`Insufficient balance.`,t),{fundingUrl:t})}};function Wt(e,t){if(!e)throw new zt({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new zt({...t&&{id:t},reason:`malformed expires timestamp`});if(Date.parse(e)<=Date.now())throw new Bt({expires:e})}function Gt(e){return e}function Kt(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}function qt(e){return{encode(t){return D.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(D.toString(t)))}catch{throw new Jt}}}}var Jt=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const Yt=[`exact`],Xt=`PAYMENT-REQUIRED`,Zt=`PAYMENT-SIGNATURE`,Qt=U.string().check(U.minLength(1)),$t=U.number().check(U.refine(e=>e>0,`Must be positive`)),en=U.string().check(U.regex(/^\d+$/,`Invalid atomic amount`)),tn=G(),nn=U.string().check(U.regex(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),rn=U.object({description:U.optional(U.string()),iconUrl:U.optional(U.string()),mimeType:U.optional(U.string()),serviceName:U.optional(U.string()),tags:U.optional(U.array(U.string())),url:Qt});U.discriminatedUnion(`type`,[U.object({name:Qt,type:U.literal(`eip3009`),version:Qt}),U.object({name:U.optional(U.string()),type:U.literal(`permit2`),version:U.optional(U.string())})]);const an=U.object({amount:en,asset:Qt,extra:U.optional(U.record(U.string(),U.unknown())),maxTimeoutSeconds:$t,network:nn,payTo:Qt,scheme:U.enum(Yt)}),on=U.object({info:U.record(U.string(),U.unknown()),schema:U.record(U.string(),U.unknown())}),sn=U.record(U.string(),on),cn=U.object({accepts:U.array(an).check(U.minLength(1)),error:U.optional(U.string()),extensions:U.optional(sn),resource:rn,x402Version:U.literal(2)}),ln=U.object({authorization:U.object({from:tn,nonce:K(),to:tn,validAfter:en,validBefore:en,value:en}),signature:q()}),un=U.object({permit2Authorization:U.object({deadline:en,from:tn,nonce:en,permitted:U.object({amount:en,token:tn}),spender:tn,witness:U.object({to:tn,validAfter:en})}),signature:q()}),dn=U.union([ln,un]),fn=U.object({accepted:an,extensions:U.optional(sn),payload:dn,resource:U.optional(rn),x402Version:U.literal(2)});U.object({extensions:U.optional(sn),extra:U.optional(U.record(U.string(),U.unknown())),invalidMessage:U.optional(U.string()),invalidReason:U.optional(U.string()),isValid:U.boolean(),payer:U.optional(U.string())});const pn=U.object({amount:U.optional(en),errorMessage:U.optional(U.string()),errorReason:U.optional(U.string()),extensions:U.optional(sn),extra:U.optional(U.record(U.string(),U.unknown())),network:Qt,payer:U.optional(U.string()),success:U.boolean(),transaction:U.string()});function mn(e){let{extensions:t,resource:n,...r}=e;return an.parse(r)}const hn=qt(cn),gn=qt(fn),_n=qt(pn);hn.encode,hn.decode;function vn(e){try{let t=JSON.parse(D.toString(e));return bn(t)}catch{throw new Jt}}const yn=gn.encode;gn.decode,_n.encode,_n.decode;const bn=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new Jt;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new Jt;let n=rn.parse(t.resource),r=t.extensions===void 0?void 0:sn.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}};function xn(e){let t=[H(e.accepted),H(e.resource),H(e.extensions)].join(`|`);return k.sha256(O.fromString(t),{as:`Hex`})}async function Sn(e){let t=e.context?.account??e.config.account;if(!t?.signTypedData)throw Error(`x402 exact requires a typed-data signer.`);let n=e.challenge.request,r=mn(n);if(En(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?On(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,c=r.extra?.version;if(typeof o!=`string`||typeof c!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let l=Math.floor(Date.now()/1e3),u={from:s(t.address),nonce:i?.mppx?xn({accepted:r,extensions:i,resource:n.resource}):An(),to:s(r.payTo),validAfter:(l-600).toString(),validBefore:(l+r.maxTimeoutSeconds).toString(),value:r.amount},d=await t.signTypedData({domain:{chainId:Tn(r.network),name:o,verifyingContract:s(r.asset),version:c},message:{...u,value:BigInt(u.value),validAfter:BigInt(u.validAfter),validBefore:BigInt(u.validBefore)},primaryType:`TransferWithAuthorization`,types:wn});return yn({accepted:r,...i?{extensions:i}:{},payload:{authorization:u,signature:d},...n.resource?{resource:n.resource}:{},x402Version:2})}function Cn(e){let t=e.challenge.request,n;try{n=mn(t),En(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 wn={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 Tn(e){return Number(e.slice(7))}function En(e,t){let n=Tn(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=>Re(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=s(t.asset);if(!r.some(n=>Be(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=Dn(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>h(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function Dn(e,t){let n=e.currencies??e.assets,r=s(t.asset),i=n?.find(e=>Be(e,r,t.network)),a=i?ze(i,t.network):void 0;return a?.decimals===void 0?e.decimals:a.decimals}function On(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:kn()}}}:e}function kn(){return jn().slice(2)}function An(){return jn()}function jn(){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 Mn=Symbol.for(`mppx.x402.challenge`);function Nn(e){return Object.defineProperty(e,Mn,{value:!0}),e}function Pn(e){return!!e?.[Mn]}const Fn=[`authorization`],In=U.string().check(U.regex(/^\d+$/,`Invalid atomic amount`));U.object({name:U.string().check(U.minLength(1)),version:U.string().check(U.minLength(1))});const Ln=U.object({chainId:U.number(),credentialTypes:U.optional(U.array(U.enum(Fn)).check(U.minLength(1))),decimals:U.optional(U.number()),permit2Address:U.optional(G()),splits:U.optional(U.array(U.object({amount:In,recipient:G()})))});U.object({amount:In,currency:G(),description:U.optional(U.string()),externalId:U.optional(U.string()),methodDetails:Ln,recipient:G()});const Rn=U.object({amount:W(),chainId:U.number(),currency:G(),credentialTypes:U.optional(U.array(U.enum(Fn)).check(U.minLength(1))),decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),permit2Address:U.optional(G()),recipient:G(),splits:U.optional(U.array(U.object({amount:In,recipient:G()})))}),zn=U.object({from:G(),nonce:K(),signature:q(),to:G(),type:U.literal(`authorization`),validAfter:In,validBefore:In,value:In}),Bn={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 Vn(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function Hn(e){return k.keccak256(O.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function Un(e){return`eip155:${e}`}function Wn(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const Gn=Gt({name:`evm`,intent:`charge`,schema:{credential:{payload:zn},request:U.pipe(Rn,U.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:c,...l})=>({...l,amount:h(e,i).toString(),currency:s(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:s(a)}:{},...c?{splits:c}:{}},recipient:s(o)})))}});function Kn(e){return Kt(Gn,{canHandleChallenge({challenge:t}){return!qn(t)||Cn({challenge:t,config:e})},context:U.object({account:U.optional(U.custom())}),async createCredential({challenge:t,context:n}){if(qn(t))return Sn({challenge:t,config:e,context:n});let r=n?.account??e.account;if(!r?.signTypedData)throw Error(`EVM authorization requires a typed-data signer.`);let i=t.request;if(Jn(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=Yn(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return Ft(Pt({challenge:t,payload:{from:s(r.address),nonce:Hn(t),signature:await r.signTypedData({domain:Vn({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:s(r.address),nonce:Hn(t),to:s(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:Bn}),to:s(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:Wn({address:s(r.address),chainId:i.methodDetails.chainId})}))}})}function qn(e){return Pn(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function Jn(e,t){let n=t.methodDetails.chainId,r=Un(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=>Re(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=s(t.currency);if(!i.some(t=>Be(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=Xn(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>h(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function Yn(e,t){let n=e.currencies??e.assets,r=s(t.currency),i=Un(t.methodDetails.chainId),a=n?.find(e=>Be(e,r,i)),o=a?ze(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;throw Error(`EVM authorization requires token name and version.`)}function Xn(e,t){let n=e.currencies??e.assets,r=s(t.currency),i=Un(t.methodDetails.chainId),a=n?.find(e=>Be(e,r,i)),o=a?ze(a,i):void 0;return o?.decimals===void 0?e.decimals:o.decimals}function Zn(e){return[Zn.charge(e)]}(function(e){e.charge=Kn,e.assets=We,e.chains=Ge})(Zn||={});var Qn=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 er(this,e)}},$n=class extends Qn{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 er(e,t){if(t){let n=e?.cause;for(;n;){if(t(n))return n;n=n?.cause}return}let n=e;for(;n?.cause;)n=n.cause;return n}const X={mainnet:4217,testnet:42431},tr={ousd:ie(X.mainnet).address,usdc:s(oe(X.mainnet).address),pathUsd:ae(X.mainnet).address},nr={[X.mainnet]:tr.usdc,[X.testnet]:tr.pathUsd},rr=Object.freeze({[X.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[X.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})});X.mainnet,X.testnet;const ir={[X.mainnet]:`https://rpc.tempo.xyz`,[X.testnet]:`https://rpc.moderato.tempo.xyz`},Z=(()=>{let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes(`--no-color`))&&(!!n.FORCE_COLOR||t.includes(`--color`)||(e.stdout||{}).isTTY&&n.TERM!==`dumb`||!!n.CI),i=(e,t,n,r)=>{let i=``,a=0,o=r;do i+=e.substring(a,o)+n,a=o+t.length,o=e.indexOf(t,a);while(~o);return i+e.substring(a)},a=r?(e,t,n=e)=>r=>{let a=`${r}`,o=a.indexOf(t,e.length);return~o?e+i(a,t,n,o)+t:e+a+t}:()=>String;return{isColorSupported:r,reset:a(`\x1B[0m`,`\x1B[0m`),bold:a(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:a(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:a(`\x1B[3m`,`\x1B[23m`),underline:a(`\x1B[4m`,`\x1B[24m`),inverse:a(`\x1B[7m`,`\x1B[27m`),hidden:a(`\x1B[8m`,`\x1B[28m`),strikethrough:a(`\x1B[9m`,`\x1B[29m`),black:a(`\x1B[30m`,`\x1B[39m`),red:a(`\x1B[31m`,`\x1B[39m`),green:a(`\x1B[32m`,`\x1B[39m`),yellow:a(`\x1B[33m`,`\x1B[39m`),blue:a(`\x1B[34m`,`\x1B[39m`),magenta:a(`\x1B[35m`,`\x1B[39m`),cyan:a(`\x1B[36m`,`\x1B[39m`),white:a(`\x1B[37m`,`\x1B[39m`),gray:a(`\x1B[90m`,`\x1B[39m`),bgBlack:a(`\x1B[40m`,`\x1B[49m`),bgRed:a(`\x1B[41m`,`\x1B[49m`),bgGreen:a(`\x1B[42m`,`\x1B[49m`),bgYellow:a(`\x1B[43m`,`\x1B[49m`),bgBlue:a(`\x1B[44m`,`\x1B[49m`),bgMagenta:a(`\x1B[45m`,`\x1B[49m`),bgCyan:a(`\x1B[46m`,`\x1B[49m`),bgWhite:a(`\x1B[47m`,`\x1B[49m`),blackBright:a(`\x1B[90m`,`\x1B[39m`),redBright:a(`\x1B[91m`,`\x1B[39m`),greenBright:a(`\x1B[92m`,`\x1B[39m`),yellowBright:a(`\x1B[93m`,`\x1B[39m`),blueBright:a(`\x1B[94m`,`\x1B[39m`),magentaBright:a(`\x1B[95m`,`\x1B[39m`),cyanBright:a(`\x1B[96m`,`\x1B[39m`),whiteBright:a(`\x1B[97m`,`\x1B[39m`),bgBlackBright:a(`\x1B[100m`,`\x1B[49m`),bgRedBright:a(`\x1B[101m`,`\x1B[49m`),bgGreenBright:a(`\x1B[102m`,`\x1B[49m`),bgYellowBright:a(`\x1B[103m`,`\x1B[49m`),bgBlueBright:a(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:a(`\x1B[105m`,`\x1B[49m`),bgCyanBright:a(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:a(`\x1B[107m`,`\x1B[49m`),link(e,t,n){return r?`\x1b]8;;${e}\x07${n?t:Z.underline(t)}\x1b]8;;\x07`:t}}})();function ar(e,t){return Z.link(e,t)}function or(e){return e.startsWith(`tempo:`)}function sr(e,t,n=6,r){let[i,a]=(Number(e)/10**n).toString().split(`.`),o=i.replace(/\B(?=(\d{3})+(?!\d))/g,`_`),s=r?.explorerUrl&&r.token?Z.dim(Z.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):Z.dim(t);return`${a?`${o}.${a}`:o} ${s}`}const cr={mainnet:ir[X.mainnet],testnet:ir[X.testnet]};function lr(e,t={}){return e??(t.network?cr[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}async function ur(t={}){let n=lr(t.rpcUrl,{network:t.network});if(!n)return R;let{getChainId:r}=await import(`viem/actions`),i=await r(e({transport:l(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 dr(e){return typeof e==`bigint`?e:e.amount}function fr(e){return e.id!==R.id}async function pr(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(dr).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 hr(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function gr(e){return new $n({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 _r(e){if(e&&hr(e,`secret-tool`))throw gr(e)}function vr(e,t){return new Promise(n=>{N.execFile(e,t,{timeout:mr()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function yr(){let e=I.join(process.env.XDG_CONFIG_HOME||I.join(F.homedir(),`.config`),`mppx`,`default`);return{get(){try{return P.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(t){P.mkdirSync(I.dirname(e),{recursive:!0}),P.writeFileSync(e,t,`utf-8`)},clear(){try{P.unlinkSync(e)}catch{}}}}function br(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:yr().get())}function xr(e=`main`){let t=`mppx`;return{async list(){let e=F.platform();if(e===`darwin`){let{stdout:e,error:n}=await vr(`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 vr(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(_r(r),r)return[];let i=`${e}\n${n}`,a=[],o=i.matchAll(/\baccount = (.+)/g);for(let e of o)e[1]&&a.push(e[1]);return a}throw Error(`Unsupported platform: ${e}`)},async get(){let n=F.platform();if(n===`darwin`){let{stdout:n,error:r}=await vr(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await vr(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return _r(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=F.platform();if(r===`darwin`){await vr(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await vr(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=N.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),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(hr(e,`secret-tool`)?gr(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=F.platform();if(n===`darwin`){await vr(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await vr(`secret-tool`,[`clear`,`service`,t,`account`,e]);_r(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function Sr(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=br(e),i=await xr(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function Cr(e){return(await Sr(e)).account}function wr(e){return e}function Tr(){return wr({method:`evm`,supports:e=>e.method===`evm`&&!Pn(e),async setup({challenge:t,options:n}){let r=t.request,a=r.methodDetails,o=a?.chainId,s=o?Er(o):void 0,c=r.currency,u=await Cr(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:l()}),n=await b(t,{address:c,abi:i,functionName:`symbol`});n&&(f=n)}catch{}return{tokenSymbol:f,tokenDecimals:a?.decimals??6,explorerUrl:s?.blockExplorers?.default?.url,methods:[...Zn({account:u,currencies:d})]}}})}function Er(e){return Object.values(te).find(t=>t.id===e)}function Dr(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 Or=U.object({customer:U.optional(U.string().check(U.minLength(1))),hooks:U.optional(U.object({inputs:U.object({tax:U.object({calculation:U.string().check(U.minLength(1))})})})),metadata:U.optional(U.record(U.string(),U.string())),receipt_email:U.optional(U.string().check(U.minLength(1)))}),kr=U.custom(e=>typeof e==`function`),Ar=U.union([Or,kr]),jr=Gt({name:`stripe`,intent:`charge`,schema:{credential:{payload:U.object({externalId:U.optional(U.string()),spt:U.string()})},request:U.pipe(U.object({amount:W(),currency:U.string(),decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),metadata:U.optional(U.record(U.string(),U.string())),networkId:U.string(),paymentIntentOptions:U.optional(Ar),paymentMethodTypes:U.array(U.string()).check(U.minLength(1)),recipient:U.optional(U.string())}),U.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:Dr(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});function Mr(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return Kt(jr,{context:U.object({paymentMethod:U.optional(U.string())}),async createCredential({challenge:e,context:a}){let o=a?.paymentMethod??i;if(!o)throw Error(`paymentMethod is required (pass via context or parameters)`);let s=e.request.amount,c=e.request.currency,l=typeof e.request.externalId==`string`?e.request.externalId:void 0,u=e.request.methodDetails?.networkId;if(!u)throw Error(`networkId is required in challenge.methodDetails`);let d=e.request.methodDetails?.metadata;if(d?.externalId)throw Error(`methodDetails.metadata.externalId is reserved; use credential externalId instead`);let f=e.expires?Math.floor(new Date(e.expires).getTime()/1e3):Math.floor(Date.now()/1e3)+3600,p=await n({amount:s,challenge:e,client:t,currency:c,expiresAt:f,metadata:d,networkId:u,paymentMethod:o}),m=l??r;return Ft({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function Nr(e){return[Mr(e)]}(function(e){e.charge=Mr})(Nr||={});function Pr(){return wr({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=Ir(L.object({paymentMethod:L.string(),secretKey:L.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new $n({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:[Nr.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=Fr(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 $n({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${(await d.json()).error.message}`,exitCode:77})}else throw new $n({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&&Fr(e)?`/test`:``}/payments/${t}`;return Z.link(n,t,!0)}}})}function Fr(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function Ir(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 Lr=Symbol.for(`mppx.fetch.skipPayment`);Object.freeze({phase:`unproved`});function Rr(e,t,n={}){return async(r,i)=>{let a=new Request(r,i),o=zr(a.headers)??n.challenge,{response:s}=await t.send((t,n)=>e(t,{...n,...i?.[Lr]?{[Lr]:!0}:{}}),a,{...n,challenge:o});if(s.status===402&&o)for(let e of Br(s))e.method===o.method&&e.intent===o.intent&&await t.challenge(s,{challenge:e},a.url);return s}}function zr(e){for(let[,t]of e){let e=It(t);if(e)try{return jt(e).challenge}catch{}}}function Br(e){try{return xt(e)}catch{return[]}}const Vr=Symbol(`mppx.deferredContext`);function Hr(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=qr(n)}return t}function Ur(e,t){let n=Hr(e),r=ei(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[qr(e)]??1,index:t}));return{definition:r,entries:i,header:Gr(i),keys:n}}function Wr(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)=>Qr(e,t))}function Gr(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${ii(n)}`}).join(`, `)}function Kr(e,t,n,r){let i=new Map;for(let e of t){let t=qr(e),n=i.get(t);n?n.push(e):i.set(t,[e])}return e.flatMap((e,t)=>{let a=i.get(qr(e));if(!a)return[];let o=Jr(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)=>Zr(e.challenge)-Zr(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function qr(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function Jr(e,t){let n;for(let r of t){if(!Yr(e,r))continue;let t={...r,specificity:Xr(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 Yr(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function Xr(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function Zr(e){return+!!Pn(e)}function Qr(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}`);ai(r,`method`),ai(i,`intent`);let a=1;for(let t of $r(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=ni(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function $r(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function ei(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>qr(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 ri(e,t)}function ni(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 ri(Number(e),t)}function ri(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 ii(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function ai(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}function oi(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 ee,signTypedData as T,waitForTransactionReceipt as te}from"viem/actions";import*as ne from"viem/chains";import{tempo as re}from"viem/chains";import{AbiParameters as E,Base64 as D,Bytes as O,Hash as k,Hex as A,Json as j}from"ox";import*as M from"zod/mini";import*as N from"node:child_process";import*as P from"node:fs";import*as F from"node:os";import*as I from"node:path";import{z as L}from"zod";import"node:readline";import{tempo as R,tempoModerato as ie}from"viem/tempo/chains";import{ousd as ae,pathusd as oe,usdce as se}from"viem/tokens";import{Abis as ce,Account as le,Actions as z,Addresses as ue,TokenId as de,Transaction as fe,withFeePayer as pe}from"viem/tempo";import{parseAccount as me,privateKeyToAccount as he}from"viem/accounts";import{Channel as ge,KeyAuthorization as _e,SignatureEnvelope as B,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:Ue(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:He(t.chainId),transfer:We(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`}})};function Le(e){return typeof e!=`object`||!e?!1:e[Ae]===!0}const Re=De;function ze(e){return typeof e==`string`}function Be(e,t){if(Le(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:Ue(t)});if(n)return{address:n.address,decimals:n.decimals,name:n.name}}function Ve(e,t,n){let r=Be(e,n);return r?c(r.address)===c(t):!1}function He(e){return`eip155:${e}`}function Ue(e){return Number(e.slice(7))}function We(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 Ge=we({base:()=>Ne,baseSepolia:()=>Pe,celo:()=>Fe,celoSepolia:()=>Ie,define:()=>je,fromToken:()=>Me,isAsset:()=>Le,isRawAddress:()=>ze,isToken:()=>Re,matches:()=>Ve,resolve:()=>Be,toChainId:()=>Ue,toNetwork:()=>He}),Ke=we({base:()=>qe,baseSepolia:()=>Je,celo:()=>Ye,celoSepolia:()=>Xe});const qe=8453,Je=84532,Ye=42220,Xe=11142220,V={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},Ze={payment:`Payment`},Qe={evm:`evm`,stripe:`stripe`,tempo:`tempo`},$e={charge:`charge`,session:`session`,subscription:`subscription`},et={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},tt={v1:`v1`,v2:`v2`};function nt(e,t){if(!(!e||typeof e!=`object`))return e[t]}function rt(e){let t=D.toString(e);return JSON.parse(t)}function H(e){let t=j.canonicalize(e);return D.fromString(t,{pad:!1,url:!0})}var U=we({address:()=>G,amount:()=>W,datetime:()=>at,datetimeInput:()=>ot,hash:()=>K,period:()=>lt,signature:()=>q,toDate:()=>st,toDatetimeString:()=>ct,unwrapOptional:()=>ut});import*as it from"zod/mini";Ee(U,it);function W(){return M.string().check(M.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function at(){return M.string().check(M.regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,`Invalid ISO 8601 datetime`))}function ot(e=`Invalid ISO 8601 datetime`){return M.pipe(M.union([at(),M.custom(e=>e instanceof Date)]),M.transform(st)).check(M.refine(e=>Number.isFinite(e.getTime()),e))}function st(e){return e instanceof Date?e:new Date(e)}function ct(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function G(){return M.string().check(M.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function K(){return M.string().check(M.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function lt(){return M.string().check(M.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function q(){return M.string().check(M.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function ut(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}const dt=U.object({description:U.optional(U.string()),digest:U.optional(U.string().check(U.regex(/^sha-256=/,`Invalid digest format`))),expires:U.optional(at()),header:U.optional(U.string().check(U.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,`Invalid HTTP header name`))),id:U.string().check(U.minLength(1)),intent:U.string(),method:U.string(),meta:U.optional(U.record(U.string(),U.string())),opaque:U.optional(U.string()),realm:U.string(),request:U.record(U.string(),U.unknown())});function ft(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=Dt(o)?void 0:o,f=e.expires?ct(e.expires):void 0,p=e.opaque??(i===void 0?void 0:H(i)),m=u?Ot({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return dt.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 pt(e){let t=[J(`id`,e.id),J(`realm`,e.realm),J(`method`,e.method),J(`intent`,e.intent),J(`request`,H(e.request))];e.description!==void 0&&t.push(J(`description`,e.description)),e.digest!==void 0&&t.push(J(`digest`,e.digest)),e.expires!==void 0&&t.push(J(`expires`,e.expires));let n=e.header;return n!==void 0&&!Dt(n)&&t.push(J(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(J(`opaque`,H(e.meta))):t.push(J(`opaque`,e.opaque)),`${Ze.payment} ${t.join(`, `)}`}function J(e,t){if(/[\r\n]/.test(t))throw Error(`Invalid quoted-string value.`);return`${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`}function mt(e,t){let n=ht(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=gt(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>16384)throw Error(`Request parameter too large.`);if(a.method&&!/^[a-z][a-z0-9:_-]*$/.test(a.method))throw Error(`Invalid method: "${a.method}". Must be lowercase per spec.`);return ft({...a,request:rt(r),...i&&{opaque:i}},t)}function ht(e){let t=Ze.payment,[n]=xt(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 gt(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]=_t(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function _t(e,t){if(e[t]===`"`)return vt(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function vt(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 yt(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 bt(e){return xt(e,Ze.payment).length>0||e.split(`,`).some(e=>e.trim().toLowerCase()===Ze.payment.toLowerCase())}function xt(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(!yt(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 St(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return Ct(e.headers,t)}function Ct(e,t){let n=e.get(V.wwwAuthenticate);if(!n)throw Error(`Missing ${V.wwwAuthenticate} header.`);return wt(n,t)}function wt(e,t){let n=xt(e,Ze.payment);if(n.length===0)throw Error(`No Payment schemes found.`);return n.map((r,i)=>{let a=i+1<n.length?n[i+1]:e.length;return mt(e.slice(r,a).replace(/,\s*$/,``),t)})}function Tt(e){let t=[e.realm,e.method,e.intent,H(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!Dt(n)&&t.push(n),t.push(e.opaque??(e.meta?H(e.meta):``)),t.join(`|`)}function Et(e){return e.header??V.authorization}function Dt(e){return e?.toLowerCase()===V.authorization.toLowerCase()}function Ot(e,t){let n=Tt(e),r=O.fromString(t.secretKey),i=O.fromString(n),a=k.hmac256(r,i,{as:`Bytes`});return D.fromBytes(a,{url:!0,pad:!1})}const kt=65536;var At=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},jt=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function Mt(e){if(e.length>kt)throw new jt;let t=e.match(RegExp(`^${Ze.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new At;try{let e=D.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=Nt(r);return{challenge:dt.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:rt(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new jt}}function Nt(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!Pt(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:H(e)}}function Pt(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function Ft(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function It(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:H(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:H(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=D.fromString(s,{pad:!1,url:!0});return`${Ze.payment} ${c}`}function Lt(e){return e.length>kt?null:e.split(`,`).map(e=>e.trim()).find(e=>RegExp(`^${Ze.payment}\\s+`,`i`).test(e))??null}function Rt(e,t){return t?`${e} Add funds at ${t}`:e}var zt=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}}}},Bt=class extends zt{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 zt{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,fundingUrl:n,reason:r}=e;super(Rt(r?`Payment verification failed: ${r}.`:`Payment verification failed.`,n),{details:t,fundingUrl:n})}},Vt=class extends zt{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.`)}},Ht=class extends zt{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}},Ut=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})}},Wt=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??`with sender tag ${i.join(` or `)}`;super(`Zone ${r} withdrawal ${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})}},Gt=class extends zt{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(Rt(r?`Insufficient balance: ${r}.`:`Insufficient balance.`,n),{cause:t,fundingUrl:n})}};function Kt(e,t){if(!e)throw new Bt({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new Bt({...t&&{id:t},reason:`malformed expires timestamp`});if(Date.parse(e)<=Date.now())throw new Vt({expires:e})}function qt(e){return e}function Jt(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}function Yt(e){return{encode(t){return D.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(D.toString(t)))}catch{throw new Xt}}}}var Xt=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const Zt=[`exact`],Qt=`PAYMENT-REQUIRED`,$t=`PAYMENT-SIGNATURE`,en=U.string().check(U.minLength(1)),tn=U.number().check(U.refine(e=>e>0,`Must be positive`)),nn=U.string().check(U.regex(/^\d+$/,`Invalid atomic amount`)),rn=G(),an=U.string().check(U.regex(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),on=U.object({description:U.optional(U.string()),iconUrl:U.optional(U.string()),mimeType:U.optional(U.string()),serviceName:U.optional(U.string()),tags:U.optional(U.array(U.string())),url:en});U.discriminatedUnion(`type`,[U.object({name:en,type:U.literal(`eip3009`),version:en}),U.object({name:U.optional(U.string()),type:U.literal(`permit2`),version:U.optional(U.string())})]);const sn=U.object({amount:nn,asset:en,extra:U.optional(U.record(U.string(),U.unknown())),maxTimeoutSeconds:tn,network:an,payTo:en,scheme:U.enum(Zt)}),cn=U.object({info:U.record(U.string(),U.unknown()),schema:U.record(U.string(),U.unknown())}),ln=U.record(U.string(),cn),un=U.object({accepts:U.array(sn).check(U.minLength(1)),error:U.optional(U.string()),extensions:U.optional(ln),resource:on,x402Version:U.literal(2)}),dn=U.object({authorization:U.object({from:rn,nonce:K(),to:rn,validAfter:nn,validBefore:nn,value:nn}),signature:q()}),fn=U.object({permit2Authorization:U.object({deadline:nn,from:rn,nonce:nn,permitted:U.object({amount:nn,token:rn}),spender:rn,witness:U.object({to:rn,validAfter:nn})}),signature:q()}),pn=U.union([dn,fn]),mn=U.object({accepted:sn,extensions:U.optional(ln),payload:pn,resource:U.optional(on),x402Version:U.literal(2)});U.object({extensions:U.optional(ln),extra:U.optional(U.record(U.string(),U.unknown())),invalidMessage:U.optional(U.string()),invalidReason:U.optional(U.string()),isValid:U.boolean(),payer:U.optional(U.string())});const hn=U.object({amount:U.optional(nn),errorMessage:U.optional(U.string()),errorReason:U.optional(U.string()),extensions:U.optional(ln),extra:U.optional(U.record(U.string(),U.unknown())),network:en,payer:U.optional(U.string()),success:U.boolean(),transaction:U.string()});function gn(e){let{extensions:t,resource:n,...r}=e;return sn.parse(r)}const _n=Yt(un),vn=Yt(mn),yn=Yt(hn);_n.encode,_n.decode;function bn(e){try{let t=JSON.parse(D.toString(e));return Sn(t)}catch{throw new Xt}}const xn=vn.encode;vn.decode,yn.encode,yn.decode;const Sn=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new Xt;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new Xt;let n=on.parse(t.resource),r=t.extensions===void 0?void 0:ln.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}};function Cn(e){let t=[H(e.accepted),H(e.resource),H(e.extensions)].join(`|`);return k.sha256(O.fromString(t),{as:`Hex`})}async function wn(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=gn(n);if(On(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?An(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?Cn({accepted:r,extensions:i,resource:n.resource}):Mn(),to:c(r.payTo),validAfter:(l-600).toString(),validBefore:(l+r.maxTimeoutSeconds).toString(),value:r.amount},d=await t.signTypedData({domain:{chainId:Dn(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:En});return xn({accepted:r,...i?{extensions:i}:{},payload:{authorization:u,signature:d},...n.resource?{resource:n.resource}:{},x402Version:2})}function Tn(e){let t=e.challenge.request,n;try{n=gn(t),On(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 En={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function Dn(e){return Number(e.slice(7))}function On(e,t){let n=Dn(t.network);if(e.networks&&!e.networks.includes(n))throw Error(`x402 exact chain ID is not allowed: ${n}.`);let r=e.currencies??e.assets;if(r?.some(e=>ze(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=c(t.asset);if(!r.some(n=>Ve(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=kn(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 kn(e,t){let n=e.currencies??e.assets,r=c(t.asset),i=n?.find(e=>Ve(e,r,t.network)),a=i?Be(i,t.network):void 0;return a?.decimals===void 0?e.decimals:a.decimals}function An(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:jn()}}}:e}function jn(){return Nn().slice(2)}function Mn(){return Nn()}function Nn(){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 Pn=Symbol.for(`mppx.x402.challenge`);function Fn(e){return Object.defineProperty(e,Pn,{value:!0}),e}function In(e){return!!e?.[Pn]}const Ln=[`authorization`],Rn=U.string().check(U.regex(/^\d+$/,`Invalid atomic amount`));U.object({name:U.string().check(U.minLength(1)),version:U.string().check(U.minLength(1))});const zn=U.object({chainId:U.number(),credentialTypes:U.optional(U.array(U.enum(Ln)).check(U.minLength(1))),decimals:U.optional(U.number()),permit2Address:U.optional(G()),splits:U.optional(U.array(U.object({amount:Rn,recipient:G()})))});U.object({amount:Rn,currency:G(),description:U.optional(U.string()),externalId:U.optional(U.string()),methodDetails:zn,recipient:G()});const Bn=U.object({amount:W(),chainId:U.number(),currency:G(),credentialTypes:U.optional(U.array(U.enum(Ln)).check(U.minLength(1))),decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),permit2Address:U.optional(G()),recipient:G(),splits:U.optional(U.array(U.object({amount:Rn,recipient:G()})))}),Vn=U.object({from:G(),nonce:K(),signature:q(),to:G(),type:U.literal(`authorization`),validAfter:Rn,validBefore:Rn,value:Rn}),Hn={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function Un(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function Wn(e){return k.keccak256(O.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function Gn(e){return`eip155:${e}`}function Kn(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const qn=qt({name:`evm`,intent:`charge`,schema:{credential:{payload:Vn},request:U.pipe(Bn,U.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 Jn(e){return Jt(qn,{canHandleChallenge({challenge:t}){return!Yn(t)||Tn({challenge:t,config:e})},context:U.object({account:U.optional(U.custom())}),async createCredential({challenge:t,context:n}){if(Yn(t))return wn({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(Xn(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=Zn(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return It(Ft({challenge:t,payload:{from:c(r.address),nonce:Wn(t),signature:await r.signTypedData({domain:Un({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:c(r.address),nonce:Wn(t),to:c(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:Hn}),to:c(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:Kn({address:c(r.address),chainId:i.methodDetails.chainId})}))}})}function Yn(e){return In(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function Xn(e,t){let n=t.methodDetails.chainId,r=Gn(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=>ze(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=c(t.currency);if(!i.some(t=>Ve(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=Qn(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 Zn(e,t){let n=e.currencies??e.assets,r=c(t.currency),i=Gn(t.methodDetails.chainId),a=n?.find(e=>Ve(e,r,i)),o=a?Be(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;throw Error(`EVM authorization requires token name and version.`)}function Qn(e,t){let n=e.currencies??e.assets,r=c(t.currency),i=Gn(t.methodDetails.chainId),a=n?.find(e=>Ve(e,r,i)),o=a?Be(a,i):void 0;return o?.decimals===void 0?e.decimals:o.decimals}function $n(e){return[$n.charge(e)]}(function(e){e.charge=Jn,e.assets=Ge,e.chains=Ke})($n||={});var er=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 nr(this,e)}},tr=class extends er{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 nr(e,t){if(t){let n=e?.cause;for(;n;){if(t(n))return n;n=n?.cause}return}let n=e;for(;n?.cause;)n=n.cause;return n}const X={mainnet:4217,testnet:42431},rr={ousd:ae(X.mainnet).address,usdc:c(se(X.mainnet).address),pathUsd:oe(X.mainnet).address},ir={[X.mainnet]:rr.usdc,[X.testnet]:rr.pathUsd},ar=Object.freeze({[X.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[X.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})});X.mainnet,X.testnet;const or={[X.mainnet]:`https://rpc.tempo.xyz`,[X.testnet]:`https://rpc.moderato.tempo.xyz`},Z=(()=>{let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes(`--no-color`))&&(!!n.FORCE_COLOR||t.includes(`--color`)||(e.stdout||{}).isTTY&&n.TERM!==`dumb`||!!n.CI),i=(e,t,n,r)=>{let i=``,a=0,o=r;do i+=e.substring(a,o)+n,a=o+t.length,o=e.indexOf(t,a);while(~o);return i+e.substring(a)},a=r?(e,t,n=e)=>r=>{let a=`${r}`,o=a.indexOf(t,e.length);return~o?e+i(a,t,n,o)+t:e+a+t}:()=>String;return{isColorSupported:r,reset:a(`\x1B[0m`,`\x1B[0m`),bold:a(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:a(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:a(`\x1B[3m`,`\x1B[23m`),underline:a(`\x1B[4m`,`\x1B[24m`),inverse:a(`\x1B[7m`,`\x1B[27m`),hidden:a(`\x1B[8m`,`\x1B[28m`),strikethrough:a(`\x1B[9m`,`\x1B[29m`),black:a(`\x1B[30m`,`\x1B[39m`),red:a(`\x1B[31m`,`\x1B[39m`),green:a(`\x1B[32m`,`\x1B[39m`),yellow:a(`\x1B[33m`,`\x1B[39m`),blue:a(`\x1B[34m`,`\x1B[39m`),magenta:a(`\x1B[35m`,`\x1B[39m`),cyan:a(`\x1B[36m`,`\x1B[39m`),white:a(`\x1B[37m`,`\x1B[39m`),gray:a(`\x1B[90m`,`\x1B[39m`),bgBlack:a(`\x1B[40m`,`\x1B[49m`),bgRed:a(`\x1B[41m`,`\x1B[49m`),bgGreen:a(`\x1B[42m`,`\x1B[49m`),bgYellow:a(`\x1B[43m`,`\x1B[49m`),bgBlue:a(`\x1B[44m`,`\x1B[49m`),bgMagenta:a(`\x1B[45m`,`\x1B[49m`),bgCyan:a(`\x1B[46m`,`\x1B[49m`),bgWhite:a(`\x1B[47m`,`\x1B[49m`),blackBright:a(`\x1B[90m`,`\x1B[39m`),redBright:a(`\x1B[91m`,`\x1B[39m`),greenBright:a(`\x1B[92m`,`\x1B[39m`),yellowBright:a(`\x1B[93m`,`\x1B[39m`),blueBright:a(`\x1B[94m`,`\x1B[39m`),magentaBright:a(`\x1B[95m`,`\x1B[39m`),cyanBright:a(`\x1B[96m`,`\x1B[39m`),whiteBright:a(`\x1B[97m`,`\x1B[39m`),bgBlackBright:a(`\x1B[100m`,`\x1B[49m`),bgRedBright:a(`\x1B[101m`,`\x1B[49m`),bgGreenBright:a(`\x1B[102m`,`\x1B[49m`),bgYellowBright:a(`\x1B[103m`,`\x1B[49m`),bgBlueBright:a(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:a(`\x1B[105m`,`\x1B[49m`),bgCyanBright:a(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:a(`\x1B[107m`,`\x1B[49m`),link(e,t,n){return r?`\x1b]8;;${e}\x07${n?t:Z.underline(t)}\x1b]8;;\x07`:t}}})();function sr(e,t){return Z.link(e,t)}function cr(e){return e.startsWith(`tempo:`)}function lr(e,t,n=6,r){let[i,a]=(Number(e)/10**n).toString().split(`.`),o=i.replace(/\B(?=(\d{3})+(?!\d))/g,`_`),s=r?.explorerUrl&&r.token?Z.dim(Z.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):Z.dim(t);return`${a?`${o}.${a}`:o} ${s}`}const ur={mainnet:or[X.mainnet],testnet:or[X.testnet]};function dr(e,t={}){return e??(t.network?ur[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}async function fr(t={}){let n=dr(t.rpcUrl,{network:t.network});if(!n)return R;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 pr(e){return typeof e==`bigint`?e:e.amount}function mr(e){return e.id!==R.id}async function hr(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(pr).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 gr(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:1e4}function _r(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function vr(e){return new tr({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 yr(e){if(e&&_r(e,`secret-tool`))throw vr(e)}function br(e,t){return new Promise(n=>{N.execFile(e,t,{timeout:gr()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function xr(){let e=I.join(process.env.XDG_CONFIG_HOME||I.join(F.homedir(),`.config`),`mppx`,`default`);return{get(){try{return P.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(t){P.mkdirSync(I.dirname(e),{recursive:!0}),P.writeFileSync(e,t,`utf-8`)},clear(){try{P.unlinkSync(e)}catch{}}}}function Sr(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:xr().get())}function Cr(e=`main`){let t=`mppx`;return{async list(){let e=F.platform();if(e===`darwin`){let{stdout:e,error:n}=await br(`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 br(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(yr(r),r)return[];let i=`${e}\n${n}`,a=[],o=i.matchAll(/\baccount = (.+)/g);for(let e of o)e[1]&&a.push(e[1]);return a}throw Error(`Unsupported platform: ${e}`)},async get(){let n=F.platform();if(n===`darwin`){let{stdout:n,error:r}=await br(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await br(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return yr(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=F.platform();if(r===`darwin`){await br(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await br(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=N.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),gr());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(_r(e,`secret-tool`)?vr(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=F.platform();if(n===`darwin`){await br(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await br(`secret-tool`,[`clear`,`service`,t,`account`,e]);yr(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function wr(e){let{privateKeyToAccount:t}=await import(`viem/accounts`),n=process.env.MPPX_PRIVATE_KEY?.trim();if(n)return{account:t(n),source:`environment`};let r=Sr(e),i=await Cr(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function Tr(e){return(await wr(e)).account}function Er(e){return e}function Dr(){return Er({method:`evm`,supports:e=>e.method===`evm`&&!In(e),async setup({challenge:t,options:n}){let r=t.request,i=r.methodDetails,o=i?.chainId,s=o?Or(o):void 0,c=r.currency,l=await Tr(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:[...$n({account:l,currencies:d})]}}})}function Or(e){return Object.values(ne).find(t=>t.id===e)}function kr(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 Ar=U.object({customer:U.optional(U.string().check(U.minLength(1))),hooks:U.optional(U.object({inputs:U.object({tax:U.object({calculation:U.string().check(U.minLength(1))})})})),metadata:U.optional(U.record(U.string(),U.string())),receipt_email:U.optional(U.string().check(U.minLength(1)))}),jr=U.custom(e=>typeof e==`function`),Mr=U.union([Ar,jr]),Nr=qt({name:`stripe`,intent:`charge`,schema:{credential:{payload:U.object({externalId:U.optional(U.string()),spt:U.string()})},request:U.pipe(U.object({amount:W(),currency:U.string(),decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),metadata:U.optional(U.record(U.string(),U.string())),networkId:U.string(),paymentIntentOptions:U.optional(Mr),paymentMethodTypes:U.array(U.string()).check(U.minLength(1)),recipient:U.optional(U.string())}),U.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:kr(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});function Pr(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return Jt(Nr,{context:U.object({paymentMethod:U.optional(U.string())}),async createCredential({challenge:e,context:a}){let o=a?.paymentMethod??i;if(!o)throw Error(`paymentMethod is required (pass via context or parameters)`);let s=e.request.amount,c=e.request.currency,l=typeof e.request.externalId==`string`?e.request.externalId:void 0,u=e.request.methodDetails?.networkId;if(!u)throw Error(`networkId is required in challenge.methodDetails`);let d=e.request.methodDetails?.metadata;if(d?.externalId)throw Error(`methodDetails.metadata.externalId is reserved; use credential externalId instead`);let f=e.expires?Math.floor(new Date(e.expires).getTime()/1e3):Math.floor(Date.now()/1e3)+3600,p=await n({amount:s,challenge:e,client:t,currency:c,expiresAt:f,metadata:d,networkId:u,paymentMethod:o}),m=l??r;return It({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function Fr(e){return[Pr(e)]}(function(e){e.charge=Pr})(Fr||={});function Ir(){return Er({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=Rr(L.object({paymentMethod:L.string(),secretKey:L.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new tr({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:[Fr.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=Lr(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 tr({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${(await d.json()).error.message}`,exitCode:77})}else throw new tr({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&&Lr(e)?`/test`:``}/payments/${t}`;return Z.link(n,t,!0)}}})}function Lr(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function Rr(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 zr=Symbol.for(`mppx.fetch.skipPayment`);Object.freeze({phase:`unproved`});function Br(e,t,n={}){return async(r,i)=>{let a=new Request(r,i),o=Vr(a.headers)??n.challenge,{response:s}=await t.send((t,n)=>e(t,{...n,...i?.[zr]?{[zr]:!0}:{}}),a,{...n,challenge:o});if(s.status===402&&o)for(let e of Hr(s))e.method===o.method&&e.intent===o.intent&&await t.challenge(s,{challenge:e},a.url);return s}}function Vr(e){for(let[,t]of e){let e=Lt(t);if(e)try{return Mt(e).challenge}catch{}}}function Hr(e){try{return St(e)}catch{return[]}}const Ur=Symbol(`mppx.deferredContext`);function Wr(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=Yr(n)}return t}function Gr(e,t){let n=Wr(e),r=ni(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[Yr(e)]??1,index:t}));return{definition:r,entries:i,header:qr(i),keys:n}}function Kr(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)=>ei(e,t))}function qr(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${oi(n)}`}).join(`, `)}function Jr(e,t,n,r){let i=new Map;for(let e of t){let t=Yr(e),n=i.get(t);n?n.push(e):i.set(t,[e])}return e.flatMap((e,t)=>{let a=i.get(Yr(e));if(!a)return[];let o=Xr(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)=>$r(e.challenge)-$r(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function Yr(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function Xr(e,t){let n;for(let r of t){if(!Zr(e,r))continue;let t={...r,specificity:Qr(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 Zr(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function Qr(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function $r(e){return+!!In(e)}function ei(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}`);si(r,`method`),si(i,`intent`);let a=1;for(let t of ti(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=ii(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function ti(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function ni(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>Yr(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]=ri(t,`payment preference "${e}"`)}return a}function ri(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return ai(e,t)}function ii(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 ai(Number(e),t)}function ai(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 si(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}function ci(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 si=[V.authorization,Xt,`PAYMENT-RESPONSE`,Zt];function ci(e,t,n){let r=new Headers(e.headers);for(let e of si)e===V.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}function li(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 ui(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 di=1048576,fi=new WeakMap;function pi(e){let t=li(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 hi(e){if(!e||typeof e!=`object`)return;let t=e?.challenges;if(!Array.isArray(t)||t.length===0)return;let n=[];for(let e of t){let t=ut.safeParse(e);if(!t.success)return;n.push(t.data)}let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function gi(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:hi(e.error.data):hi(e.result?._meta?.[`org.paymentauth/payment-required`])}function _i(e,t){return!e||e.id!==t?[]:gi(e)?.challenges??[]}async function vi(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=oi(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>di)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function yi(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>di)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function bi(e){let t=fi.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>di)){if(t.includes(`application/json`))return yi(e);if(t.includes(`text/event-stream`))return vi(e)}})();return fi.set(e,n),n}function xi(){return{getChallenges(e,t){let n=pi(t);return e.status===402||n===void 0?[]:bi(e).then(e=>_i(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=jt(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}function Si(){return{getChallenges(e){let t=e.headers.get(V.wwwAuthenticate);return e.status!==402||!t||!yt(t)?[]:xt(e)},setCredential(e,t,n){return ci(e,n?.challenge?Tt(n.challenge):V.authorization,t)}}}function Ci(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(Xt);if(!t)return[];let n=vn(t);return n.accepts.flatMap((e,t)=>{let r=an.safeParse(e);if(!r.success)return[];let i=r.data;return Nn(dt({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 ci(e,Zt,t)}}}function wi(e){return e}function Ti(){let e=[Si(),Ci(),xi()],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 wi({name:`http`,isPaymentRequired(e,t){if(e.status===402)return!0;let n=r(e,t);return n instanceof Promise?n.then(e=>e.length>0):n.length>0},getChallenges(e,t){return r(e,t)},setCredential(n,r,i){let a=i?.challenge?t.get(i.challenge):void 0,o=e[0];if(!a&&!o)throw Error(`No protocol to attach the credential.`);return(a??o).setCredential(n,r,i)}})}const Ei=new WeakMap;function Di(e,t){return Ei.set(e,t),e}function Oi(e){return Ei.has(e)}function ki(e,t){return Promise.resolve(Ei.get(e)?.(t))}function Ai(e){return Ei.get(e)}const ji=new WeakMap,Mi=new WeakMap,Ni=new WeakMap,Pi=new WeakMap;function Fi(e,t){return ji.set(e,t),e}function Ii(e){ji.delete(e)}function Li(e,t,n){ji.has(e)&&Mi.set(t,n)}function Ri(e){return Mi.get(e)}function zi(e,t){return Promise.resolve(ji.get(e)?.(t)??t.response)}function Bi(e,t){return Pi.set(e,t),e}function Vi(e,t){try{return Pi.get(e)?.(t)}catch{return}}function Hi(e,t){Ni.set(e,t)}function Ui(e){return Ni.get(e)??Mi.get(e)?.origin}function Wi(e,t,n){if(!Gi(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&&Ki(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 Gi(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Ki(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}const qi=Symbol.for(`mppx.fetch.wrapper`),Ji=Symbol.for(`mppx.fetch.identity`),Yi=Symbol.for(`mppx.fetch.skipPayment`),Xi=65536,Zi=new WeakMap;async function Qi(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>Xi){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,Xi),{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 $i(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=Ti(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&Ca(e.fetch)),d=e.eventDispatcher??na(),f=t??Ur(a),p=wa(r),m=async(e,t,n)=>u?u.send(p,new Request(e,t),n):{response:await p(e,t),headers:[]},h=async(e,t,r)=>{let g=Sa(e,t?.headers),_=g.has(V.acceptPayment),v=ka(g,f),y=ba(e,t,g),b=ya(e,t,g,v.header,_,n),x=await m(Ta(b.input),b.init),S=x.response,C=x.headers,w=xa(b.init,await y);if(t?.[Yi]||ui(w)||!await c.isPaymentRequired(S,w))return S;let ee=t?.context,{context:T,orderChallenges:te,...ne}=w??{},E,D,O,k,A;try{for(let n=0;n<i;n++){D=await c.getChallenges(S,w);let i=(await Aa(Kr(D,a,v.entries,ee),te??s))[0];if(!i){if(await $i(k,{challenges:D,response:S,status:`rejected`}),n>0)return S;throw Error(`No method found for challenges: ${D.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let f=i.challenge;E=f,O=i.method,E.expires&&Wt(E.expires,E.id),await u?.challenge(S,{challenge:f},Pa(b.input).href);let g=await Ia(S,b.input,b.input,ne);Wi(f,()=>Pa(g),l);let _=k,y=ft(f),x=_?.method===i.method&&_?.key===y,T=!1;if(_){let e=await $i(_,{challenges:D,response:S,status:x?`pending`:`rejected`});T=x&&!e}k=T?_:void 0;let j=sa(async n=>{if(n===void 0&&T&&_)return _.promise;T&&_&&(await $i(_,{status:`rejected`}),k=void 0),Ea(e,t)?.throwIfAborted();let r=n??ee;if(!Oi(i.method))return Oa(f,i.method,r);let a={origin:Pa(g).origin,prepare:()=>ki(i.method,{challenge:f,context:r,fetch:u?Rr(p,u,{challenge:f}):p,input:g,signal:Ea(e,t)})},o=a.prepare().then(()=>Oa(f,i.method,r,a));return k={context:r,attempt:a,key:n===void 0?y:void 0,method:i.method,promise:o},o}),M=await d.emit(`challenge.received`,ca({challenge:f,challenges:D,createCredential:j,init:t,input:e,method:i.method,response:S}))??(o?await o(E,{createCredential:j}):void 0)??await j(),N=k;N&&await N.promise.catch(()=>void 0)!==M&&(await $i(N,{status:`rejected`}),k=void 0);let P=k?k.context:ee;Da(M),await d.emit(`credential.created`,la({challenge:f,credential:M,init:t,input:e,method:i.method,response:S}));let F=e=>new Vt({cause:e,challenge:f,credential:M,transactionHash:Vi(i.method,M)});try{({response:S}=await m(g,{...c.setCredential({...ne,headers:b.headers},M,{challenge:f}),redirect:`manual`},{challenge:f,headers:C}))}catch(e){throw A=F(e),e}let I=await c.isPaymentRequired(S,w);if(I||(await $i(N,{response:S,status:S.status>=300&&S.status<400?`pending`:S.ok?`accepted`:`rejected`}),k=void 0),S.ok&&ra(d,`payment.response`)&&await d.emit(`payment.response`,ua({challenge:f,credential:M,init:t,input:e,method:i.method,response:S})),!I){if(S.status>=500&&ra(d,`payment.failed`)){try{S=await Qi(S)}catch(e){throw A=F(e),S=new Response(null,{headers:S.headers,status:S.status,statusText:S.statusText}),e}await d.emit(`payment.failed`,da({challenge:f,challenges:D,error:F(),init:t,input:e,method:i.method,response:S}))}return S.ok?zi(i.method,{context:P,challenge:f,credential:M,fetch:p,headers:b.headers,input:g,...r?{refetch:()=>h(Ta(b.input),t,!1)}:{},response:S,signal:Ea(e,t)}):S}}D=void 0;try{D=await c.getChallenges(S,w)}catch{}return await $i(k,{challenges:D,response:S,status:`rejected`}),S}catch(n){throw await $i(k,{challenges:D,response:S,status:`rejected`}),await d.emit(`payment.failed`,da({challenge:E,challenges:D,error:A??n,init:t,input:e,method:O,response:S})),n}},g=(e,t)=>h(e,t,!0);return g[qi]=p,u&&(g[Ji]=u),g}function ta(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 na(){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 ia(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await oa(e[`*`],t,n),r}case`credential.created`:await aa(e[`credential.created`],n),await oa(e[`*`],t,n);return;case`payment.failed`:await aa(e[`payment.failed`],n),await oa(e[`*`],t,n);return;case`payment.response`:await aa(e[`payment.response`],n),await oa(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 Zi.set(t,t=>e[t].size>0||e[`*`].size>0),t}function ra(e,t){return Zi.get(e)?.(t)??!0}async function ia(e,t){try{return await e(t)}catch{return}}async function aa(e,t){for(let n of e)try{await n(t)}catch{}}async function oa(e,t,n){await aa(e,Object.freeze({name:t,payload:n}))}function sa(e){let t;return n=>(t??=e(n),t)}function ca(e){return Object.freeze({challenge:ga(e.challenge),challenges:e.challenges.map(e=>ga(e)),createCredential:e.createCredential,init:fa(e.init),input:pa(e.input),method:ma(e.method),response:ha(e.response)})}function la(e){return Object.freeze({challenge:ga(e.challenge),credential:e.credential,init:fa(e.init),input:pa(e.input),method:ma(e.method),...e.response===void 0?{}:{response:ha(e.response)}})}function ua(e){return Object.freeze({challenge:ga(e.challenge),credential:e.credential,init:fa(e.init),input:pa(e.input),method:ma(e.method),response:ha(e.response)})}function da(e){return Object.freeze({...e.challenge?{challenge:ga(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>ga(e))}:{},error:e.error,init:fa(e.init),input:pa(e.input),...e.method?{method:ma(e.method)}:{},...e.response===void 0?{}:{response:ha(e.response)}})}function fa(e){if(e)return va({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function pa(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function ma(e){return va(Object.assign({},e))}function ha(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 ga(e)}function ga(e){try{return _a(structuredClone(e))}catch{return va(e)}}function _a(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))_a(t);return e}function va(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function ya(e,t,n,r,i,a){let o=!!r&&!i&&ja(e,a);if(!o)return{headers:n,init:t,input:e};let s=new Headers(e instanceof Request?e.headers:void 0);return n.forEach((e,t)=>{s.set(t,e)}),s.set(V.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function 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 xa(e,t){return t===void 0?e:{...e,body:t}}function Sa(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function Ca(e){return e[Ji]}function wa(e){let t=e;for(;t[qi];)t=t[qi];return t}function Ta(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function Ea(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function Da(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 Oa(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&&Hi(a,r.origin),r&&Li(t,a,r),t.createCredential(a)}function ka(e,t){let n=e.get(V.acceptPayment);if(!n)return t;try{return{...t,entries:Wr(n),header:n}}catch{return t}}async function Aa(e,t){return t?t(e):e}function ja(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=Pa(e);return t===`same-origin`?!Na()||n.origin===globalThis.location.origin:t.origins.some(e=>Ma(n,e))}function Ma(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 Na(){return globalThis.location!==void 0}function Pa(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,Na()?globalThis.location.href:void 0)}function Fa(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 Ia(e,t,n,r){if(Fa(t,r),!e.url)return t;let i=new URL(e.url),a=Pa(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 La(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 Ra(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}const za={[R.id]:R,[re.id]:re};function Ba(e,t={}){return l(e.url,{fetchFn:e.fetch,fetchOptions:{headers:Ra(e)},...t})}function Va(r){let{chain:i,getClient:a,remoteFeePayer:o,rpcUrl:s}=r;return a?!i?.serializers&&!o?a:async e=>{let r=await a(e),s=r;if(o&&r.transport.key!==`feePayer`){let e=r.request.bind(r),i=fe(n({request:t=>e(t)},{retryCount:0}),Ba(o,{retryCount:r.transport.retryCount}))({account:r.account,chain:r.chain,pollingInterval:r.pollingInterval,retryCount:0}),a=t({...i.config,retryCount:0},i.value);s=Object.assign({},r,{request:a.request,transport:{...a.config,...a.value}})}return!i?.serializers||s.chain?.serializers?.transaction?s:Object.assign({},s,{chain:{...i,...e.chainId===void 0?{}:{id:e.chainId},...s.chain,formatters:s.chain?.formatters??i.formatters,prepareTransactionRequest:s.chain?.prepareTransactionRequest??i.prepareTransactionRequest,serializers:s.chain?.serializers?.transaction?s.chain.serializers:i.serializers}})}:({chainId:t})=>{if(!s)throw Error("No `rpcUrl` provided.");let n=t||Number(Object.keys(s)[0]),r=s[n];if(!r)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let a=o?fe(l(r),Ba(o)):l(r);return e({chain:za[n]??{...i,id:n},transport:a})}}function Ha(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 Ua(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}const Wa=A.slice(k.keccak256(O.fromString(`mpp`),{as:`Hex`}),0,4);function Ga(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,10))}function Ka(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(A.toBytes(Wa),0),i[4]=1,i.set(Ga(t),5),n&&i.set(Ga(n),15),i.set(qa(r),25),A.fromBytes(i)}function qa(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,7))}function Ja(e,t){return _e.resolve(e).toLowerCase()===_e.resolve(t).toLowerCase()}const Ya=10000n,Xa=[tr.pathUsd,tr.usdc,tr.ousd];async function Za(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||Ja(t,i)||c.some(e=>Ja(e,t))||c.push(t)}let l=await Promise.allSettled([b(e,{...z.token.getBalance.call(e,{account:n,token:i}),account:null}),...c.map(t=>b(e,{...z.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/Ya;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 z.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:f});if(t<=0n||t>m)continue;let n=t+t*p/Ya,o=n<m?n:m;if(r>=o)return[z.token.approve.call(e,{amount:o,spender:le.stablecoinDex,token:a}),z.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:f,maxAmountIn:o})]}catch{}}throw new $a({currency:i})}function Qa(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`&&Ja(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var $a=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}};function eo(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=>Ja(e,t))||e.some(e=>Ja(e,t))||e.push(t))}async function no(e,t,n){try{return(await z.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function ro(e){let t=e.chain?.feeToken;if(t)return ue.toAddress(t);let n=e.chain?.id;return n?nr[n]:void 0}function io(e){let t=[];return to(t,tr.pathUsd),to(t,nr[e]),t}async function ao(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 z.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),to(o,ro(i),n),!a)for(let e of r??[])to(o,e,n);for(let e of o)if(await no(i,t,e))return e;return o[0]}const oo=p([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]);function so(e){if(e!==void 0)return rr[e]}function co(e){let t=so(e.chainId);return!!t&&u(e.currency,{strict:!1})&&d(e.currency,t.token)}function lo(e){let t=so(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let i=BigInt(n.amount),a=n.memo;return{calls:[{data:r({abi:se.tip20,functionName:`approve`,args:[t.swap,i]}),to:t.token},{data:r({abi:oo,functionName:`swapTo`,args:[t.token,i,e.currency,n.recipient,a]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:i,memo:a,recipient:n.recipient}]}}async function uo(e,t){let n=lo(t);if(n)try{return await b(e,z.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await g(e,{account:t.account,calls:n.calls}),n)}catch{return}}const fo=10n**BigInt(4);function po(e={}){let{address:t,amount:n,chainId:r=X.mainnet}=e;if(r!==X.mainnet)return;let i=new URL(`https://wallet.tempo.xyz/agent?action=fund&intent=mach&chainId=4217`);if(t&&u(t,{strict:!1})&&i.searchParams.set(`address`,s(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 mo(e,t){let n=so(t.chainId);if(!n)return;let r=await b(e,z.token.getBalance.call(e,{account:t.account,token:n.token})).catch(()=>void 0);return typeof r==`bigint`?r:void 0}async function ho(e,t){let{account:n,amount:r,chainId:i}=t,o=await mo(e,{account:n,chainId:i});if(o===void 0||o>=r)return;let s=e=>`${a(e,6)} MACH`,c=r-o;return{fundingUrl:po({address:n,amount:c,chainId:i}),reason:`requested ${s(r)}, available ${s(o)}`,shortfall:c}}async function go(e,t){let n=await ho(e,t);if(n)return new Ut({fundingUrl:n.fundingUrl,reason:n.reason})}const _o={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]};function vo(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 bo(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:vo(n),types:_o,primaryType:`Proof`,message:yo({account:t,challengeId:r,realm:i})}}function xo(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const So=7200n,Co=64n,wo=o({abi:se.zonePortal,name:`WithdrawalProcessed`});function To(e){return Number.isInteger(e)&&e>0&&e<4217e5}function Eo(e,t){return To(t)?e===!0||(e?.includes(t)??!1):!1}function Do(e){return le.zonePortal(e)}function Oo(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 ko(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 Ao(e){return k.keccak256(E.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function jo(e,t){let{blockNumber:n,sender:r,transactionHash:i}=t,a=t=>b(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>Co)throw Error(`Zone withdrawal transaction ${i} has ${s-o} candidate sender tags, more than ${Co}.`);let c=[];for(let e=o+1n;e<=s;e++)c.push(Ao({fallbackNonce:e,sender:r,transactionHash:i}));return c}async function Mo(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 _(e,{cacheTime:0}),a=i>So?i-So:0n,o=Date.now()+r;for(;;){if(a<=i){let[r]=await v(e,{address:t.portal,event:wo,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 _(e,{cacheTime:0})}}const No=[`push`,`pull`],Po=U.object({amount:W(),memo:U.optional(K()),recipient:U.pipe(U.string(),U.transform(e=>e))}),Fo=(1n<<64n)-1n,Io={dev_second:1n,day:86400n,week:604800n},Lo=U.pipe(G(),U.transform(e=>e.toLowerCase())),Ro=U.object({accessKeyAddress:Lo,keyType:U.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:U.optional(U.pipe(U.string().check(U.regex(/^0x[0-9a-fA-F]{120}$/)),U.transform(e=>e)))}),zo=U.object({accessKey:U.optional(Ro),chainId:U.optional(U.number())}),Bo=at(`subscriptionExpires must be a valid date`).check(U.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),Vo=U.enum([`dev_second`,`day`,`week`]),Ho=U.pipe(U.union([U.string(),U.bigint(),U.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),U.transform(e=>e.toString())).check(U.regex(/^[1-9]\d*$/,`Invalid periodCount`),U.refine(e=>{try{return BigInt(e)<=Fo}catch{return!1}},`periodCount exceeds uint64`));function Uo(e){return U.refine(e=>{let{amount:t,decimals:n}=e;return h(t,n)>0n},e)}function Wo(e){let{periodCount:t,periodUnit:n}=e;try{let e=Io[n];return e!==void 0&&BigInt(t)*e<=Fo}catch{return!1}}const Go=Gt({name:`tempo`,intent:`charge`,schema:{credential:{payload:U.discriminatedUnion(`type`,[U.object({hash:K(),type:U.literal(`hash`)}),U.object({signature:q(),type:U.literal(`transaction`)}),U.object({signature:q(),type:U.literal(`proof`)}),U.object({hash:K(),senderTag:K(),type:U.literal(`zone`),zoneId:U.number().check(U.refine(To,`Invalid Zone ID`))})])},request:U.pipe(U.object({machineTokenEnabled:U.optional(U.boolean()),amount:W(),chainId:U.optional(U.number()),currency:U.string(),decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),feePayer:U.optional(U.pipe(U.union([U.boolean(),U.custom()]),U.transform(e=>typeof e==`object`||e))),memo:U.optional(U.never()),recipient:U.optional(U.string()),splits:U.optional(U.array(Po).check(U.minLength(1),U.maxLength(10))),supportedModes:U.optional(U.array(U.enum(No)).check(U.minLength(1))),zones:U.optional(U.union([U.literal(!0),U.array(U.number().check(U.refine(To,`Invalid Zone ID`))).check(U.minLength(1))]))}).check(U.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=h(e,t),i=n.reduce((e,n)=>e+h(n.amount,t),0n);return n.every(e=>h(e.amount,t)>0n)&&i<r},`Invalid splits`)),U.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,zones:c,...l})=>({...l,amount:h(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:h(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),Ko=Gt({name:`tempo`,intent:`session`,schema:{credential:{payload:U.discriminatedUnion(`action`,[U.object({action:U.literal(`open`),authorizedSigner:U.optional(U.string()),channelId:K(),cumulativeAmount:W(),descriptor:U.optional(U.custom()),signature:q(),transaction:q(),type:U.literal(`transaction`)}),U.object({action:U.literal(`topUp`),additionalDeposit:W(),channelId:K(),descriptor:U.optional(U.custom()),transaction:q(),type:U.literal(`transaction`)}),U.object({action:U.literal(`voucher`),channelId:K(),cumulativeAmount:W(),descriptor:U.optional(U.custom()),signature:q()}),U.object({action:U.literal(`close`),channelId:K(),closeSignature:q(),cumulativeAmount:W(),descriptor:U.optional(U.custom()),signature:q()})])},request:U.pipe(U.object({amount:W(),chainId:U.optional(U.number()),channelId:U.optional(K()),currency:U.string(),decimals:U.number(),escrowContract:U.optional(U.string()),feePayer:U.optional(U.pipe(U.union([U.boolean(),U.custom()]),U.transform(e=>typeof e==`object`||e))),feeToken:U.optional(G()),minVoucherDelta:U.optional(W()),operator:U.optional(G()),recipient:U.optional(U.string()),sessionProtocol:U.optional(U.enum([et.v2,et.v1])),sessionSnapshot:U.optional(U.custom()),suggestedDeposit:U.optional(W()),unitType:U.string()}).check(U.refine(({amount:e,decimals:t})=>h(e,t)>0n,`Session amount must be greater than 0`)),U.transform(({amount:e,chainId:t,channelId:n,decimals:r,escrowContract:i,feePayer:a,feeToken:o,minVoucherDelta:s,operator:c,sessionProtocol:l,sessionSnapshot:u,suggestedDeposit:d,...f})=>({...f,amount:h(e,r).toString(),...d?{suggestedDeposit:h(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:h(s,r).toString()},...t!==void 0&&{chainId:t},...a!==void 0&&{feePayer:a},...o!==void 0&&{feeToken:o},...c!==void 0&&{operator:c},...l!==void 0&&{[$e.sessionProtocol]:l},...u!==void 0&&{[$e.sessionSnapshot]:u}}})))}}),qo=Gt({name:`tempo`,intent:`subscription`,schema:{credential:{payload:U.object({signature:q(),type:U.literal(`keyAuthorization`)})},request:U.pipe(U.object({amount:W(),accessKey:U.optional(Ro),chainId:U.optional(U.number()),currency:Lo,decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),methodDetails:U.optional(zo),periodCount:Ho,periodUnit:Vo,recipient:Lo,subscriptionExpires:Bo}).check(Uo(`Subscription amount must be greater than 0`),U.refine(Wo,`Subscription period exceeds uint64`)),U.transform(({accessKey:e,amount:t,chainId:n,decimals:r,methodDetails:i,subscriptionExpires:a,...o})=>{let s={...i,...e!==void 0&&{accessKey:e},...n!==void 0&&{chainId:n}};return{...o,amount:h(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}}),Jo=U.object({account:U.optional(U.custom()),autoSwap:U.optional(U.custom()),feeToken:U.optional(U.custom()),mode:U.optional(U.enum(No))});function Yo(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??[])is(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=Va({chain:R,getClient:e.getClient,rpcUrl:ir}),i=La({account:e.account});$o(e.zone);let a=new Map,o=Kt(Go,{canHandleChallenge({challenge:t}){try{return as(e,n,t.request),!0}catch{return!1}},context:Jo,async createCredential({challenge:o,context:s}){as(e,n,o.request);let c=o.request.methodDetails?.chainId,l=c??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),u=await r({chainId:l});Ha(u,l);let d=l??u.chain?.id;if(Ua(e.allowedChainIds,d),d===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");c===void 0&&as(e,n,o.request,d);let{request:f}=o,{amount:p,methodDetails:m}=f,h=m?.supportedModes??[`pull`,`push`],g=e.zone?.client.chain,_=e.zone?e.zone.zoneId??Oo(g?.id??0):void 0,v=g?.sourceId??(g?ko(g.id):void 0),b=s?.mode??e.mode;if(BigInt(p)>0n&&e.zone&&_!==void 0&&v===d&&h.includes(`push`)&&(b===void 0||b===`push`)&&Eo(m?.zones,_)&&!m?.splits&&(a.has(ns(o))||es(o.expires,e.zone.settlementTimeoutMs)))return Qo({challenge:o,clientId:t,client:u,pending:a,zone:e.zone,zoneId:_});let S=i(u,s),T=async t=>await e.resolveAccount?.({account:S,chainId:d,operation:t})??S;if(BigInt(p)===0n){let e=await T({kind:`signPaymentProof`});return Ft({challenge:o,payload:{signature:await ee(u,{account:e,...bo({account:e.address,chainId:d,challengeId:o.id,realm:o.realm})}),type:`proof`},source:xo({address:e.address,chainId:d})})}let te=f.currency,ne=co({chainId:d,currency:te}),E=Ka({challengeId:o.id,clientId:t,serverId:o.realm}),D=eo({amount:p,methodDetails:{...m,memo:E},recipient:f.recipient}),O=D.map(e=>z.token.transfer.call(u,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:te})),k=Qa(s?.autoSwap??e.autoSwap,Xa),A=m?.machineTokenEnabled===!0?lo({chainId:d,currency:te,transfers:D}):void 0,j=S,M,N=!1;if(A){let e=await(async()=>{try{return await T({calls:A.calls,kind:`executeCalls`})}catch{return}})();e&&(M=await uo(u,{account:e.address,chainId:d,currency:te,transfers:D}),M?j=e:N=!0)}let P;if(!M&&(j=await T({kind:`executeCalls`,...k?{}:{calls:O}}),P=k?await Za(u,{account:j.address,amountOut:BigInt(p),tokenOut:te,tokenIn:k.tokenIn,slippage:k.slippage,maxAmountIn:k.maxAmountIn}):void 0,N&&!k)){let e=await Xo(u,{account:j.address,amount:BigInt(p),chainId:d,currency:te});if(e)throw e}let F=M?.calls??[...P??[],...O],I=io(d),L=(s?.feeToken??e.feeToken)||(M||ne?await ao({account:j.address,allowedTokens:I,candidateTokens:I,client:u,prioritizeCandidates:!0}):void 0),R=(()=>{let t=s?.mode??e.mode;if(t){if(!h.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=j.type===`json-rpc`?`push`:`pull`;return h.includes(n)?n:h[0]})(),re=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!o.expires)return e;let t=Math.floor(new Date(o.expires).getTime()/1e3)+1;return Math.min(e,t)})();if(R===`push`){let{receipts:e}=j.type===`local`?{receipts:[await C(u,{account:j,calls:F,...L?{feeToken:L}:{},nonceKey:`expiring`,validBefore:re})]}:await x(u,{account:j,...L?{capabilities:{feeToken:L}}:{},calls:F,experimental_fallback:F.length===1,forceAtomic:F.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return Ft({challenge:o,payload:{hash:t,type:`hash`},source:xo({address:j.address,chainId:d})})}let ie=()=>{if(m?.feePayer!==!0)return;let e=15e3,t=o.expires?new Date(o.expires).getTime():1/0,n=Date.now();if(!(t-n>=e))throw Error(`Sponsored challenge expires in less than 15 seconds; the fee payer would reject the transaction. Request a new challenge.`);if(!(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 y(u,{account:j,calls:F,...L?{feeToken:L}:{},nonceKey:`expiring`,validBefore:re});if(ae.gas=(ae.gas??0n)+5000n,m?.feePayer){let e=ae;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return ie(),Ft({challenge:o,payload:{signature:await w(u,ae),type:`transaction`},source:xo({address:j.address,chainId:d})})}}),s=new Map,c=async t=>{as(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 Bi({...o,createCredential:c},Zo)}async function Xo(e,t){let{account:n,amount:r,chainId:i,currency:a}=t,o=await b(e,z.token.getBalance.call(e,{account:n,token:a})).catch(()=>void 0);if(!(typeof o!=`bigint`||o>=r))return go(e,{account:n,amount:r,chainId:i})}function Zo(e){let t=Go.schema.credential.payload.safeParse(jt(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 f(r)}async function Qo(e){let{challenge:t,client:n,pending:r,zone:i,zoneId:a}=e,o=t.request.recipient,s=ns(t),c=r.get(s);if(!c){let t={sent:!1};c=rs(e,t),r.set(s,c),c.catch(()=>{t.sent||r.delete(s)})}let l=await c,u=l.senderTags??await jo(i.client,l).catch(e=>{let t=Error(`Zone withdrawal transaction ${l.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}),d;try{d=await Mo(n,{portal:Do(a),senderTags:u,timeoutMs:ts(t.expires,i.settlementTimeoutMs),to:o})}catch(e){throw new Ht({cause:e,challengeId:t.id,senderTags:u,zoneId:a})}r.delete(s);let{hash:f,senderTag:p}=d;return Ft({challenge:t,payload:{hash:f,senderTag:p,type:`zone`,zoneId:a}})}function $o(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||ko(n)===void 0)return;let r=Oo(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function es(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+15e3}function ts(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function ns(e){return JSON.stringify(e)}async function rs(e,t){let{challenge:n,clientId:r,zone:i}=e,a=n.request,o=i.client.account;if(!o)throw Error("`zone.client` requires an account.");let s=BigInt(a.amount),c=a.currency,l=a.recipient,u=Ka({challengeId:n.id,clientId:r,serverId:n.realm}),d=await z.zone.getWithdrawalFee(i.client),[,p]=z.zone.requestWithdrawal.calls({amount:s,fallbackRecipient:o.address,memo:u,to:l,token:c}),h=await y(i.client,{account:o,calls:[z.token.approve.call({amount:s+d,spender:le.zoneOutbox,token:c}),p]}),g=await w(i.client,h);t.sent=!0;let _=f(g),v=await S(i.client,{serializedTransaction:g}).catch(e=>T(i.client,{hash:_,timeout:15e3}).catch(()=>{let t=Error(`Zone withdrawal outcome is unknown: transaction ${_} may have been sent. Retrying this challenge does not withdraw again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),t}));if(v.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${v.transactionHash} reverted.`);let[b]=m({abi:se.zoneOutbox,eventName:`WithdrawalRequested`,logs:v.logs});return{blockNumber:v.blockNumber,sender:o.address,senderTags:b?[Ao({fallbackNonce:b.args.fallbackNonce,sender:b.args.sender,transactionHash:v.transactionHash})]:void 0,transactionHash:v.transactionHash}}function is(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 h(e,t)}}function as(e,t,n,r){let{amount:i,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)&&Ua(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&&BigInt(i)>t.maxAtomicAmount)throw Error(`Tempo charge amount exceeds maxAtomicAmount.`);if(t.maxAmount!==void 0&&BigInt(i)>is(t.maxAmount,c?.decimals))throw Error(`Tempo charge amount exceeds maxAmount.`)}const os=(1n<<96n)-1n;function ss(e){return e>=0n&&e<=os}function cs(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return ss(t)?t:void 0}function ls(e){return us(e),e}function us(e){if(!ss(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const ds=new Set([`open`,`topUp`,`voucher`,`close`]);function fs(e){return typeof e==`object`&&!!e}function ps(e){return typeof e==`string`&&ds.has(e)}function ms(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!ps(t.action))}function hs(e,t=`No session credential context available.`){if(!ms(e))throw Error(t);return e}function gs(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function _s(e){return fs(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function vs(e){return fs(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 ys(e){let t=D.toString(e),n=JSON.parse(t);if(!vs(n))throw Error(`Invalid session receipt.`);return n}function bs(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function xs(e){let t=`message`,n=[];for(let r of e.split(`
6
+ `,i))}t=t.slice(i)}}}const li=[V.authorization,Qt,`PAYMENT-RESPONSE`,$t];function ui(e,t,n){let r=new Headers(e.headers);for(let e of li)e===V.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 fi(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 pi=1048576,mi=new WeakMap;function hi(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 gi(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 _i(e){if(!e||typeof e!=`object`)return;let t=e?.challenges;if(!Array.isArray(t)||t.length===0)return;let n=[];for(let e of t){let t=dt.safeParse(e);if(!t.success)return;n.push(t.data)}let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function vi(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:_i(e.error.data):_i(e.result?._meta?.[`org.paymentauth/payment-required`])}function yi(e,t){return!e||e.id!==t?[]:vi(e)?.challenges??[]}async function bi(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=ci(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=gi(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>pi)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function xi(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 gi(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>pi)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function Si(e){let t=mi.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>pi)){if(t.includes(`application/json`))return xi(e);if(t.includes(`text/event-stream`))return bi(e)}})();return mi.set(e,n),n}function Ci(){return{getChallenges(e,t){let n=hi(t);return e.status===402||n===void 0?[]:Si(e).then(e=>yi(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=Mt(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}function wi(){return{getChallenges(e){let t=e.headers.get(V.wwwAuthenticate);return e.status!==402||!t||!bt(t)?[]:St(e)},setCredential(e,t,n){return ui(e,n?.challenge?Et(n.challenge):V.authorization,t)}}}function Ti(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(Qt);if(!t)return[];let n=bn(t);return n.accepts.flatMap((e,t)=>{let r=sn.safeParse(e);if(!r.success)return[];let i=r.data;return Fn(ft({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 ui(e,$t,t)}}}function Ei(e){return e}function Di(){let e=[wi(),Ti(),Ci()],t=new WeakMap,n=(e,n)=>{for(let r of n)t.set(r,e);return n},r=(t,r)=>{let i=(a,o)=>{for(let s=a;s<e.length;s++){let a=e[s],c=a.getChallenges(t,r);if(c instanceof Promise)return c.then(e=>i(s+1,[...o,...n(a,e)]));o.push(...n(a,c))}return o};return i(0,[])};return Ei({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 Oi=new WeakMap;function ki(e,t){return Oi.set(e,t),e}function Ai(e){return Oi.has(e)}function ji(e,t){return Promise.resolve(Oi.get(e)?.(t))}function Mi(e){return Oi.get(e)}const Ni=new WeakMap,Pi=new WeakMap,Fi=new WeakMap,Ii=new WeakMap;function Li(e,t){return Ni.set(e,t),e}function Ri(e){Ni.delete(e)}function zi(e,t,n){Ni.has(e)&&Pi.set(t,n)}function Bi(e){return Pi.get(e)}function Vi(e,t){return Promise.resolve(Ni.get(e)?.(t)??t.response)}function Hi(e,t){return Ii.set(e,t),e}function Ui(e,t){try{return Ii.get(e)?.(t)}catch{return}}function Wi(e,t){Fi.set(e,t)}function Gi(e){return Fi.get(e)??Pi.get(e)?.origin}function Ki(e,t,n){if(!qi(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&&Ji(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 qi(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Ji(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}const Yi=Symbol.for(`mppx.fetch.wrapper`),Xi=Symbol.for(`mppx.fetch.identity`),Zi=Symbol.for(`mppx.fetch.skipPayment`),Qi=65536,$i=new WeakMap;async function ea(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>Qi){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,Qi),{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 na(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=Di(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&Ta(e.fetch)),d=e.eventDispatcher??ia(),f=t??Gr(a),p=Ea(r),m=async(e,t,n)=>u?u.send(p,new Request(e,t),n):{response:await p(e,t),headers:[]},h=async(e,t,r)=>{let g=wa(e,t?.headers),_=g.has(V.acceptPayment),v=ja(g,f),y=Sa(e,t,g),b=xa(e,t,g,v.header,_,n),x=await m(Da(b.input),b.init),S=x.response,C=x.headers,w=Ca(b.init,await y);if(t?.[Zi]||fi(w)||!await c.isPaymentRequired(S,w))return S;let ee=t?.context,{context:T,orderChallenges:te,...ne}=w??{},re,E,D,O,k;try{for(let n=0;n<i;n++){E=await c.getChallenges(S,w);let i=(await Ma(Jr(E,a,v.entries,ee),te??s))[0];if(!i){if(await ta(O,{challenges:E,response:S,status:`rejected`}),n>0)return S;throw Error(`No method found for challenges: ${E.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let f=i.challenge;re=f,D=i.method,re.expires&&Kt(re.expires,re.id),await u?.challenge(S,{challenge:f},Ia(b.input).href);let g=await Ra(S,b.input,b.input,ne);Ki(f,()=>Ia(g),l);let _=O,y=pt(f),x=_?.method===i.method&&_?.key===y,T=!1;if(_){let e=await ta(_,{challenges:E,response:S,status:x?`pending`:`rejected`});T=x&&!e}O=T?_:void 0;let A=la(async n=>{if(n===void 0&&T&&_)return _.promise;T&&_&&(await ta(_,{status:`rejected`}),O=void 0),Oa(e,t)?.throwIfAborted();let r=n??ee;if(!Ai(i.method))return Aa(f,i.method,r);let a={origin:Ia(g).origin,prepare:()=>ji(i.method,{challenge:f,context:r,fetch:u?Br(p,u,{challenge:f}):p,input:g,signal:Oa(e,t)})},o=a.prepare().then(()=>Aa(f,i.method,r,a));return O={context:r,attempt:a,key:n===void 0?y:void 0,method:i.method,promise:o},o}),j=await d.emit(`challenge.received`,ua({challenge:f,challenges:E,createCredential:A,init:t,input:e,method:i.method,response:S}))??(o?await o(re,{createCredential:A}):void 0)??await A(),M=O;M&&await M.promise.catch(()=>void 0)!==j&&(await ta(M,{status:`rejected`}),O=void 0);let N=O?O.context:ee;ka(j),await d.emit(`credential.created`,da({challenge:f,credential:j,init:t,input:e,method:i.method,response:S}));let P=e=>new Ht({cause:e,challenge:f,credential:j,transactionHash:Ui(i.method,j)});try{({response:S}=await m(g,{...c.setCredential({...ne,headers:b.headers},j,{challenge:f}),redirect:`manual`},{challenge:f,headers:C}))}catch(e){throw k=P(e),e}let F=await c.isPaymentRequired(S,w);if(F||(await ta(M,{response:S,status:S.status>=300&&S.status<400?`pending`:S.ok?`accepted`:`rejected`}),O=void 0),S.ok&&aa(d,`payment.response`)&&await d.emit(`payment.response`,fa({challenge:f,credential:j,init:t,input:e,method:i.method,response:S})),!F){if(S.status>=500&&aa(d,`payment.failed`)){try{S=await ea(S)}catch(e){throw k=P(e),S=new Response(null,{headers:S.headers,status:S.status,statusText:S.statusText}),e}await d.emit(`payment.failed`,pa({challenge:f,challenges:E,error:P(),init:t,input:e,method:i.method,response:S}))}return S.ok?Vi(i.method,{context:N,challenge:f,credential:j,fetch:p,headers:b.headers,input:g,...r?{refetch:()=>h(Da(b.input),t,!1)}:{},response:S,signal:Oa(e,t)}):S}}E=void 0;try{E=await c.getChallenges(S,w)}catch{}return await ta(O,{challenges:E,response:S,status:`rejected`}),S}catch(n){throw await ta(O,{challenges:E,response:S,status:`rejected`}),await d.emit(`payment.failed`,pa({challenge:re,challenges:E,error:k??n,init:t,input:e,method:D,response:S})),n}},g=(e,t)=>h(e,t,!0);return g[Yi]=p,u&&(g[Xi]=u),g}function ra(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 ia(){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 oa(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await ca(e[`*`],t,n),r}case`credential.created`:await sa(e[`credential.created`],n),await ca(e[`*`],t,n);return;case`payment.failed`:await sa(e[`payment.failed`],n),await ca(e[`*`],t,n);return;case`payment.response`:await sa(e[`payment.response`],n),await ca(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 $i.set(t,t=>e[t].size>0||e[`*`].size>0),t}function aa(e,t){return $i.get(e)?.(t)??!0}async function oa(e,t){try{return await e(t)}catch{return}}async function sa(e,t){for(let n of e)try{await n(t)}catch{}}async function ca(e,t,n){await sa(e,Object.freeze({name:t,payload:n}))}function la(e){let t;return n=>(t??=e(n),t)}function ua(e){return Object.freeze({challenge:va(e.challenge),challenges:e.challenges.map(e=>va(e)),createCredential:e.createCredential,init:ma(e.init),input:ha(e.input),method:ga(e.method),response:_a(e.response)})}function da(e){return Object.freeze({challenge:va(e.challenge),credential:e.credential,init:ma(e.init),input:ha(e.input),method:ga(e.method),...e.response===void 0?{}:{response:_a(e.response)}})}function fa(e){return Object.freeze({challenge:va(e.challenge),credential:e.credential,init:ma(e.init),input:ha(e.input),method:ga(e.method),response:_a(e.response)})}function pa(e){return Object.freeze({...e.challenge?{challenge:va(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>va(e))}:{},error:e.error,init:ma(e.init),input:ha(e.input),...e.method?{method:ga(e.method)}:{},...e.response===void 0?{}:{response:_a(e.response)}})}function ma(e){if(e)return ba({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function ha(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function ga(e){return ba(Object.assign({},e))}function _a(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 va(e)}function va(e){try{return ya(structuredClone(e))}catch{return ba(e)}}function ya(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))ya(t);return e}function ba(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function xa(e,t,n,r,i,a){let o=!!r&&!i&&Na(e,a);if(!o)return{headers:n,init:t,input:e};let s=new Headers(e instanceof Request?e.headers:void 0);return n.forEach((e,t)=>{s.set(t,e)}),s.set(V.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function Sa(e,t,n){if(!(!(e instanceof Request)||t?.body!==void 0||!e.body||e.bodyUsed)){if(!n.has(`mcp-method`)){let e=n.get(`accept`)?.toLowerCase()??``;if(!e.includes(`application/json`)||!e.includes(`text/event-stream`))return}try{return e.clone().text().catch(()=>void 0)}catch{return}}}function Ca(e,t){return t===void 0?e:{...e,body:t}}function wa(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function Ta(e){return e[Xi]}function Ea(e){let t=e;for(;t[Yi];)t=t[Yi];return t}function Da(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function Oa(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function ka(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 Aa(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&&Wi(a,r.origin),r&&zi(t,a,r),t.createCredential(a)}function ja(e,t){let n=e.get(V.acceptPayment);if(!n)return t;try{return{...t,entries:Kr(n),header:n}}catch{return t}}async function Ma(e,t){return t?t(e):e}function Na(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=Ia(e);return t===`same-origin`?!Fa()||n.origin===globalThis.location.origin:t.origins.some(e=>Pa(n,e))}function Pa(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 Fa(){return globalThis.location!==void 0}function Ia(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,Fa()?globalThis.location.href:void 0)}function La(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 Ra(e,t,n,r){if(La(t,r),!e.url)return t;let i=new URL(e.url),a=Ia(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 za(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 me(r)}}function Ba(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}const Va={[R.id]:R,[ie.id]:ie};function Ha(e,t={}){return u(e.url,{fetchFn:e.fetch,fetchOptions:{headers:Ba(e)},...t})}function Ua(r){let{chain:i,getClient:a,remoteFeePayer:o,rpcUrl:s}=r;return a?!i?.serializers&&!o?a:async e=>{let r=await a(e),s=r;if(o&&r.transport.key!==`feePayer`){let e=r.request.bind(r),i=pe(n({request:t=>e(t)},{retryCount:0}),Ha(o,{retryCount:r.transport.retryCount}))({account:r.account,chain:r.chain,pollingInterval:r.pollingInterval,retryCount:0}),a=t({...i.config,retryCount:0},i.value);s=Object.assign({},r,{request:a.request,transport:{...a.config,...a.value}})}return!i?.serializers||s.chain?.serializers?.transaction?s:Object.assign({},s,{chain:{...i,...e.chainId===void 0?{}:{id:e.chainId},...s.chain,formatters:s.chain?.formatters??i.formatters,prepareTransactionRequest:s.chain?.prepareTransactionRequest??i.prepareTransactionRequest,serializers:s.chain?.serializers?.transaction?s.chain.serializers:i.serializers}})}:({chainId:t})=>{if(!s)throw Error("No `rpcUrl` provided.");let n=t||Number(Object.keys(s)[0]),r=s[n];if(!r)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let a=o?pe(u(r),Ha(o)):u(r);return e({chain:Va[n]??{...i,id:n},transport:a})}}function Wa(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 Ga(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}const Ka=A.slice(k.keccak256(O.fromString(`mpp`),{as:`Hex`}),0,4);function qa(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,10))}function Ja(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(A.toBytes(Ka),0),i[4]=1,i.set(qa(t),5),n&&i.set(qa(n),15),i.set(Ya(r),25),A.fromBytes(i)}function Ya(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,7))}function Xa(e,t){return ve.resolve(e).toLowerCase()===ve.resolve(t).toLowerCase()}const Za=10000n,Qa=[rr.pathUsd,rr.usdc,rr.ousd];async function $a(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||Xa(t,i)||c.some(e=>Xa(e,t))||c.push(t)}let l=await Promise.allSettled([x(e,{...z.token.getBalance.call(e,{account:n,token:i}),account:null}),...c.map(t=>x(e,{...z.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/Za;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 z.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:f});if(t<=0n||t>m)continue;let n=t+t*p/Za,o=n<m?n:m;if(r>=o)return[z.token.approve.call(e,{amount:o,spender:ue.stablecoinDex,token:a}),z.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:f,maxAmountIn:o})]}catch{}}throw new to({currency:i})}function eo(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`&&Xa(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var to=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}};function no(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 ro(e,t,n){t&&(n&&!n.some(e=>Xa(e,t))||e.some(e=>Xa(e,t))||e.push(t))}async function io(e,t,n){try{return(await z.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function ao(e){let t=e.chain?.feeToken;if(t)return de.toAddress(t);let n=e.chain?.id;return n?ir[n]:void 0}function oo(e){let t=[];return ro(t,rr.pathUsd),ro(t,ir[e]),t}async function so(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])ro(o,e,n);if(ro(o,await z.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),ro(o,ao(i),n),!a)for(let e of r??[])ro(o,e,n);for(let e of o)if(await io(i,t,e))return e;return o[0]}const co=m([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]);function lo(e){if(e!==void 0)return ar[e]}function uo(e){let t=lo(e.chainId);return!!t&&d(e.currency,{strict:!1})&&f(e.currency,t.token)}function fo(e){let t=lo(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:ce.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:i({abi:co,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=fo(t);if(n)try{return await x(e,z.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 mo=10n**BigInt(4);function ho(e={}){let{address:t,amount:n,chainId:r=X.mainnet}=e;if(r!==X.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+mo-1n)/mo,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 go(e,t){let n=lo(t.chainId);if(!n)return;let r=await x(e,z.token.getBalance.call(e,{account:t.account,token:n.token})).catch(()=>void 0);return typeof r==`bigint`?r:void 0}async function _o(e,t){let{account:n,amount:r,chainId:i}=t,a=await go(e,{account:n,chainId:i});if(a===void 0||a>=r)return;let s=e=>`${o(e,6)} MACH`,c=r-a;return{fundingUrl:ho({address:n,amount:c,chainId:i}),reason:`requested ${s(r)}, available ${s(a)}`,shortfall:c}}async function vo(e,t){let n=await _o(e,t);if(n)return new Gt({fundingUrl:n.fundingUrl,reason:n.reason})}const yo={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]};function bo(e){return{name:`MPP`,version:`3`,chainId:e}}function xo(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function So(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:bo(n),types:yo,primaryType:`Proof`,message:xo({account:t,challengeId:r,realm:i})}}function Co(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const wo=[...ce.accountKeychain.filter(e=>e.type===`error`),...ce.tip20.filter(e=>e.type===`error`)];function To(e){let t=new Set,n=e;for(;typeof n==`object`&&n&&!t.has(n);){t.add(n);let e=n.data;if(Oo(e))return e;let r=e?.data;if(Oo(r))return r;n=n.cause}}function Eo(e,t){let n=To(e);if(!n)return;let i=(()=>{try{return r({abi:wo,data:n})}catch{return}})();if(i?.errorName===`SpendingLimitExceeded`){let n=t.account.accessKeyAddress;return new Ut({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 Gt({cause:e,reason:`${t.account.address} holds ${n} of token ${a}, but the payment requires ${r}`})}}async function Do(e,t){try{return await t()}catch(t){throw Eo(t,e)??t}}function Oo(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{8}/.test(e)}const ko=7200n,Ao=64n,jo=s({abi:ce.zonePortal,name:`WithdrawalProcessed`});function Mo(e){return Number.isInteger(e)&&e>0&&e<4217e5}function No(e,t){return Mo(t)?e===!0||(e?.includes(t)??!1):!1}function Po(e){return ue.zonePortal(e)}function Fo(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 Io(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 Lo(e){return k.keccak256(E.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function Ro(e,t){let{blockNumber:n,sender:r,transactionHash:i}=t,a=t=>x(e,{abi:ce.zoneOutbox,address:ue.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>Ao)throw Error(`Zone withdrawal transaction ${i} has ${s-o} candidate sender tags, more than ${Ao}.`);let c=[];for(let e=o+1n;e<=s;e++)c.push(Lo({fallbackNonce:e,sender:r,transactionHash:i}));return c}async function zo(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>ko?i-ko:0n,o=Date.now()+r;for(;;){if(a<=i){let[r]=await y(e,{address:t.portal,event:jo,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 Bo=[`push`,`pull`],Vo=U.object({amount:W(),memo:U.optional(K()),recipient:U.pipe(U.string(),U.transform(e=>e))}),Ho=(1n<<64n)-1n,Uo={dev_second:1n,day:86400n,week:604800n},Wo=U.pipe(G(),U.transform(e=>e.toLowerCase())),Go=U.object({accessKeyAddress:Wo,keyType:U.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:U.optional(U.pipe(U.string().check(U.regex(/^0x[0-9a-fA-F]{120}$/)),U.transform(e=>e)))}),Ko=U.object({accessKey:U.optional(Go),chainId:U.optional(U.number())}),qo=ot(`subscriptionExpires must be a valid date`).check(U.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),Jo=U.enum([`dev_second`,`day`,`week`]),Yo=U.pipe(U.union([U.string(),U.bigint(),U.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),U.transform(e=>e.toString())).check(U.regex(/^[1-9]\d*$/,`Invalid periodCount`),U.refine(e=>{try{return BigInt(e)<=Ho}catch{return!1}},`periodCount exceeds uint64`));function Xo(e){return U.refine(e=>{let{amount:t,decimals:n}=e;return g(t,n)>0n},e)}function Zo(e){let{periodCount:t,periodUnit:n}=e;try{let e=Uo[n];return e!==void 0&&BigInt(t)*e<=Ho}catch{return!1}}const Qo=qt({name:`tempo`,intent:`charge`,schema:{credential:{payload:U.discriminatedUnion(`type`,[U.object({hash:K(),type:U.literal(`hash`)}),U.object({signature:q(),type:U.literal(`transaction`)}),U.object({signature:q(),type:U.literal(`proof`)}),U.object({hash:K(),senderTag:K(),type:U.literal(`zone`),zoneId:U.number().check(U.refine(Mo,`Invalid Zone ID`))})])},request:U.pipe(U.object({machineTokenEnabled:U.optional(U.boolean()),amount:W(),chainId:U.optional(U.number()),currency:U.string(),decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),feePayer:U.optional(U.pipe(U.union([U.boolean(),U.custom()]),U.transform(e=>typeof e==`object`||e))),memo:U.optional(U.never()),recipient:U.optional(U.string()),splits:U.optional(U.array(Vo).check(U.minLength(1),U.maxLength(10))),supportedModes:U.optional(U.array(U.enum(Bo)).check(U.minLength(1))),zones:U.optional(U.union([U.literal(!0),U.array(U.number().check(U.refine(Mo,`Invalid Zone ID`))).check(U.minLength(1))]))}).check(U.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`)),U.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}}}:{}})))}}),$o=qt({name:`tempo`,intent:`session`,schema:{credential:{payload:U.discriminatedUnion(`action`,[U.object({action:U.literal(`open`),authorizedSigner:U.optional(U.string()),channelId:K(),cumulativeAmount:W(),descriptor:U.optional(U.custom()),signature:q(),transaction:q(),type:U.literal(`transaction`)}),U.object({action:U.literal(`topUp`),additionalDeposit:W(),channelId:K(),descriptor:U.optional(U.custom()),transaction:q(),type:U.literal(`transaction`)}),U.object({action:U.literal(`voucher`),channelId:K(),cumulativeAmount:W(),descriptor:U.optional(U.custom()),signature:q()}),U.object({action:U.literal(`close`),channelId:K(),closeSignature:q(),cumulativeAmount:W(),descriptor:U.optional(U.custom()),signature:q()})])},request:U.pipe(U.object({amount:W(),chainId:U.optional(U.number()),channelId:U.optional(K()),currency:U.string(),decimals:U.number(),escrowContract:U.optional(U.string()),feePayer:U.optional(U.pipe(U.union([U.boolean(),U.custom()]),U.transform(e=>typeof e==`object`||e))),feeToken:U.optional(G()),minVoucherDelta:U.optional(W()),operator:U.optional(G()),recipient:U.optional(U.string()),sessionProtocol:U.optional(U.enum([tt.v2,tt.v1])),sessionSnapshot:U.optional(U.custom()),suggestedDeposit:U.optional(W()),unitType:U.string()}).check(U.refine(({amount:e,decimals:t})=>g(e,t)>0n,`Session amount must be greater than 0`)),U.transform(({amount:e,chainId:t,channelId:n,decimals:r,escrowContract:i,feePayer:a,feeToken:o,minVoucherDelta:s,operator:c,sessionProtocol:l,sessionSnapshot:u,suggestedDeposit:d,...f})=>({...f,amount:g(e,r).toString(),...d?{suggestedDeposit:g(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:g(s,r).toString()},...t!==void 0&&{chainId:t},...a!==void 0&&{feePayer:a},...o!==void 0&&{feeToken:o},...c!==void 0&&{operator:c},...l!==void 0&&{[et.sessionProtocol]:l},...u!==void 0&&{[et.sessionSnapshot]:u}}})))}}),es=qt({name:`tempo`,intent:`subscription`,schema:{credential:{payload:U.object({signature:q(),type:U.literal(`keyAuthorization`)})},request:U.pipe(U.object({amount:W(),accessKey:U.optional(Go),chainId:U.optional(U.number()),currency:Wo,decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),methodDetails:U.optional(Ko),periodCount:Yo,periodUnit:Jo,recipient:Wo,subscriptionExpires:qo}).check(Xo(`Subscription amount must be greater than 0`),U.refine(Zo,`Subscription period exceeds uint64`)),U.transform(({accessKey:e,amount:t,chainId:n,decimals:r,methodDetails:i,subscriptionExpires:a,...o})=>{let s={...i,...e!==void 0&&{accessKey:e},...n!==void 0&&{chainId:n}};return{...o,amount:g(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}}),ts=U.object({account:U.optional(U.custom()),autoSwap:U.optional(U.custom()),feeToken:U.optional(U.custom()),mode:U.optional(U.enum(Bo))});function ns(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??[])ds(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=Ua({chain:R,getClient:e.getClient,rpcUrl:or}),i=za({account:e.account});os(e.zone);let a=new Map,o=Jt(Qo,{canHandleChallenge({challenge:t}){try{return fs(e,n,t.request),!0}catch{return!1}},context:ts,async createCredential({challenge:o,context:s}){fs(e,n,o.request);let c=o.request.methodDetails?.chainId,l=c??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),u=await r({chainId:l});Wa(u,l);let d=l??u.chain?.id;if(Ga(e.allowedChainIds,d),d===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");c===void 0&&fs(e,n,o.request,d);let{request:f}=o,{amount:p,methodDetails:m}=f,h=m?.supportedModes??[`pull`,`push`],g=e.zone?.client.chain,_=e.zone?e.zone.zoneId??Fo(g?.id??0):void 0,v=g?.sourceId??(g?Io(g.id):void 0),y=s?.mode??e.mode;if(BigInt(p)>0n&&e.zone&&_!==void 0&&v===d&&h.includes(`push`)&&(y===void 0||y===`push`)&&No(m?.zones,_)&&!m?.splits&&(a.has(ls(o))||ss(o.expires,e.zone.settlementTimeoutMs)))return as({challenge:o,clientId:t,client:u,pending:a,zone:e.zone,zoneId:_});let x=i(u,s),C=async t=>await e.resolveAccount?.({account:x,chainId:d,operation:t})??x;if(BigInt(p)===0n){let e=await C({kind:`signPaymentProof`});return It({challenge:o,payload:{signature:await T(u,{account:e,...So({account:e.address,chainId:d,challengeId:o.id,realm:o.realm})}),type:`proof`},source:Co({address:e.address,chainId:d})})}let te=f.currency,ne=uo({chainId:d,currency:te}),re=Ja({challengeId:o.id,clientId:t,serverId:o.realm}),E=no({amount:p,methodDetails:{...m,memo:re},recipient:f.recipient}),D=E.map(e=>z.token.transfer.call(u,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:te})),O=eo(s?.autoSwap??e.autoSwap,Qa),k=m?.machineTokenEnabled===!0?fo({chainId:d,currency:te,transfers:E}):void 0,A=x,j,M=!1;if(k){let e=await(async()=>{try{return await C({calls:k.calls,kind:`executeCalls`})}catch{return}})();e&&(j=await po(u,{account:e.address,chainId:d,currency:te,transfers:E}),j?A=e:M=!0)}let N;if(!j&&(A=await C({kind:`executeCalls`,...O?{}:{calls:D}}),N=O?await $a(u,{account:A.address,amountOut:BigInt(p),tokenOut:te,tokenIn:O.tokenIn,slippage:O.slippage,maxAmountIn:O.maxAmountIn}):void 0,M&&!O)){let e=await rs(u,{account:A.address,amount:BigInt(p),chainId:d,currency:te});if(e)throw e}let P=j?.calls??[...N??[],...D],F=oo(d),I=(s?.feeToken??e.feeToken)||(j||ne?await so({account:A.address,allowedTokens:F,candidateTokens:F,client:u,prioritizeCandidates:!0}):void 0),L=(()=>{let t=s?.mode??e.mode;if(t){if(!h.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=A.type===`json-rpc`?`push`:`pull`;return h.includes(n)?n:h[0]})(),R=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!o.expires)return e;let t=Math.floor(new Date(o.expires).getTime()/1e3)+1;return Math.min(e,t)})();if(L===`push`){let{receipts:e}=A.type===`local`?{receipts:[await Do({account:A},()=>w(u,{account:A,calls:P,...I?{feeToken:I}:{},nonceKey:`expiring`,validBefore:R}))]}:await S(u,{account:A,...I?{capabilities:{feeToken:I}}:{},calls:P,experimental_fallback:P.length===1,forceAtomic:P.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return It({challenge:o,payload:{hash:t,type:`hash`},source:Co({address:A.address,chainId:d})})}let ie=()=>{if(m?.feePayer!==!0)return;let e=15e3,t=o.expires?new Date(o.expires).getTime():1/0,n=Date.now();if(!(t-n>=e))throw Error(`Sponsored challenge expires in less than 15 seconds; the fee payer would reject the transaction. Request a new challenge.`);if(!(R*1e3-n>=e))throw Error(`Sponsored transaction preparation took too long: less than 15 seconds of its validity window remain, so the fee payer would reject it.`)};ie();let ae=await Do({account:A},()=>b(u,{account:A,calls:P,...I?{feeToken:I}:{},nonceKey:`expiring`,validBefore:R}));if(ae.gas=(ae.gas??0n)+5000n,m?.feePayer){let e=ae;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return ie(),It({challenge:o,payload:{signature:await ee(u,ae),type:`transaction`},source:Co({address:A.address,chainId:d})})}}),s=new Map,c=async t=>{fs(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 Hi({...o,createCredential:c},is)}async function rs(e,t){let{account:n,amount:r,chainId:i,currency:a}=t,o=await x(e,z.token.getBalance.call(e,{account:n,token:a})).catch(()=>void 0);if(!(typeof o!=`bigint`||o>=r))return vo(e,{account:n,amount:r,chainId:i})}function is(e){let t=Qo.schema.credential.payload.safeParse(Mt(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)}async function as(e){let{challenge:t,client:n,pending:r,zone:i,zoneId:a}=e,o=t.request.recipient,s=ls(t),c=r.get(s);if(!c){let t={sent:!1};c=us(e,t),r.set(s,c),c.catch(()=>{t.sent||r.delete(s)})}let l=await c,u=l.senderTags??await Ro(i.client,l).catch(e=>{let t=Error(`Zone withdrawal transaction ${l.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}),d;try{d=await zo(n,{portal:Po(a),senderTags:u,timeoutMs:cs(t.expires,i.settlementTimeoutMs),to:o})}catch(e){throw new Wt({cause:e,challengeId:t.id,senderTags:u,zoneId:a})}r.delete(s);let{hash:f,senderTag:p}=d;return It({challenge:t,payload:{hash:f,senderTag:p,type:`zone`,zoneId:a}})}function os(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||Io(n)===void 0)return;let r=Fo(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function ss(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+15e3}function cs(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function ls(e){return JSON.stringify(e)}async function us(e,t){let{challenge:n,clientId:r,zone:i}=e,a=n.request,o=i.client.account;if(!o)throw Error("`zone.client` requires an account.");let s=BigInt(a.amount),c=a.currency,l=a.recipient,u=Ja({challengeId:n.id,clientId:r,serverId:n.realm}),d=await z.zone.getWithdrawalFee(i.client),[,f]=z.zone.requestWithdrawal.calls({amount:s,fallbackRecipient:o.address,memo:u,to:l,token:c}),m=await b(i.client,{account:o,calls:[z.token.approve.call({amount:s+d,spender:ue.zoneOutbox,token:c}),f]}),g=await ee(i.client,m);t.sent=!0;let _=p(g),v=await C(i.client,{serializedTransaction:g}).catch(e=>te(i.client,{hash:_,timeout:15e3}).catch(()=>{let t=Error(`Zone withdrawal outcome is unknown: transaction ${_} may have been sent. Retrying this challenge does not withdraw again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),t}));if(v.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${v.transactionHash} reverted.`);let[y]=h({abi:ce.zoneOutbox,eventName:`WithdrawalRequested`,logs:v.logs});return{blockNumber:v.blockNumber,sender:o.address,senderTags:y?[Lo({fallbackNonce:y.args.fallbackNonce,sender:y.args.sender,transactionHash:v.transactionHash})]:void 0,transactionHash:v.transactionHash}}function ds(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 fs(e,t,n,r){let{amount:i,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)&&Ga(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&&BigInt(i)>t.maxAtomicAmount)throw Error(`Tempo charge amount exceeds maxAtomicAmount.`);if(t.maxAmount!==void 0&&BigInt(i)>ds(t.maxAmount,c?.decimals))throw Error(`Tempo charge amount exceeds maxAmount.`)}const ps=(1n<<96n)-1n;function ms(e){return e>=0n&&e<=ps}function hs(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return ms(t)?t:void 0}function gs(e){return _s(e),e}function _s(e){if(!ms(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const vs=new Set([`open`,`topUp`,`voucher`,`close`]);function ys(e){return typeof e==`object`&&!!e}function bs(e){return typeof e==`string`&&vs.has(e)}function xs(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!bs(t.action))}function Ss(e,t=`No session credential context available.`){if(!xs(e))throw Error(t);return e}function Cs(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function ws(e){return ys(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function Ts(e){return ys(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 Es(e){let t=D.toString(e),n=JSON.parse(t);if(!Ts(n))throw Error(`Invalid session receipt.`);return n}function Ds(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function Os(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=Ss(r);return _s(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=Ss(r);return vs(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function Ss(e){try{return JSON.parse(e)}catch{return null}}function Cs(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function ws(){return JSON.stringify({mpp:`payment-close-request`})}function Ts(e){let t=Es(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`&&vs(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`&&_s(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&vs(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function Es(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}const Ds=`0x4d50500000000000000000000000000000000000`;function Os(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function ks(e){let t=E.encode(E.from([`address payer`,`address payee`,`address operator`,`address token`,`bytes32 salt`,`address authorizedSigner`,`bytes32 expiringNonceHash`,`address escrow`,`uint256 chainId`]),[e.payer,e.payee,e.operator,e.token,e.salt,e.authorizedSigner,e.expiringNonceHash,e.escrow??`0x4d50500000000000000000000000000000000000`,BigInt(e.chainId)]);return k.keccak256(t)}function As(e){return ve.encodeForSigning(e)}function js(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function Ms(e,t){return k.keccak256(A.concat(As(e),t.sender))}const Ns=[{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`}],Ps=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],Fs={name:`descriptor`,type:`tuple`,components:Ns},Is=[{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:[Fs,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[Fs,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[Fs,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[Fs],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[Fs],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[Fs],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:Ns},{name:`state`,type:`tuple`,components:Ps}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:Ps}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:Ps}]},{type:`function`,name:`computeChannelId`,stateMutability:`view`,inputs:[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`getVoucherDigest`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`domainSeparator`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`event`,name:`ChannelOpened`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`authorizedSigner`,type:`address`},{name:`salt`,type:`bytes32`},{name:`expiringNonceHash`,type:`bytes32`},{name:`deposit`,type:`uint96`}]},{type:`event`,name:`Settled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`cumulativeAmount`,type:`uint96`},{name:`deltaPaid`,type:`uint96`},{name:`newSettled`,type:`uint96`}]},{type:`event`,name:`TopUp`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`additionalDeposit`,type:`uint96`},{name:`newDeposit`,type:`uint96`}]},{type:`event`,name:`CloseRequested`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`closeGraceEnd`,type:`uint256`}]},{type:`event`,name:`ChannelClosed`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`settledToPayee`,type:`uint96`},{name:`refundedToPayer`,type:`uint96`}]},{type:`event`,name:`CloseRequestCancelled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0}]}];function Ls(e,t){return{name:`TIP20 Channel Reserve`,version:`1`,chainId:t,verifyingContract:e}}const Rs={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},zs={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]};function Bs(e,t,n){return c({domain:Ls(e,t),types:zs,primaryType:`CloseAuthorization`,message:n})}function Vs(e,t){return he.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function Hs(e,t,n){return e.toLowerCase()===he.address.toLowerCase()?Vs(t,n):c({domain:Ls(e,t),types:Rs,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function Us(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function Ws(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function Gs(e,t){return ce.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function Ks(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===he.address.toLowerCase())try{return await Gs(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return ee(e,{account:t,domain:Ls(r,i),types:Rs,primaryType:`Voucher`,message:n})})(),o=B.from(a);if(!Us(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return B.serialize(o)}async function qs(e,t,n,r,i){let a=Ws(t)?await t.sign({hash:Bs(r,i,n),raw:!0}):await ee(e,{account:t,domain:Ls(r,i),types:zs,primaryType:`CloseAuthorization`,message:n}),o=B.from(a);if(!Us(o.type))throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive signature; received "${o.type}".`);return B.serialize(o)}function Js(e,t,n,r){try{let i=B.from(n.signature);if(!Us(i.type)||B.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=Hs(e,t,n),o=B.extractAddress({payload:a,signature:i});return B.verify(i,{address:o,payload:a})&&Ja(o,r)}catch{return!1}}function Ys(e){return typeof e==`object`&&!!e}function Xs(e){return typeof e==`string`&&u(e,{strict:!1})?e:void 0}function Zs(e){return Xs(e.accessKeyAddress)}function Qs(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(A.random(8))%e)}function $s(e){return Zs(e)??e.address}async function ec(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return y(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}})}async function tc(e,t){return await w(e,t)}function nc(e,t,n=!1){let r=e.request.methodDetails,i=Ys(r)?Xs(r.escrowContract)??Xs(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!ic(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!ic(i,a)?i:a}function rc(e,t,n,r){return Ft({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function ic(e,t){return e.toLowerCase()===t.toLowerCase()}async function ac(e,t,n,r,i,a=Ds){let o=ks({...n,chainId:i,escrow:a}),s=ls(r),c=await Ks(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function oc(e,t,n,r,i,a=Ds){let o=await ac(e,t,n,r,i,a),s=await qs(e,t,{channelId:o.channelId,cumulativeAmount:ls(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function sc(e,t,n){let i=$s(t),a=n.escrow??`0x4d50500000000000000000000000000000000000`,o=n.operator??`0x0000000000000000000000000000000000000000`,s=A.random(32),c=ls(n.deposit),l=ls(n.initialAmount),u=r({abi:Is,functionName:`open`,args:[n.payee,o,n.token,c,s,i]}),d=await tc(e,await ec(e,{account:t,calls:[...n.prefixCalls??[],{to:a,data:u}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),f=de.deserialize(d),p={authorizedSigner:i,expiringNonceHash:Ms(js({...n.feePayer?{feePayer:!0}:{},transaction:f}),{sender:t.address}),operator:o,payee:n.payee,payer:t.address,salt:s,token:n.token},m=ks({...p,chainId:n.chainId,escrow:a});return{action:`open`,type:`transaction`,channelId:m,transaction:d,signature:await Ks(e,t,{channelId:m,cumulativeAmount:l},a,n.chainId),descriptor:p,cumulativeAmount:l.toString(),authorizedSigner:p.authorizedSigner}}async function cc(e,t,n,i,a,o,s=Ds,c=[],l=n.token){let u=ks({...n,chainId:a,escrow:s}),d=ls(i);return{action:`topUp`,type:`transaction`,channelId:u,transaction:await tc(e,await ec(e,{account:t,calls:[...c,{to:s,data:r({abi:Is,functionName:`topUp`,args:[n,d]})}],feePayer:o,feeToken:l,validAfter:Qs()})),descriptor:n,additionalDeposit:d.toString()}}function lc(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Q(e){return lc({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function uc(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Q(t),t)},delete(t){e.delete(t)}}}const dc=new WeakMap,fc=new WeakMap;function pc(e,t){fc.set(e,fc.get(t)??t)}async function mc(e,t,n){let r=dc.get(e);r||(r=new Map,dc.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 hc(e,t,n){return mc(fc.get(e)??e,`funding:${t}`,n)}async function gc(e,t){await mc(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 _c(e,t){await mc(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}const vc=2n**96n-1n;function yc(e){if(e<0n||e>vc)throw new Y({reason:`amount exceeds uint96 range`})}async function bc(e,t,n=Ds,r){return xc(await b(e,{address:n,abi:Is,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function xc(e){return yc(e.settled),yc(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}const Sc=U.custom(e=>typeof e==`string`&&u(e,{strict:!1})),Cc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),wc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),Tc=U.object({authorizedSigner:Sc,expiringNonceHash:Cc,operator:Sc,payee:Sc,payer:Sc,salt:Cc,token:Sc}),Ec=qt(U.object({acceptedCumulative:U.string(),chainId:U.number(),channelId:Cc,closeRequestedAt:U.optional(U.string()),deposit:U.string(),descriptor:Tc,escrow:Sc,highestVoucher:U.optional(U.object({channelId:Cc,cumulativeAmount:U.string(),signature:wc})),requiredCumulative:U.string(),settled:U.string(),spent:U.string(),units:U.optional(U.number())}));function Dc(e){return Ec.encode(e)}function Oc(e){return Ec.decode(e)}const kc={status:`idle`};function Ac(e){return{status:`active`,...e}}function jc(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:Pc(e.challengeId,t.snapshot),effects:[]}:$(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:qc({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:Fc(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:$(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Xc(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?Nc({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:Fc(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:Fc(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 Mc(e,t){let n=jc(e.state,t);return e.state=n.state,n}function Nc(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 Pc(e,t){return Ac({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function Fc(e,t,n,r){return Ac({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 Ic(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function Lc(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`);Ic({cumulativeAmount:i,maxVoucherCumulative:n}),Ic({cumulativeAmount:a,maxVoucherCumulative:n})}function Rc(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;Lc({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function zc(e,t){return typeof e==`bigint`?e:h(e,t)}function Bc(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(Hc(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 Vc(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;Ic({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 Hc(e,t){Ic({cumulativeAmount:e,maxVoucherCumulative:t??null})}function Uc(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 Wc(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function Gc(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!ss(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>Wc({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function Kc(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=cs(r),s=cs(a.spent);return o===void 0||s===void 0||!ss(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function qc(e){return Ac({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 Jc(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:kc}}function Yc(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=Rc({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&Mc(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function Xc(e,t){return Ac({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function Zc(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=cs(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 Qc(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 jc(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function $c(e){return{channel:e.channel===null?null:{entry:e.channel,cumulativeAmount:e.channel.cumulativeAmount,deposit:e.channel.deposit,opened:e.channel.opened},spent:e.spent,state:e.state}}function el(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 tl(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(ws()),e.waitForCloseReady()))(),a=BigInt(i.spent);Gc({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=>Kc({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(Cs(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}function nl(e){return`cumulativeAmount`in e}function rl(e){if(nl(e))return BigInt(e.cumulativeAmount)}async function il(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await gc(e.store,t):await _c(e.store,Q(t)),e.notifyUpdate(t)}async function al(e,t,n){let r=rl(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 il(e,i))}const ol=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),sl=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),cl=U.object({account:U.optional(U.custom()),autoSwap:U.optional(U.custom()),action:U.optional(U.enum([`open`,`topUp`,`voucher`,`close`])),channelId:U.optional(sl),cumulativeAmount:U.optional(W()),cumulativeAmountRaw:U.optional(U.string()),transaction:U.optional(ol),descriptor:U.optional(U.custom()),additionalDeposit:U.optional(W()),additionalDepositRaw:U.optional(U.string()),depositRaw:U.optional(U.string())});function ll(e){return e?.action!==void 0}function ul(e){return ll(e)&&e.descriptor!==void 0}function dl(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 h(i,t)}function fl(e,t,n,r){let i=dl(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function pl(e){return typeof e==`object`&&!!e}function ml(e){return typeof e==`string`&&u(e,{strict:!1})?e:void 0}function hl(e){let t=e.request.methodDetails;return pl(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:ml(t.escrowContract),escrow:ml(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:ml(t.feeToken),operator:ml(t.operator),sessionSnapshot:tt(t,$e.sessionSnapshot)}:{}}function gl(e,t){if(typeof e==`string`&&u(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function _l(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function vl(e){return typeof e==`string`?e:void 0}async function yl(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=hl(n);(o.chainId!==void 0||i?.length===0)&&Ua(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});Ha(c,s);let l=s??c.chain?.id;if(Ua(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=nc(n,r,t),d=gl(n.request.recipient,`recipient`),f=gl(n.request.currency,`currency`);return{amount:_l(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:lc({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:vl(n.request.suggestedDeposit),token:f}}async function bl(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=bc}=e,o=ks({...r,chainId:i.chainId,escrow:i.escrow});xl({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 xl(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(!ic(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!ic(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!ic(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!ic(Os(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function Sl(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function Cl(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=dl(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function wl(e){let{account:t,client:n,readChannelState:r,snapshot:i}=e,a=i.highestVoucher;if(!a)throw Error(`session snapshot is missing its highest signed voucher`);if(a.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let o=BigInt(i.acceptedCumulative),s=BigInt(a.cumulativeAmount),c=BigInt(i.requiredCumulative),l=BigInt(i.deposit),u=BigInt(i.settled),d=BigInt(i.spent);if(s!==o)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(d>o)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(u>l)throw Error(`session snapshot settled amount exceeds deposit`);if(!Js(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},Os(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await bl({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:$s(t),token:i.descriptor.token},readChannelState:r}),p=[o,c,f.state.settled].reduce((e,t)=>t>e?t:e,0n);if(p>f.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:f.channelId,cumulativeAmount:p,deposit:f.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:d}}function Tl(e,t){return ic(e.address,t.payer)?ic($s(e),Os(t)):!1}function El(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(ll(r)){if(!ul(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=Sl({context:r,snapshot:o.snapshot});return!n&&s&&Tl(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&Tl(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 Dl(e,t,n=!1){switch(e.type){case`open`:return Al(e,t,n);case`recover`:return jl(e,t);case`voucher`:return Ml(e,t);case`manual`:return Nl(e,t,n)}}async function Ol(e,t){if(e)return await Za(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function kl(e,t){let{account:n,amount:r,chainId:i,client:a,token:o}=t;if(e||!co({chainId:i,currency:o}))return;let s=await go(a,{account:n,amount:r,chainId:i});if(s)throw s}async function Al(e,t,n){let{account:r,resolved:i}=e,a=Bc({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw});await kl(n,{account:r.address,amount:a,chainId:i.chainId,client:i.client,token:i.token});let o=await sc(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 Ol(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await il(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function jl(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await bl({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:$s(n),token:o.token}}),l=Cl({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`);Hc(l,a);let u=await ac(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await il(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 Ml(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;Hc(a,e.maxDeposit);let o=await ac(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await il(t,r),o}async function Nl(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=ks({...s,chainId:o.chainId,escrow:o.escrow});xl({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:$s(r),token:o.token});let l=await Pl({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await al(t,o.key,l),l}async function Pl(e,t){switch(e.context.action){case`open`:return Fl(e);case`topUp`:return Il(e,t);case`voucher`:return Ll(e);case`close`:return Rl(e)}}async function Fl(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=fl(r,i,`cumulativeAmount`,`open`),c=await ac(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 Il(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=fl(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:(await kl(t,{account:n.address,amount:c,chainId:s.chainId,client:s.client,token:s.token}),cc(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await Ol(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken))}function Ll(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return ac(a.client,t,i,fl(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function Rl(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return oc(a.client,t,i,fl(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}const zl={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function Bl(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=zl.CLOSED,r=null}if(a.type===`open`&&(i=zl.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 Vl(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function Hl(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=zc(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 Ul(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:Xc(s,u)}:i?{channel:u,state:qc({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function Wl(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=Vl(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:ls(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function Gl(e){return e.method===Ze.tempo&&e.intent===Qe.session}function Kl(e){return Gl(e)&&tt(e.request.methodDetails,$e.sessionProtocol)===et.v2}function ql(e){return tt(e.request.methodDetails,$e.sessionSnapshot)}function Jl(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return ci({...t,redirect:`manual`,headers:{...ta(i),...ta(t?.headers)}},Tt(r),n)}function Yl(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 Xl(e){try{let t=typeof location>`u`?void 0:location.href,n=Yl(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function Zl(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function Ql(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 $l=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 eu(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 tu({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 $l&&(t.uncertainTopUp=!0,await e.onUncertainFunding?.(t)),n});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(V.paymentReceipt);return i?ys(i):void 0}async function tu(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(Xl(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:Tu(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new $l(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=xt(n).find(Kl);return r?t(r):n}async function nu(e){let t=ru({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,Jl(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(V.paymentReceipt)&&await l(),u}function ru(e){let t=xt(e.response).find(Kl);if(!t)return;let n=ql(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function iu(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=Yl(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?Xl(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:Tu(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=xt(o).find(Kl);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await Ql(o),t=o.headers.get(V.wwwAuthenticate)??``;throw Error(`Close request failed with status ${o.status}${e?`: ${e}`:``}${t?` [${V.wwwAuthenticate}: ${t}]`:``}`)}let s=o.headers.get(V.paymentReceipt);if(!s)return;let c=ys(s);if(!c.txHash||!A.validate(c.txHash,{strict:!0})||A.size(c.txHash)!==32||!Kc({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 au(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...ta(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!bs(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),ou(e,c,{onReceipt:r,signal:o},n,s.headers)}function ou(e,t,n,r,i){if(!bs(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return su({onNeedVoucher:t=>fu({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*su(e){for await(let t of cu(e))t.data!==void 0&&(yield t.data)}async function*cu(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=lu(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=xs(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 lu(e,t){for(let n=0;n<e.length;n++){let r=uu(e,n,t);if(!r)continue;let i=uu(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function uu(e,t,n){return e[t]===`
9
+ `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=ks(r);return ws(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=ks(r);return Ts(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function ks(e){try{return JSON.parse(e)}catch{return null}}function As(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function js(){return JSON.stringify({mpp:`payment-close-request`})}function Ms(e){let t=Ns(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`&&Ts(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`&&ws(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&Ts(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function Ns(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}const Ps=`0x4d50500000000000000000000000000000000000`;function Fs(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function Is(e){let t=E.encode(E.from([`address payer`,`address payee`,`address operator`,`address token`,`bytes32 salt`,`address authorizedSigner`,`bytes32 expiringNonceHash`,`address escrow`,`uint256 chainId`]),[e.payer,e.payee,e.operator,e.token,e.salt,e.authorizedSigner,e.expiringNonceHash,e.escrow??`0x4d50500000000000000000000000000000000000`,BigInt(e.chainId)]);return k.keccak256(t)}function Ls(e){return ye.encodeForSigning(e)}function Rs(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function zs(e,t){return k.keccak256(A.concat(Ls(e),t.sender))}const Bs=[{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`}],Vs=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],Hs={name:`descriptor`,type:`tuple`,components:Bs},Us=[{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:[Hs,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[Hs,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[Hs,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[Hs],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[Hs],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[Hs],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:Bs},{name:`state`,type:`tuple`,components:Vs}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:Vs}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:Vs}]},{type:`function`,name:`computeChannelId`,stateMutability:`view`,inputs:[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`getVoucherDigest`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`domainSeparator`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`event`,name:`ChannelOpened`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`authorizedSigner`,type:`address`},{name:`salt`,type:`bytes32`},{name:`expiringNonceHash`,type:`bytes32`},{name:`deposit`,type:`uint96`}]},{type:`event`,name:`Settled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`cumulativeAmount`,type:`uint96`},{name:`deltaPaid`,type:`uint96`},{name:`newSettled`,type:`uint96`}]},{type:`event`,name:`TopUp`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`additionalDeposit`,type:`uint96`},{name:`newDeposit`,type:`uint96`}]},{type:`event`,name:`CloseRequested`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`closeGraceEnd`,type:`uint256`}]},{type:`event`,name:`ChannelClosed`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`settledToPayee`,type:`uint96`},{name:`refundedToPayer`,type:`uint96`}]},{type:`event`,name:`CloseRequestCancelled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0}]}];function Ws(e,t){return{name:`TIP20 Channel Reserve`,version:`1`,chainId:t,verifyingContract:e}}const Gs={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},Ks={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]};function qs(e,t,n){return l({domain:Ws(e,t),types:Ks,primaryType:`CloseAuthorization`,message:n})}function Js(e,t){return ge.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function Ys(e,t,n){return e.toLowerCase()===ge.address.toLowerCase()?Js(t,n):l({domain:Ws(e,t),types:Gs,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function Xs(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function Zs(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function Qs(e,t){return le.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function $s(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===ge.address.toLowerCase())try{return await Qs(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return T(e,{account:t,domain:Ws(r,i),types:Gs,primaryType:`Voucher`,message:n})})(),o=B.from(a);if(!Xs(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return B.serialize(o)}async function ec(e,t,n,r,i){let a=Zs(t)?await t.sign({hash:qs(r,i,n),raw:!0}):await T(e,{account:t,domain:Ws(r,i),types:Ks,primaryType:`CloseAuthorization`,message:n}),o=B.from(a);if(!Xs(o.type))throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive signature; received "${o.type}".`);return B.serialize(o)}function tc(e,t,n,r){try{let i=B.from(n.signature);if(!Xs(i.type)||B.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=Ys(e,t,n),o=B.extractAddress({payload:a,signature:i});return B.verify(i,{address:o,payload:a})&&Xa(o,r)}catch{return!1}}function nc(e){return typeof e==`object`&&!!e}function rc(e){return typeof e==`string`&&d(e,{strict:!1})?e:void 0}function ic(e){return rc(e.accessKeyAddress)}function ac(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(A.random(8))%e)}function oc(e){return ic(e)??e.address}async function sc(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return Do({account:n},()=>b(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}}))}async function cc(e,t){return await ee(e,t)}function lc(e,t,n=!1){let r=e.request.methodDetails,i=nc(r)?rc(r.escrowContract)??rc(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!dc(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!dc(i,a)?i:a}function uc(e,t,n,r){return It({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function dc(e,t){return e.toLowerCase()===t.toLowerCase()}async function fc(e,t,n,r,i,a=Ps){let o=Is({...n,chainId:i,escrow:a}),s=gs(r),c=await $s(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function pc(e,t,n,r,i,a=Ps){let o=await fc(e,t,n,r,i,a),s=await ec(e,t,{channelId:o.channelId,cumulativeAmount:gs(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function mc(e,t,n){let r=oc(t),a=n.escrow??`0x4d50500000000000000000000000000000000000`,o=n.operator??`0x0000000000000000000000000000000000000000`,s=A.random(32),c=gs(n.deposit),l=gs(n.initialAmount),u=i({abi:Us,functionName:`open`,args:[n.payee,o,n.token,c,s,r]}),d=await cc(e,await sc(e,{account:t,calls:[...n.prefixCalls??[],{to:a,data:u}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),f=fe.deserialize(d),p={authorizedSigner:r,expiringNonceHash:zs(Rs({...n.feePayer?{feePayer:!0}:{},transaction:f}),{sender:t.address}),operator:o,payee:n.payee,payer:t.address,salt:s,token:n.token},m=Is({...p,chainId:n.chainId,escrow:a});return{action:`open`,type:`transaction`,channelId:m,transaction:d,signature:await $s(e,t,{channelId:m,cumulativeAmount:l},a,n.chainId),descriptor:p,cumulativeAmount:l.toString(),authorizedSigner:p.authorizedSigner}}async function hc(e,t,n,r,a,o,s=Ps,c=[],l=n.token){let u=Is({...n,chainId:a,escrow:s}),d=gs(r);return{action:`topUp`,type:`transaction`,channelId:u,transaction:await cc(e,await sc(e,{account:t,calls:[...c,{to:s,data:i({abi:Us,functionName:`topUp`,args:[n,d]})}],feePayer:o,feeToken:l,validAfter:ac()})),descriptor:n,additionalDeposit:d.toString()}}function gc(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Q(e){return gc({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function _c(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Q(t),t)},delete(t){e.delete(t)}}}const vc=new WeakMap,yc=new WeakMap;function bc(e,t){yc.set(e,yc.get(t)??t)}async function xc(e,t,n){let r=vc.get(e);r||(r=new Map,vc.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 Sc(e,t,n){return xc(yc.get(e)??e,`funding:${t}`,n)}async function Cc(e,t){await xc(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 wc(e,t){await xc(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}const Tc=2n**96n-1n;function Ec(e){if(e<0n||e>Tc)throw new Y({reason:`amount exceeds uint96 range`})}async function Dc(e,t,n=Ps,r){return Oc(await x(e,{address:n,abi:Us,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function Oc(e){return Ec(e.settled),Ec(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}const kc=U.custom(e=>typeof e==`string`&&d(e,{strict:!1})),Ac=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),jc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),Mc=U.object({authorizedSigner:kc,expiringNonceHash:Ac,operator:kc,payee:kc,payer:kc,salt:Ac,token:kc}),Nc=Yt(U.object({acceptedCumulative:U.string(),chainId:U.number(),channelId:Ac,closeRequestedAt:U.optional(U.string()),deposit:U.string(),descriptor:Mc,escrow:kc,highestVoucher:U.optional(U.object({channelId:Ac,cumulativeAmount:U.string(),signature:jc})),requiredCumulative:U.string(),settled:U.string(),spent:U.string(),units:U.optional(U.number())}));function Pc(e){return Nc.encode(e)}function Fc(e){return Nc.decode(e)}const Ic={status:`idle`};function Lc(e){return{status:`active`,...e}}function Rc(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:Vc(e.challengeId,t.snapshot),effects:[]}:$(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:el({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:Hc(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:$(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:rl(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?Bc({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:Hc(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:Hc(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 zc(e,t){let n=Rc(e.state,t);return e.state=n.state,n}function Bc(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 Vc(e,t){return Lc({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function Hc(e,t,n,r){return Lc({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 Uc(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function Wc(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`);Uc({cumulativeAmount:i,maxVoucherCumulative:n}),Uc({cumulativeAmount:a,maxVoucherCumulative:n})}function Gc(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;Wc({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function Kc(e,t){return typeof e==`bigint`?e:g(e,t)}function qc(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(Yc(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 Jc(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;Uc({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 Yc(e,t){Uc({cumulativeAmount:e,maxVoucherCumulative:t??null})}function Xc(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 Zc(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function Qc(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!ms(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>Zc({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function $c(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=hs(r),s=hs(a.spent);return o===void 0||s===void 0||!ms(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function el(e){return Lc({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 tl(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:Ic}}function nl(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=Gc({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&zc(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function rl(e,t){return Lc({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function il(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=hs(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 al(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 Rc(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function ol(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 sl(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 cl(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(js()),e.waitForCloseReady()))(),a=BigInt(i.spent);Qc({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=>$c({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(As(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}function ll(e){return`cumulativeAmount`in e}function ul(e){if(ll(e))return BigInt(e.cumulativeAmount)}async function dl(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await Cc(e.store,t):await wc(e.store,Q(t)),e.notifyUpdate(t)}async function fl(e,t,n){let r=ul(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 dl(e,i))}const pl=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),ml=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),hl=U.object({account:U.optional(U.custom()),autoSwap:U.optional(U.custom()),action:U.optional(U.enum([`open`,`topUp`,`voucher`,`close`])),channelId:U.optional(ml),cumulativeAmount:U.optional(W()),cumulativeAmountRaw:U.optional(U.string()),transaction:U.optional(pl),descriptor:U.optional(U.custom()),additionalDeposit:U.optional(W()),additionalDepositRaw:U.optional(U.string()),depositRaw:U.optional(U.string())});function gl(e){return e?.action!==void 0}function _l(e){return gl(e)&&e.descriptor!==void 0}function vl(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 yl(e,t,n,r){let i=vl(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function bl(e){return typeof e==`object`&&!!e}function xl(e){return typeof e==`string`&&d(e,{strict:!1})?e:void 0}function Sl(e){let t=e.request.methodDetails;return bl(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:xl(t.escrowContract),escrow:xl(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:xl(t.feeToken),operator:xl(t.operator),sessionSnapshot:nt(t,et.sessionSnapshot)}:{}}function Cl(e,t){if(typeof e==`string`&&d(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function wl(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function Tl(e){return typeof e==`string`?e:void 0}async function El(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=Sl(n);(o.chainId!==void 0||i?.length===0)&&Ga(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});Wa(c,s);let l=s??c.chain?.id;if(Ga(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=lc(n,r,t),d=Cl(n.request.recipient,`recipient`),f=Cl(n.request.currency,`currency`);return{amount:wl(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:gc({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:Tl(n.request.suggestedDeposit),token:f}}async function Dl(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=Dc}=e,o=Is({...r,chainId:i.chainId,escrow:i.escrow});Ol({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 Ol(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(!dc(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!dc(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!dc(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!dc(Fs(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function kl(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function Al(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=vl(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function jl(e){let{account:t,client:n,readChannelState:r,snapshot:i}=e,a=i.highestVoucher;if(!a)throw Error(`session snapshot is missing its highest signed voucher`);if(a.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let o=BigInt(i.acceptedCumulative),s=BigInt(a.cumulativeAmount),c=BigInt(i.requiredCumulative),l=BigInt(i.deposit),u=BigInt(i.settled),d=BigInt(i.spent);if(s!==o)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(d>o)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(u>l)throw Error(`session snapshot settled amount exceeds deposit`);if(!tc(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},Fs(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await Dl({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:oc(t),token:i.descriptor.token},readChannelState:r}),p=[o,c,f.state.settled].reduce((e,t)=>t>e?t:e,0n);if(p>f.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:f.channelId,cumulativeAmount:p,deposit:f.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:d}}function Ml(e,t){return dc(e.address,t.payer)?dc(oc(e),Fs(t)):!1}function Nl(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(gl(r)){if(!_l(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=kl({context:r,snapshot:o.snapshot});return!n&&s&&Ml(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&Ml(t,n.descriptor)?{type:`voucher`,account:t,entry:n,maxDeposit:a,resolved:o}:{type:`open`,account:t,context:r,maxDeposit:a,resolved:o}}async function Pl(e,t,n=!1){switch(e.type){case`open`:return Ll(e,t,n);case`recover`:return Rl(e,t);case`voucher`:return zl(e,t);case`manual`:return Bl(e,t,n)}}async function Fl(e,t){if(e)return await $a(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function Il(e,t){let{account:n,amount:r,chainId:i,client:a,token:o}=t;if(e||!uo({chainId:i,currency:o}))return;let s=await vo(a,{account:n,amount:r,chainId:i});if(s)throw s}async function Ll(e,t,n){let{account:r,resolved:i}=e,a=qc({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw});await Il(n,{account:r.address,amount:a,chainId:i.chainId,client:i.client,token:i.token});let o=await mc(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 Fl(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await dl(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function Rl(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await Dl({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:oc(n),token:o.token}}),l=Al({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`);Yc(l,a);let u=await fc(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await dl(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 zl(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;Yc(a,e.maxDeposit);let o=await fc(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await dl(t,r),o}async function Bl(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=Is({...s,chainId:o.chainId,escrow:o.escrow});Ol({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:oc(r),token:o.token});let l=await Vl({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await fl(t,o.key,l),l}async function Vl(e,t){switch(e.context.action){case`open`:return Hl(e);case`topUp`:return Ul(e,t);case`voucher`:return Wl(e);case`close`:return Gl(e)}}async function Hl(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=yl(r,i,`cumulativeAmount`,`open`),c=await fc(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 Ul(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=yl(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:(await Il(t,{account:n.address,amount:c,chainId:s.chainId,client:s.client,token:s.token}),hc(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await Fl(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken))}function Wl(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return fc(a.client,t,i,yl(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function Gl(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return pc(a.client,t,i,yl(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}const Kl={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function ql(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=Kl.CLOSED,r=null}if(a.type===`open`&&(i=Kl.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 Jl(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function Yl(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=Kc(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 Xl(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:rl(s,u)}:i?{channel:u,state:el({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function Zl(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=Jl(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:gs(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function Ql(e){return e.method===Qe.tempo&&e.intent===$e.session}function $l(e){return Ql(e)&&nt(e.request.methodDetails,et.sessionProtocol)===tt.v2}function eu(e){return nt(e.request.methodDetails,et.sessionSnapshot)}function tu(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return ui({...t,redirect:`manual`,headers:{...ra(i),...ra(t?.headers)}},Et(r),n)}function nu(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 ru(e){try{let t=typeof location>`u`?void 0:location.href,n=nu(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function iu(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function au(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 ou=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 su(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 cu({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 ou&&(t.uncertainTopUp=!0,await e.onUncertainFunding?.(t)),n});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(V.paymentReceipt);return i?Es(i):void 0}async function cu(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(ru(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:Mu(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new ou(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=St(n).find($l);return r?t(r):n}async function lu(e){let t=uu({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,tu(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(V.paymentReceipt)&&await l(),u}function uu(e){let t=St(e.response).find($l);if(!t)return;let n=eu(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function du(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=nu(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?ru(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:Mu(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=St(o).find($l);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await au(o),t=o.headers.get(V.wwwAuthenticate)??``;throw Error(`Close request failed with status ${o.status}${e?`: ${e}`:``}${t?` [${V.wwwAuthenticate}: ${t}]`:``}`)}let s=o.headers.get(V.paymentReceipt);if(!s)return;let c=Es(s);if(!c.txHash||!A.validate(c.txHash,{strict:!0})||A.size(c.txHash)!==32||!$c({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 fu(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...ra(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!Ds(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),pu(e,c,{onReceipt:r,signal:o},n,s.headers)}function pu(e,t,n,r,i){if(!Ds(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return mu({onNeedVoucher:t=>yu({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*mu(e){for await(let t of hu(e))t.data!==void 0&&(yield t.data)}async function*hu(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=gu(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=Os(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 gu(e,t){for(let n=0;n<e.length;n++){let r=_u(e,n,t);if(!r)continue;let i=_u(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function _u(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 du(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=cu({...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 fu(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await Wl({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 tu({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 pu(e){let t=new URL(e.input.toString()),n=Zl(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=xt(r).find(Kl);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 mu(e){e.signal?.throwIfAborted();let t=await pu(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function hu(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:jt(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:gs(t)}}function gu(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function _u(e){if(!gu(e))return`received mismatched payment-close-ready frame`;let t=cs(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 vu(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!gu(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!Kc({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function yu(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=hu({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=Bl(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===zl.CONNECTING||s.readyState===zl.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 xu({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await bu(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(Cs(n)),await e.waitForReceipt(),l.socket}function bu(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 xu(e){let t=Ts(e.message);if(!t){e.managedEmit(`message`,{data:e.message,type:`message`});return}switch(t.mpp){case`authorization`:return;case`message`:e.socketState.deliveredChunks+=1n,e.managedEmit(`message`,{data:t.data,type:`message`});return;case`payment-close-ready`:Su(e,t.data);return;case`payment-error`:e.driver.rejectReceipt(Error(t.message)),e.driver.rejectCloseReady(Error(t.message));return;case`payment-need-voucher`:await Cu(e,t.data);return;case`payment-receipt`:wu(e,t.data);return}}function Su(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=_u({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,cumulativeAmount:n,receipt:t});if(r){e.failSocketFlow(r);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleCloseReady(t),e.managedEmit(`close`,{code:1e3,reason:`stream complete`,type:`close`,wasClean:!0})}async function Cu(e,t){try{let n=e.driver.challenge;n.expires&&new Date(n.expires).getTime()<=Date.now()+5e3&&(n=await e.driver.refreshChallenge(),e.driver.challenge=n,e.socketState.challenge=n);let r=await Wl({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(Cs(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function wu(e,t){let n=vu({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 Tu(e,t,n,r){let i=Tt(e),a=new Headers;if(i.toLowerCase()!==V.authorization.toLowerCase()){let e=new Headers(r).get(V.authorization)??(n instanceof Request?n.headers.get(V.authorization):null);e&&!e.startsWith(`${Xe.payment} `)&&a.set(V.authorization,e)}return a.set(i,t),a}const Eu=new WeakMap;async function Du(e,t){let n=Eu.get(e)??new Map;Eu.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 Ou(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function ku(e,t,n){try{let r=e.response?.headers.get(V.paymentReceipt);if(r){let e=ys(r);if(e.challengeId===t.id&&Ou(n,e))return!0}}catch{}return e.challenges?.some(e=>Kl(e)?Ou(n,ql(e)):!1)??!1}function Au(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??[])ju(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 ju(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 h(e,t)}}function Mu(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>ju(e.maxAmount,r?.decimals))throw Error(`Tempo session amount exceeds maxAmount.`)}function Nu(e,t){try{return Mu(e,t),!0}catch{return!1}}function Pu(e){return typeof e==`object`&&!!e&&e.action===`close`}function Fu(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=Au(e),m=Va({chain:ne,getClient:c,rpcUrl:ir}),g=La({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:h(l,n),topUpAmount:u===void 0?void 0:h(u,n)}};l!==void 0&&h(l,6),u!==void 0&&h(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??uc(),b={store:y,notifyUpdate:e=>d?.(e)},x=async(e,t,n)=>{let r=g(e.client,t),i=t?.action?t.descriptor:n?.descriptor??Sl({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:Os(i)}:{}}})??r},S=async(e,t,n)=>{let{decimals:r,maxDeposit:i}=_(e.challenge.request,e.chainId);return El({account:await x(e,t,n),entry:n,context:t,decimals:r,maxDeposit:i,resolved:e})},C=Kt(Ko,{canHandleChallenge:({challenge:e,context:t})=>Kl(e)&&(Pu(t)||t===Vr||Nu(p,e.request)),context:cl,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&Mu(p,t.request);let a=await yl({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m});i?.action!==`close`&&t.request.methodDetails?.chainId===void 0&&Mu(p,t.request,a.chainId);let c=Ri(e),l=Ui(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=!ll(i)&&i?.descriptor===void 0;e&&(d=await Du(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 Du(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 rc(t,await Dl(o,f,Qa(i?.autoSwap??r,Xa)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||ku(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 gc(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 Hi(r,Iu(n)),C.createCredential(r)}let ee=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>hc(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=Vc({deposit:l,maxDeposit:u,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:d});f>0n&&await eu({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 gc(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 gc(y,g),b.notifyUpdate(g)});return Di(C,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!Kl(e))return;let c=t===void 0?void 0:cl.parse(t);if(ll(c))return;Mu(p,e.request);let l=await yl({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),u=await y.get(l.key);if(!u?.opened)return;let d=Iu(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+gs(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||!Tl(await x(l,c,u),u.descriptor)||await ee({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:b,fetch:r,input:i,requiredCumulative:_,signal:a})}),Fi(C,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!Kl(e))return u;if(!bs(u))return hs(jt(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await yl({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,p=await y.get(f),h={assertVoucherWithinLocalLimit:t=>Hc(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 ee({autoSwap:t===void 0?void 0:cl.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return du({onNeedVoucher:(t,n)=>fu({challenge:e,driver:h,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function Iu(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 Lu=new WeakMap;function Ru(e,t){Lu.set(e,t)}function zu(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 Bu(e){let t=zu(`close-ready`),n=zu(`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 Vu(e){return e.method===Ze.tempo&&e.intent===Qe.charge}function Hu(e){if(!Vu(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Uu(e,t,n){if(!n)return t;let r={...ta(Yl(e)?e.headers:void 0),...ta(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===V.paymentSession.toLowerCase())?t:{...t,headers:{...r,[V.paymentSession]:n}}}function Wu(e,t){return e===void 0?t:{...cl.parse(e),...t}}function Gu(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:h(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:h(e.topUpAmount,t),WebSocket:n}}function Ku(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&Ua(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=Gu(e),i;function a(e){let t=new URL(Yl(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=Ca(r.fetch),s=wa(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??(Yl(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=Rr(c,o));let l=Va({chain:ne,getClient:e.client?()=>e.client:e.getClient,rpcUrl:ir}),u=La({account:e.account}),d=Jc(),f=e.credentialContext===void 0?void 0:Wu(e.credentialContext,{}),p=Bu({getSocketSession:()=>d.socketSession}),m=e.channelStore??uc(),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,gc(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=>_c(m,e)};pc(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(_c(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(_c(m,t)).catch(()=>void 0)}e.created.clear(),await ce(e.committed??e.previous)}}function S(e){let t=tt(e.request.methodDetails,$e.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=g;if(!n?.created.size||!d.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&d.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=$c({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function C(e){return Mc(d,e)}function w(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function ee(e){let t=g,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit&&!e.uncertainTopUp||(t.resumed=void 0,t.committed=$c({channel:d.channel,spent:d.spent,state:d.state}))}let T=Fu({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:y,onChannelUpdate(e){e.channelId!==d.channel?.channelId&&(d.spent=0n),d.channel=e,d.lastChallenge&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),ee(e)}}),te=Ai(T);te&&Di(T,e=>ie(()=>Promise.resolve(te(e)),e.signal)),Ii(T);let E=Yo({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),D=ea({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[T],onChallenge:async(e,t)=>{if(!Gl(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&ft(e)===ft(d.lastChallenge);n&&n.challengesReceived++,!i&&(S(e)||(n?.created.size?await x():r&&await ce(n.committed??n.previous)),d.lastChallenge=e,C({type:`challengeReceived`,challengeId:e.id}))}});function O(e,t){let n={challenge:e,context:Wu(f,t)};return i&&Hi(n,i),T.createCredential(n)}function k(e){Yc({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 n=t.headers.get(V.paymentSessionSnapshot);if(!n)return;let r=Oc(n);Ua(e.allowedChainIds,r.chainId);let i=await l({chainId:r.chainId});Ha(i,r.chainId);let a=u(i),{entry:o,spent:s}=await wl({account:await e.resolveAccount?.({account:a,chainId:r.chainId,operation:{authority:Os(r.descriptor),kind:`authorizePaymentChannel`}})??a,client:i,snapshot:r});return L(o.cumulativeAmount),await Promise.resolve(y.set(o)).catch(()=>void 0),d.channel=o,d.spent=s,o}async function M(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=Yl(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=Yl(t)?t.url:t,l={...s,method:`HEAD`,headers:{...ta(i),...ta(n?.headers),[V.acceptPayment]:`${Ze.tempo}/${Qe.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await j(t);let n=xt(t).find(Vu);if(!n||!Hu(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;Wi(n,i,e.trustedTempoProofRealms);let a=await E.createCredential({challenge:n,context:{}}),o=await r.fetch(c,ci({...l,redirect:`manual`},Tt(n),a));return o.ok?await j(o):void 0}catch{return}}function N(e,t){let n=d.socketSession;return Zc({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=ql(t);if(!n)return;if(ks({...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){Ic({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let R,re;async function ie(e,t){if(re)throw re;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(),re)throw re;let n=e();R=n;try{return await n}catch(e){throw e instanceof $l&&(re=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 ae(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return hc(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 eu({...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),ee(n)}});k(a);let o=d.channel,s=Ul({additionalDeposit:e.additionalDeposit,channel:d.channel,channelId:e.channelId,challengeId:d.lastChallenge?.id,currentState:d.state,knownDeposit:t,receipt:a,spent:d.spent});if(s?.channel&&d.lastChallenge){let e=s.channel;for(;;){await y.set(e);let t=d.channel;if(t===o)break;if(!t)return a;let n=s.channel;e=t.channelId===n.channelId?{...t,deposit:t.deposit>n.deposit?t.deposit:n.deposit,cumulativeAmount:t.cumulativeAmount>n.cumulativeAmount?t.cumulativeAmount:n.cumulativeAmount}:t,o=t}if(e.channelId!==s.channel.channelId)return a;d.channel=e,C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),ee(e)}return a})}async function oe(e){return ie(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=Vc({deposit:n,maxDeposit:r.maxVoucherCumulative,requiredCumulative:e.requiredCumulative,suggestedDeposit:e.challenge.request.suggestedDeposit===void 0?void 0:BigInt(e.challenge.request.suggestedDeposit),topUpAmount:r.topUpAmount});i!==0n&&await ae({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function se(e,t){let n=Qc({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 ce(e){let t=el(e,d.channel);d.channel=t.channel,d.spent=t.spent,d.state=t.state,d.channel?.opened&&await v(d.channel)}function z(e){let t=e.headers.get(V.paymentReceipt),n=t?ys(t):null;return k(n),Object.assign(e,{receipt:n,challenge:d.lastChallenge,channelId:d.channel?.channelId??null,cumulative:d.channel?.cumulativeAmount??0n})}async function le(e,t){if(g)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);a(e),d.lastUrl=e,d.lastHeaders=t?.headers;let n=$c({channel:d.channel,spent:d.spent,state:d.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};g=i;try{await M(e,t),i.trackCreates=!0;let a=Uu(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=Uu(e,t,void 0),!0)}for(;;){let t;try{t=await D(e,a)}catch(e){if(i.created.size?await x():await ce(i.committed??n),await s())continue;throw e}let o=z(t),c=!1;if(o.status===402){let t=await nu({input:e,init:a,response:o,createSessionCredential:O,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:se,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:oe});t&&(c=!0,o=z(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await x():await ce(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function ue(e){let t=await iu({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 de={createSessionCredential:O,doFetch:le,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:L,acceptReceipt(e){k(e)},topUpIfNeeded:oe},fe={get channelId(){return d.channel?.channelId},get cumulative(){return d.channel?.cumulativeAmount??0n},get opened(){return d.channel?.opened??!1},get state(){return d.state},fetch:le,async topUp(e){let t=Hl({amount:e,assertVoucherWithinLocalLimit:L,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return ie(async()=>{if(d.channel?.channelId!==t.channelId||d.lastChallenge!==t.challenge||d.lastUrl!==t.input)throw Error(`Session changed while waiting to top up`);let n=Hl({amount:e,assertVoucherWithinLocalLimit:L,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return ae({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){return au(e,t,de)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=Zl(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 mu({async createSessionCredential(e,i){return d.lastChallenge=e,await ki(T,{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:Uu(n,i,o),signal:t?.signal});return d.lastChallenge=s,yu({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 pu({fetch:r.fetch,input:l,probeInit:Uu(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:oe,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=Uc({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===zl.OPEN){let r=await tl({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 ue(t)}};return Ru(fe,{consumeSseResponse(e,t,n){let r=a(e);if(t.url&&new URL(t.url).origin!==r)throw Error(`SessionManager: session response origin mismatch`);return ou(e,t,n,de)},rehydrate({channel:e,challenge:t,input:n,spent:r}){let i=a(n);if(e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!Gl(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})}}),fe}(function(e){e.serializeSnapshot=Dc,e.deserializeSnapshot=Oc})(Ku||={});const qu=(1n<<64n)-1n,Ju={dev_second:1n,day:86400n,week:604800n};function Yu(e){return e instanceof Date?e:new Date(e)}function Xu(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 Zu(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new Y({reason:`periodCount is invalid`});let t=Ju[e.periodUnit];if(t===void 0)throw new Y({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>qu)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 Qu(e){let{challengeExpires:t,request:n}=e;Zu(n);let r=Xu(Yu(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 $u(e){return[{address:fd(e.currency,`currency`),selector:`0x95777d59`,recipients:[fd(e.recipient,`recipient`)]}]}function ed(e){try{let t=A.fromBytes(D.toBytes(e));if(A.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new Y({reason:`challenge id must encode 32 bytes`})}}async function td(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=rd({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:ge.getSignPayload(o)}),c=B.from(s);if(c.type===`keychain`||c.type===`configurable`)throw new Y({reason:`keyAuthorization must use a primitive signature`});return ge.from(o,{signature:s})}function nd(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=id(i.signature),s=ad(o);if(od({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==ed(n))throw new Y({reason:`keyAuthorization challenge mismatch`});return sd(o,a),ld(cd(o),a),ud(o.scopes,a),{authorization:o,source:{address:dd(o,s),chainId:r}}}function rd(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return ge.from({address:fd(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:Xu(Yu(i.subscriptionExpires)),limits:[{token:fd(i.currency,`currency`),limit:BigInt(i.amount),period:Zu(i)}],scopes:$u(i),type:t.keyType,witness:ed(n)})}function id(e){try{return ge.deserialize(e)}catch(e){throw e instanceof ge.InvalidSignatureTypeError?new Y({reason:`keyAuthorization must use a primitive signature`}):new Y({reason:`invalid keyAuthorization payload`})}}function ad(e){let t=e.signature;if(!t)throw new Y({reason:`keyAuthorization must use a primitive signature`});return t}function od(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new Y({reason:`keyAuthorization chainId mismatch`});if(t){if(!d(n.address,fd(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 sd(e,t){if(Qu({request:t}),e.expiry!==Xu(Yu(t.subscriptionExpires)))throw new Y({reason:`keyAuthorization expiry mismatch`})}function cd(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 ld(e,t){if(!d(e.token,fd(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!==Zu(t))throw new Y({reason:`keyAuthorization period mismatch`})}function ud(e,t){if(!e||e.length!==1)throw new Y({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=fd(t.currency,`currency`),r=fd(t.recipient,`recipient`),i=new Set;for(let t of e){if(!d(t.address,n))throw new Y({reason:`keyAuthorization call target mismatch`});let e=pd(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||!d(t.recipients[0],r))throw new Y({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new Y({reason:`keyAuthorization must allow transferWithMemo`})}function dd(e,t){let n=ge.getSignPayload(e);try{let e=B.extractAddress({payload:n,signature:t});if(!B.verify(t,{address:e,payload:n}))throw new Y({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof Y?e:new Y({reason:`keyAuthorization signature is invalid`})}}function fd(e,t){if(!u(e))throw new Y({reason:`${t} must be an address`});return e.toLowerCase()}function pd(e){return typeof e==`string`?e.toLowerCase():``}const md=U.object({accessKey:U.optional(U.custom()),account:U.optional(U.custom())});function hd(e={}){let t=Va({chain:R,getClient:e.getClient,rpcUrl:ir}),n=La({account:e.account});return Kt(qo,{context:md,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??X.testnet,o=await t({chainId:a}),s=n(o,i),c=i?.accessKey??e.accessKey??r.request.methodDetails?.accessKey;if(!c)throw Error("No `accessKey` provided. The subscription challenge must include `accessKey`, or the client must pass one to parameters/context.");_d(r.request),await e.validateRequest?.(r.request);let l=await gd(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=nd({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:ge.serialize(l),type:`keyAuthorization`},request:r.request});if(!d(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return Ft({challenge:r,payload:{signature:ge.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function gd(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await td({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:Xu(Yu(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:A.fromNumber(BigInt(o.amount)),period:Zu(o)}],scopes:$u(o),witness:ed(i)}]});return ge.fromRpc(c.keyAuthorization)}function _d(e){Zu(e),Xu(Yu(e.subscriptionExpires))}const vd=Object.assign(Fu,{manager:Ku});function yd(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[Yo(e),vd(n)]}(function(e){e.charge=Yo,e.common=yd,e.session=vd,e.subscription=hd})(yd||={});const bd=L.union([L.boolean(),L.literal(`true`).transform(()=>!0),L.literal(`false`).transform(()=>!1)]);async function xd(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}const Sd=L.object({allowCustomEscrow:L.optional(bd),autoSwap:L.optional(bd),channel:L.optional(L.coerce.string()),deposit:L.optional(L.union([L.string(),L.number()])),payWith:L.optional(L.string()),slippage:L.optional(L.coerce.number()),tokenIn:L.optional(L.string())}),Cd=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`];function wd(){let t;return wr({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:n,options:r,methodOpts:i}){let a=br(r.account),o=n.request,s=o.currency,c=Ad(i),u=Pd({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()||(or(a)?void 0:await xr(a).get());if(!_&&or(a)&&Ud()){g=!0;let t=Vd(a);if(t){let i=lr(r.rpcUrl,{network:r.network});h=e({chain:await ur({network:r.network,rpcUrl:i}),transport:l(i)}),Md({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let a=s?await pr(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=Gd();if(e){let t=await xr(e).get();t&&(m=me(t))}if(!m)throw r.account?new $n({code:`ACCOUNT_NOT_FOUND`,message:`Account "${a}" not found.`,exitCode:69}):new $n({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!g&&m){let t=lr(r.rpcUrl,{network:r.network});h=e({chain:await ur({network:r.network,rpcUrl:t}),transport:l(t)}),Md({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let i=s?await pr(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 Wd(t)}};if(!m||!h)throw new $n({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let v=yd({account:m,...c.allowCustomEscrow===void 0?{}:{allowCustomEscrow:c.allowCustomEscrow},getClient:()=>h,...u===void 0?{}:{autoSwap:u},maxDeposit:(()=>{if(n.intent!==`session`)return;let e=n.request.suggestedDeposit,t=(c.deposit===void 0?void 0:String(c.deposit))??e??(fr(h.chain)?`10`:void 0);if(!t)throw new $n({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=Id(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 Ks(h,m,c,i,a);return Ft({challenge:n,payload:{action:o,channelId:e,...o===`close`?{closeSignature:await qs(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=jt(r),g=n.request,_=g.methodDetails,v=h.payload.channelId,y=_?.escrowContract??_?.escrow??`0x4d50500000000000000000000000000000000000`,b=_?.chainId??0,x=BigInt(g.amount),S=`cumulativeAmount`in h.payload&&h.payload.cumulativeAmount?BigInt(h.payload.cumulativeAmount):0n;if(`descriptor`in h.payload&&(t.descriptor=h.payload.descriptor),s>=1){if(h.payload.action===`open`){let e=g.suggestedDeposit,t=e?` ${Z.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
12
+ `?2:t+1===e.length&&!n?0:1:0}function vu(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=hu({...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 yu(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await Zl({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 cu({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 bu(e){let t=new URL(e.input.toString()),n=iu(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=St(r).find($l);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 xu(e){e.signal?.throwIfAborted();let t=await bu(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function Su(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:Mt(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:Cs(t)}}function Cu(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function wu(e){if(!Cu(e))return`received mismatched payment-close-ready frame`;let t=hs(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 Tu(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!Cu(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!$c({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function Eu(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=Su({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=ql(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===Kl.CONNECTING||s.readyState===Kl.OPEN)&&s.close(3008,t)},d=()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),s.close()};s.addEventListener(`close`,t=>{o?.removeEventListener(`abort`,d),c.socket=null,c.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),l.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),s.addEventListener(`error`,()=>{l.emit(`error`,{type:`error`})}),s.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await Ou({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await Du(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(As(n)),await e.waitForReceipt(),l.socket}function Du(e,t,n,r){return new Promise((i,a)=>{let o=()=>{e.removeEventListener(`open`,s),e.removeEventListener(`error`,c),e.removeEventListener(`close`,c),r?.removeEventListener(`abort`,l)},s=()=>{o(),t(`open`,{type:`open`}),i()},c=()=>{o(),a(Error(`WebSocket connection to ${n} failed to open.`))},l=()=>{o(),a(r?.reason)};e.addEventListener(`open`,s,{once:!0}),e.addEventListener(`error`,c,{once:!0}),e.addEventListener(`close`,c,{once:!0}),r?.addEventListener(`abort`,l,{once:!0}),r?.aborted&&l()})}async function Ou(e){let t=Ms(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`:ku(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 Au(e,t.data);return;case`payment-receipt`:ju(e,t.data);return}}function ku(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=wu({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 Au(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 Zl({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(As(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function ju(e,t){let n=Tu({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 Mu(e,t,n,r){let i=Et(e),a=new Headers;if(i.toLowerCase()!==V.authorization.toLowerCase()){let e=new Headers(r).get(V.authorization)??(n instanceof Request?n.headers.get(V.authorization):null);e&&!e.startsWith(`${Ze.payment} `)&&a.set(V.authorization,e)}return a.set(i,t),a}const Nu=new WeakMap;async function Pu(e,t){let n=Nu.get(e)??new Map;Nu.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 Fu(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function Iu(e,t,n){try{let r=e.response?.headers.get(V.paymentReceipt);if(r){let e=Es(r);if(e.challengeId===t.id&&Fu(n,e))return!0}}catch{}return e.challenges?.some(e=>$l(e)?Fu(n,eu(e)):!1)??!1}function Lu(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??[])Ru(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 Ru(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 zu(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>Ru(e.maxAmount,r?.decimals))throw Error(`Tempo session amount exceeds maxAmount.`)}function Bu(e,t){try{return zu(e,t),!0}catch{return!1}}function Vu(e){return typeof e==`object`&&!!e&&e.action===`close`}function Hu(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=Lu(e),m=Ua({chain:re,getClient:c,rpcUrl:or}),h=za({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??_c(),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??kl({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:Fs(i)}:{}}})??r},S=async(e,t,n)=>{let{decimals:r,maxDeposit:i}=_(e.challenge.request,e.chainId);return Nl({account:await x(e,t,n),entry:n,context:t,decimals:r,maxDeposit:i,resolved:e})},C=Jt($o,{canHandleChallenge:({challenge:e,context:t})=>$l(e)&&(Vu(t)||t===Ur||Bu(p,e.request)),context:hl,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&zu(p,t.request);let a=await El({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m});i?.action!==`close`&&t.request.methodDetails?.chainId===void 0&&zu(p,t.request,a.chainId);let c=Bi(e),l=Gi(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=!gl(i)&&i?.descriptor===void 0;e&&(d=await Pu(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 Pu(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 uc(t,await Pl(o,f,eo(i?.autoSwap??r,Qa)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||Iu(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 Cc(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 Wi(r,Uu(n)),C.createCredential(r)}let ee=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>Sc(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=Jc({deposit:l,maxDeposit:u,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:d});f>0n&&await su({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 Cc(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 Cc(y,g),b.notifyUpdate(g)});return ki(C,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!$l(e))return;let c=t===void 0?void 0:hl.parse(t);if(gl(c))return;zu(p,e.request);let l=await El({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),u=await y.get(l.key);if(!u?.opened)return;let d=Uu(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+Cs(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||!Ml(await x(l,c,u),u.descriptor)||await ee({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:b,fetch:r,input:i,requiredCumulative:_,signal:a})}),Li(C,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!$l(e))return u;if(!Ds(u))return Ss(Mt(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await El({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,p=await y.get(f),h={assertVoucherWithinLocalLimit:t=>Yc(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 ee({autoSwap:t===void 0?void 0:hl.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return vu({onNeedVoucher:(t,n)=>yu({challenge:e,driver:h,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function Uu(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 Wu=new WeakMap;function Gu(e,t){Wu.set(e,t)}function Ku(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 qu(e){let t=Ku(`close-ready`),n=Ku(`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 Ju(e){return e.method===Qe.tempo&&e.intent===$e.charge}function Yu(e){if(!Ju(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Xu(e,t,n){if(!n)return t;let r={...ra(nu(e)?e.headers:void 0),...ra(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===V.paymentSession.toLowerCase())?t:{...t,headers:{...r,[V.paymentSession]:n}}}function Zu(e,t){return e===void 0?t:{...hl.parse(e),...t}}function Qu(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 $u(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&Ga(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=Qu(e),i;function a(e){let t=new URL(nu(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=Ta(r.fetch),s=Ea(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??(nu(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=Br(c,o));let l=Ua({chain:re,getClient:e.client?()=>e.client:e.getClient,rpcUrl:or}),u=za({account:e.account}),d=tl(),f=e.credentialContext===void 0?void 0:Zu(e.credentialContext,{}),p=qu({getSocketSession:()=>d.socketSession}),m=e.channelStore??_c(),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,Cc(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=>wc(m,e)};bc(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(wc(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(wc(m,t)).catch(()=>void 0)}e.created.clear(),await ce(e.committed??e.previous)}}function S(e){let t=nt(e.request.methodDetails,et.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=ol({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function C(e){return zc(d,e)}function w(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function ee(e){let t=g,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit&&!e.uncertainTopUp||(t.resumed=void 0,t.committed=ol({channel:d.channel,spent:d.spent,state:d.state}))}let T=Hu({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:y,onChannelUpdate(e){e.channelId!==d.channel?.channelId&&(d.spent=0n),d.channel=e,d.lastChallenge&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),ee(e)}}),te=Mi(T);te&&ki(T,e=>ie(()=>Promise.resolve(te(e)),e.signal)),Ri(T);let ne=ns({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),E=na({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[T],onChallenge:async(e,t)=>{if(!Ql(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&pt(e)===pt(d.lastChallenge);n&&n.challengesReceived++,!i&&(S(e)||(n?.created.size?await x():r&&await ce(n.committed??n.previous)),d.lastChallenge=e,C({type:`challengeReceived`,challengeId:e.id}))}});function D(e,t){let n={challenge:e,context:Zu(f,t)};return i&&Wi(n,i),T.createCredential(n)}function O(e){nl({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:d})}function k(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 A(t){let n=t.headers.get(V.paymentSessionSnapshot);if(!n)return;let r=Fc(n);Ga(e.allowedChainIds,r.chainId);let i=await l({chainId:r.chainId});Wa(i,r.chainId);let a=u(i),{entry:o,spent:s}=await jl({account:await e.resolveAccount?.({account:a,chainId:r.chainId,operation:{authority:Fs(r.descriptor),kind:`authorizePaymentChannel`}})??a,client:i,snapshot:r});return I(o.cumulativeAmount),await Promise.resolve(y.set(o)).catch(()=>void 0),d.channel=o,d.spent=s,o}async function j(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=nu(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=nu(t)?t.url:t,l={...s,method:`HEAD`,headers:{...ra(i),...ra(n?.headers),[V.acceptPayment]:`${Qe.tempo}/${$e.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await A(t);let n=St(t).find(Ju);if(!n||!Yu(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;Ki(n,i,e.trustedTempoProofRealms);let a=await ne.createCredential({challenge:n,context:{}}),o=await r.fetch(c,ui({...l,redirect:`manual`},Et(n),a));return o.ok?await A(o):void 0}catch{return}}function M(e,t){let n=d.socketSession;return il({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 N(e,t){let n=eu(t);if(!n)return;if(Is({...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 P(e,t){let n=N(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 F(e,t=e.challenge,n=!1){let r=(n?P(e,t):N(e.channel,t))?.acceptedCumulative??M(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return I(r),r.toString()}function I(e){Uc({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let L,R;async function ie(e,t){if(R)throw R;for(;;){let e=L;if(!e)break;if(!t)await e;else{t.throwIfAborted();let n;try{await Promise.race([e,new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0})})])}finally{t.removeEventListener(`abort`,n)}}}if(t?.throwIfAborted(),R)throw R;let n=e();L=n;try{return await n}catch(e){throw e instanceof ou&&(R=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{L===n&&(L=void 0)}}async function ae(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return Sc(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 su({...n,channel:d.channel,createSessionCredential:D,fetch:r.fetch,onUncertainFunding:async e=>{let t=await y.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};d.channel?.channelId===e.channelId&&(d.channel=n),await y.set(n),ee(n)}});O(a);let o=d.channel,s=Xl({additionalDeposit:e.additionalDeposit,channel:d.channel,channelId:e.channelId,challengeId:d.lastChallenge?.id,currentState:d.state,knownDeposit:t,receipt:a,spent:d.spent});if(s?.channel&&d.lastChallenge){let e=s.channel;for(;;){await y.set(e);let t=d.channel;if(t===o)break;if(!t)return a;let n=s.channel;e=t.channelId===n.channelId?{...t,deposit:t.deposit>n.deposit?t.deposit:n.deposit,cumulativeAmount:t.cumulativeAmount>n.cumulativeAmount?t.cumulativeAmount:n.cumulativeAmount}:t,o=t}if(e.channelId!==s.channel.channelId)return a;d.channel=e,C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),ee(e)}return a})}async function oe(e){return ie(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=Jc({deposit:n,maxDeposit:r.maxVoucherCumulative,requiredCumulative:e.requiredCumulative,suggestedDeposit:e.challenge.request.suggestedDeposit===void 0?void 0:BigInt(e.challenge.request.suggestedDeposit),topUpAmount:r.topUpAmount});i!==0n&&await ae({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function se(e,t){let n=al({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 ce(e){let t=sl(e,d.channel);d.channel=t.channel,d.spent=t.spent,d.state=t.state,d.channel?.opened&&await v(d.channel)}function le(e){let t=e.headers.get(V.paymentReceipt),n=t?Es(t):null;return O(n),Object.assign(e,{receipt:n,challenge:d.lastChallenge,channelId:d.channel?.channelId??null,cumulative:d.channel?.cumulativeAmount??0n})}async function z(e,t){if(g)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);a(e),d.lastUrl=e,d.lastHeaders=t?.headers;let n=ol({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 j(e,t),i.trackCreates=!0;let a=Xu(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=Xu(e,t,void 0),!0)}for(;;){let t;try{t=await E(e,a)}catch(e){if(i.created.size?await x():await ce(i.committed??n),await s())continue;throw e}let o=le(t),c=!1;if(o.status===402){let t=await lu({input:e,init:a,response:o,createSessionCredential:D,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:se,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:oe});t&&(c=!0,o=le(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await x():await ce(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function ue(e){let t=await du({createSessionCredential:D,fetch:r.fetch,getMinimumSpent:()=>d.spent,headers:d.lastHeaders,lastUrl:d.lastUrl,resolveSignedCloseAmount:t=>F(e,t,!0),signedCloseAmount:F(e),setChallenge(e){d.lastChallenge=e},target:e});return t&&(k(),C({type:`closeStarted`}),C({type:`closed`,receipt:t})),t}let de={createSessionCredential:D,doFetch:z,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:I,acceptReceipt(e){O(e)},topUpIfNeeded:oe},fe={get channelId(){return d.channel?.channelId},get cumulative(){return d.channel?.cumulativeAmount??0n},get opened(){return d.channel?.opened??!1},get state(){return d.state},fetch:z,async topUp(e){let t=Yl({amount:e,assertVoucherWithinLocalLimit:I,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return ie(async()=>{if(d.channel?.channelId!==t.channelId||d.lastChallenge!==t.challenge||d.lastUrl!==t.input)throw Error(`Session changed while waiting to top up`);let n=Yl({amount:e,assertVoucherWithinLocalLimit:I,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return ae({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){return fu(e,t,de)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=iu(e);a(n);let i=t?.signal?{signal:t.signal}:void 0;await j(n,i);let o=d.channel?.opened?d.channel.channelId:void 0,{challenge:s,credential:c,httpUrl:l,wsUrl:u}=await xu({async createSessionCredential(e,i){return d.lastChallenge=e,await ji(T,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),D(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){d.lastUrl=e.toString()},probeInit:Xu(n,i,o),signal:t?.signal});return d.lastChallenge=s,Eu({challenge:s,credential:c,httpUrl:l,WebSocket:r.WebSocket,wsUrl:u,options:t,createSessionCredential:D,getChannel:()=>d.channel,setSocketSession(e){d.socketSession=e},async refreshChallenge(){let e=await bu({fetch:r.fetch,input:l,probeInit:Xu(l,i,d.channel?.opened?d.channel.channelId:void 0),signal:t?.signal});return d.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:I,acceptReceipt:O,rejectCloseReady:p.rejectCloseReady,rejectReceipt:p.rejectReceipt,settleCloseReady:p.settleCloseReady,settleReceipt:p.settleReceipt,topUpIfNeeded:oe,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=Xc({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===Kl.OPEN){let r=await cl({activeSocket:n,createSessionCredential:D,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return k(),C({type:`closeStarted`}),C({type:`closed`,receipt:r}),r}return ue(t)}};return Gu(fe,{consumeSseResponse(e,t,n){let r=a(e);if(t.url&&new URL(t.url).origin!==r)throw Error(`SessionManager: session response origin mismatch`);return pu(e,t,n,de)},rehydrate({channel:e,challenge:t,input:n,spent:r}){let i=a(n);if(e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!Ql(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.`);I(e.cumulativeAmount);let o=N(e,t),s=o&&o.spent>r?o.spent:r;d.lastUrl=n,d.lastChallenge=t,d.channel=e,d.spent=s,C({type:`challengeReceived`,challengeId:t.id}),C({type:`activated`,challengeId:t.id,entry:e,spent:s.toString(),units:0})}}),fe}(function(e){e.serializeSnapshot=Pc,e.deserializeSnapshot=Fc})($u||={});const ed=(1n<<64n)-1n,td={dev_second:1n,day:86400n,week:604800n};function nd(e){return e instanceof Date?e:new Date(e)}function rd(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 id(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new Y({reason:`periodCount is invalid`});let t=td[e.periodUnit];if(t===void 0)throw new Y({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>ed)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 ad(e){let{challengeExpires:t,request:n}=e;id(n);let r=rd(nd(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 od(e){return[{address:yd(e.currency,`currency`),selector:`0x95777d59`,recipients:[yd(e.recipient,`recipient`)]}]}function sd(e){try{let t=A.fromBytes(D.toBytes(e));if(A.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new Y({reason:`challenge id must encode 32 bytes`})}}async function cd(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=ud({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:_e.getSignPayload(o)}),c=B.from(s);if(c.type===`keychain`||c.type===`configurable`)throw new Y({reason:`keyAuthorization must use a primitive signature`});return _e.from(o,{signature:s})}function ld(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=dd(i.signature),s=fd(o);if(pd({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==sd(n))throw new Y({reason:`keyAuthorization challenge mismatch`});return md(o,a),gd(hd(o),a),_d(o.scopes,a),{authorization:o,source:{address:vd(o,s),chainId:r}}}function ud(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return _e.from({address:yd(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:rd(nd(i.subscriptionExpires)),limits:[{token:yd(i.currency,`currency`),limit:BigInt(i.amount),period:id(i)}],scopes:od(i),type:t.keyType,witness:sd(n)})}function dd(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 fd(e){let t=e.signature;if(!t)throw new Y({reason:`keyAuthorization must use a primitive signature`});return t}function pd(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,yd(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 md(e,t){if(ad({request:t}),e.expiry!==rd(nd(t.subscriptionExpires)))throw new Y({reason:`keyAuthorization expiry mismatch`})}function hd(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 gd(e,t){if(!f(e.token,yd(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!==id(t))throw new Y({reason:`keyAuthorization period mismatch`})}function _d(e,t){if(!e||e.length!==1)throw new Y({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=yd(t.currency,`currency`),r=yd(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=bd(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 vd(e,t){let n=_e.getSignPayload(e);try{let e=B.extractAddress({payload:n,signature:t});if(!B.verify(t,{address:e,payload:n}))throw new Y({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof Y?e:new Y({reason:`keyAuthorization signature is invalid`})}}function yd(e,t){if(!d(e))throw new Y({reason:`${t} must be an address`});return e.toLowerCase()}function bd(e){return typeof e==`string`?e.toLowerCase():``}const xd=U.object({accessKey:U.optional(U.custom()),account:U.optional(U.custom())});function Sd(e={}){let t=Ua({chain:R,getClient:e.getClient,rpcUrl:or}),n=za({account:e.account});return Jt(es,{context:xd,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??X.testnet,o=await t({chainId:a}),s=n(o,i),c=i?.accessKey??e.accessKey??r.request.methodDetails?.accessKey;if(!c)throw Error("No `accessKey` provided. The subscription challenge must include `accessKey`, or the client must pass one to parameters/context.");wd(r.request),await e.validateRequest?.(r.request);let l=await Cd(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=ld({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 It({challenge:r,payload:{signature:_e.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function Cd(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await cd({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:rd(nd(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:A.fromNumber(BigInt(o.amount)),period:id(o)}],scopes:od(o),witness:sd(i)}]});return _e.fromRpc(c.keyAuthorization)}function wd(e){id(e),rd(nd(e.subscriptionExpires))}const Td=Object.assign(Hu,{manager:$u});function Ed(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[ns(e),Td(n)]}(function(e){e.charge=ns,e.common=Ed,e.session=Td,e.subscription=Sd})(Ed||={});const Dd=L.union([L.boolean(),L.literal(`true`).transform(()=>!0),L.literal(`false`).transform(()=>!1)]);async function Od(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}const kd=L.object({allowCustomEscrow:L.optional(Dd),autoSwap:L.optional(Dd),channel:L.optional(L.coerce.string()),deposit:L.optional(L.union([L.string(),L.number()])),payWith:L.optional(L.string()),slippage:L.optional(L.coerce.number()),tokenIn:L.optional(L.string())}),Ad=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`];function jd(){let t;return Er({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:n,options:r,methodOpts:i}){let a=Sr(r.account),o=n.request,s=o.currency,c=Ld(i),l=Vd({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()||(cr(a)?void 0:await Cr(a).get());if(!_&&cr(a)&&Xd()){g=!0;let t=Jd(a);if(t){let i=dr(r.rpcUrl,{network:r.network});h=e({chain:await fr({network:r.network,rpcUrl:i}),transport:u(i)}),zd({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let a=s?await hr(h,s,t.wallet_address).catch(()=>void 0):void 0;d=a?.symbol??s??``,f=a?.decimals??o.decimals??6}}else if(_)m=he(_);else{let e=Qd();if(e){let t=await Cr(e).get();t&&(m=he(t))}if(!m)throw r.account?new tr({code:`ACCOUNT_NOT_FOUND`,message:`Account "${a}" not found.`,exitCode:69}):new tr({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 fr({network:r.network,rpcUrl:t}),transport:u(t)}),zd({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let i=s?await hr(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 Zd(t)}};if(!m||!h)throw new tr({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let v=Ed({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??(mr(h.chain)?`10`:void 0);if(!t)throw new tr({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=Ud(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 $s(h,m,c,i,a);return It({challenge:n,payload:{action:o,channelId:e,...o===`close`?{closeSignature:await ec(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=Mt(r),g=n.request,_=g.methodDetails,v=h.payload.channelId,y=_?.escrowContract??_?.escrow??`0x4d50500000000000000000000000000000000000`,b=_?.chainId??0,x=BigInt(g.amount),S=`cumulativeAmount`in h.payload&&h.payload.cumulativeAmount?BigInt(h.payload.cumulativeAmount):0n;if(`descriptor`in h.payload&&(t.descriptor=h.payload.descriptor),s>=1){if(h.payload.action===`open`){let e=g.suggestedDeposit,t=e?` ${Z.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
13
13
  `}${Z.dim(`Channel opened ${h.payload.channelId}`)}${t}\n`)}else m(`${l?``:`
14
- `}${Z.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let C=i;C.ok&&!C.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let w=C.headers.get(V.paymentReceipt);if(w)try{let e=JSON.parse(D.toString(w));Ed(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&Ld(v,S),s>=1&&Td(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 Dd(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 xd(C),v&&y&&b&&(l&&m(`
16
- `),l&&!await e.confirm(`Close channel?`,!0)?s>=1&&m(`${Z.dim(`Kept channel open.`)}\n`):await Od({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 Td(e,t){t.info(`${t.prefix??``}${Z.bold(Z.green(`Payment Receipt`))}\n`);let n=[],r=e.channelId&&e.reference&&e.channelId===e.reference,i=new Set([`acceptedCumulative`,`spent`]);for(let[a,o]of Object.entries(e)){if(o===void 0||t.shownKeys.has(a)||a===`reference`&&r)continue;let e=t.handler.formatReceiptField?.(a,o);e===void 0?i.has(a)&&typeof o==`string`?n.push([a,`${o} ${Z.dim(`(${sr(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,ar(`${t.explorerUrl}/tx/${o}`,o)]):n.push([a,String(o)]):n.push([a,e])}n.sort(([e],[t])=>e.localeCompare(t));let a=Math.max(...n.map(([e])=>e.length));for(let[e,r]of n)t.info(` ${Z.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
17
- `)}function Ed(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 Dd(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 kd():void 0,c=(()=>{if(!s||!Z.isColorSupported)return;let e=e=>Math.max(0,Math.min(255,Math.round(e))),t=.299*s.r+.587*s.g+.114*s.b<128?1:-1,n=n=>r=>`\x1b[48;2;${e(s.r+n*t)};${e(s.g+n*t)};${e(s.b+n*t)}m${r}\x1b[49m`;return[n(12),n(24)]})(),l=0,u=e=>{if(c){let t=c[l%c.length];process.stdout.write(e.replace(/[^\n]+/g,e=>t(e))),l++}else process.stdout.write(e)},d=async e=>{for(let r of e){if(r.startsWith(`event: `)){o=r.slice(7).trim();continue}if(!r.startsWith(`data: `)){r===``&&(o=``);continue}let e=r.slice(6);if(e.trim()!==`[DONE]`){if(o===`payment-need-voucher`&&t.channelId&&t.escrowContract&&t.chainId){try{let r=JSON.parse(e);if(r.channelId!==t.channelId)throw Error(`payment-need-voucher channelId does not match current session`);let i=BigInt(r.requiredCumulative);if(i>n+t.tickCost)throw Error(`payment-need-voucher exceeds next locally billable amount`);n=n>i?n:i;let a=await t.session.signVoucher({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId});await globalThis.fetch(t.fetchUrl,{method:`POST`,headers:{[V.authorization]:a}})}catch(e){t.info(Z.dim(Z.yellow(` [voucher failed: ${e instanceof Error?e.message:e}]`)))}o=``;continue}if(o===`payment-receipt`){if(t.verbose>=1)try{Td(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
14
+ `}${Z.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let C=i;C.ok&&!C.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let w=C.headers.get(V.paymentReceipt);if(w)try{let e=JSON.parse(D.toString(w));Nd(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&Wd(v,S),s>=1&&Md(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 Pd(C,{challenge:n,channelId:v,escrowContract:y,chainId:b,cumulativeAmount:S,tickCost:x,fetchUrl:a,fetchInit:o,session:t,info:m,verbose:s,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this}):(await Od(C),v&&y&&b&&(l&&m(`
16
+ `),l&&!await e.confirm(`Close channel?`,!0)?s>=1&&m(`${Z.dim(`Kept channel open.`)}\n`):await Fd({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 Md(e,t){t.info(`${t.prefix??``}${Z.bold(Z.green(`Payment Receipt`))}\n`);let n=[],r=e.channelId&&e.reference&&e.channelId===e.reference,i=new Set([`acceptedCumulative`,`spent`]);for(let[a,o]of Object.entries(e)){if(o===void 0||t.shownKeys.has(a)||a===`reference`&&r)continue;let e=t.handler.formatReceiptField?.(a,o);e===void 0?i.has(a)&&typeof o==`string`?n.push([a,`${o} ${Z.dim(`(${lr(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,sr(`${t.explorerUrl}/tx/${o}`,o)]):n.push([a,String(o)]):n.push([a,e])}n.sort(([e],[t])=>e.localeCompare(t));let a=Math.max(...n.map(([e])=>e.length));for(let[e,r]of n)t.info(` ${Z.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
17
+ `)}function Nd(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 Pd(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 Id():void 0,c=(()=>{if(!s||!Z.isColorSupported)return;let e=e=>Math.max(0,Math.min(255,Math.round(e))),t=.299*s.r+.587*s.g+.114*s.b<128?1:-1,n=n=>r=>`\x1b[48;2;${e(s.r+n*t)};${e(s.g+n*t)};${e(s.b+n*t)}m${r}\x1b[49m`;return[n(12),n(24)]})(),l=0,u=e=>{if(c){let t=c[l%c.length];process.stdout.write(e.replace(/[^\n]+/g,e=>t(e))),l++}else process.stdout.write(e)},d=async e=>{for(let r of e){if(r.startsWith(`event: `)){o=r.slice(7).trim();continue}if(!r.startsWith(`data: `)){r===``&&(o=``);continue}let e=r.slice(6);if(e.trim()!==`[DONE]`){if(o===`payment-need-voucher`&&t.channelId&&t.escrowContract&&t.chainId){try{let r=JSON.parse(e);if(r.channelId!==t.channelId)throw Error(`payment-need-voucher channelId does not match current session`);let i=BigInt(r.requiredCumulative);if(i>n+t.tickCost)throw Error(`payment-need-voucher exceeds next locally billable amount`);n=n>i?n:i;let a=await t.session.signVoucher({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId});await globalThis.fetch(t.fetchUrl,{method:`POST`,headers:{[V.authorization]:a}})}catch(e){t.info(Z.dim(Z.yellow(` [voucher failed: ${e instanceof Error?e.message:e}]`)))}o=``;continue}if(o===`payment-receipt`){if(t.verbose>=1)try{Md(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 Od({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 Od(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:{...ta(e.fetchInit.headers),Authorization:t}});if(n.ok){if(Rd(e.channelId),e.verbose>=1){let t=n.headers.get(V.paymentReceipt),r;if(t)try{let e=JSON.parse(D.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${Z.dim(ar(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${Z.dim(`Channel closed.`)} ${Z.dim(`Spent ${sr(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${Z.dim(Z.yellow(`Channel close failed`))} ${Z.dim(`(${n.status})`)}\n`),e.info(`${Z.dim(` channelId: ${e.channelId}`)}\n${Z.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${Z.dim(` escrowContract: ${e.escrowContract}`)}\n${Z.dim(` chainId: ${e.chainId}`)}\n${Z.dim(` response: ${t||`(empty)`}`)}\n`)}}function kd(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 Ad(e){return jd(Sd,e,Cd)}function jd(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 Md(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 $n({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function Nd(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function Pd(e){let t=Nd(e.tokenIn)??Nd(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 Fd(){return I.join(process.env.XDG_CONFIG_HOME||I.join(F.homedir(),`.config`),`mppx`,`channels`)}function Id(e){try{let t=P.readFileSync(I.join(Fd(),e),`utf-8`).trim();return t?BigInt(t):void 0}catch{return}}function Ld(e,t){let n=Fd();P.mkdirSync(n,{recursive:!0}),P.writeFileSync(I.join(n,e),t.toString(),`utf-8`)}function Rd(e){try{P.unlinkSync(I.join(Fd(),e))}catch{}}function zd(){return F.platform()===`darwin`?I.join(F.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):I.join(process.env.XDG_DATA_HOME||I.join(F.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function Bd(){try{let e=P.readFileSync(zd(),`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 Vd(e){let t=Bd();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 Hd;function Ud(){if(Hd!==void 0)return Hd;try{N.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),Hd=!0}catch{Hd=!1}return Hd}async function Wd(e){return new Promise((t,n)=>{N.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function Gd(){let e=yr();if(or(e.get())&&!Ud()&&F.platform()===`darwin`)try{let t=N.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===`mppx`&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}const Kd=[...Object.entries(Me),...Object.entries(Ne),...Object.entries(Pe),...Object.entries(Fe)];function qd(){return wr({method:`evm`,supports:Jd,async setup({challenge:e,options:t}){let n=e.request,r=n.network?Yd(He(n.network)):void 0,i=n.network&&n.asset?Kd.find(([,e])=>Be(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 Cr(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...Zn({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function Jd(e){if(!Pn(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 Yd(e){return Object.values(te).find(t=>t.id===e)}export{wr as createPlugin,Tr as evm,Pr as stripe,wd as tempo,qd as x402};
21
+ `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await Fd({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 Fd(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:{...ra(e.fetchInit.headers),Authorization:t}});if(n.ok){if(Gd(e.channelId),e.verbose>=1){let t=n.headers.get(V.paymentReceipt),r;if(t)try{let e=JSON.parse(D.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${Z.dim(sr(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${Z.dim(`Channel closed.`)} ${Z.dim(`Spent ${lr(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${Z.dim(Z.yellow(`Channel close failed`))} ${Z.dim(`(${n.status})`)}\n`),e.info(`${Z.dim(` channelId: ${e.channelId}`)}\n${Z.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${Z.dim(` escrowContract: ${e.escrowContract}`)}\n${Z.dim(` chainId: ${e.chainId}`)}\n${Z.dim(` response: ${t||`(empty)`}`)}\n`)}}function Id(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 Ld(e){return Rd(kd,e,Ad)}function Rd(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 zd(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 tr({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function Bd(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function Vd(e){let t=Bd(e.tokenIn)??Bd(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 Hd(){return I.join(process.env.XDG_CONFIG_HOME||I.join(F.homedir(),`.config`),`mppx`,`channels`)}function Ud(e){try{let t=P.readFileSync(I.join(Hd(),e),`utf-8`).trim();return t?BigInt(t):void 0}catch{return}}function Wd(e,t){let n=Hd();P.mkdirSync(n,{recursive:!0}),P.writeFileSync(I.join(n,e),t.toString(),`utf-8`)}function Gd(e){try{P.unlinkSync(I.join(Hd(),e))}catch{}}function Kd(){return F.platform()===`darwin`?I.join(F.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):I.join(process.env.XDG_DATA_HOME||I.join(F.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function qd(){try{let e=P.readFileSync(Kd(),`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 Jd(e){let t=qd();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 Yd;function Xd(){if(Yd!==void 0)return Yd;try{N.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),Yd=!0}catch{Yd=!1}return Yd}async function Zd(e){return new Promise((t,n)=>{N.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function Qd(){let e=xr();if(cr(e.get())&&!Xd()&&F.platform()===`darwin`)try{let t=N.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===`mppx`&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}const $d=[...Object.entries(Ne),...Object.entries(Pe),...Object.entries(Fe),...Object.entries(Ie)];function ef(){return Er({method:`evm`,supports:tf,async setup({challenge:e,options:t}){let n=e.request,r=n.network?nf(Ue(n.network)):void 0,i=n.network&&n.asset?$d.find(([,e])=>Ve(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 Tr(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...$n({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function tf(e){if(!In(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 nf(e){return Object.values(ne).find(t=>t.id===e)}export{Er as createPlugin,Dr as evm,Ir as stripe,jd as tempo,ef as x402};