mppx 0.18.1 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/dist/Errors.d.ts +11 -4
- package/dist/Errors.js +13 -4
- package/dist/cli/cli.js +25 -25
- package/dist/cli/plugins/index.js +12 -12
- package/dist/extensions/identity/Types.d.ts +26 -0
- package/dist/extensions/identity/attestation/Token.d.ts +6 -4
- package/dist/extensions/identity/attestation/Token.js +11 -5
- package/dist/extensions/identity/index.d.ts +2 -0
- package/dist/extensions/identity/index.js +2 -0
- package/dist/extensions/identity/internal/HttpMessageSignature.d.ts +2 -2
- package/dist/extensions/identity/internal/HttpMessageSignature.js +13 -10
- package/dist/extensions/identity/{web-bot-auth/internal → internal}/JwkThumbprint.js +1 -1
- package/dist/extensions/identity/internal/Signer.d.ts +20 -0
- package/dist/extensions/identity/internal/Signer.js +94 -0
- package/dist/extensions/identity/tap/client/index.d.ts +6 -2
- package/dist/extensions/identity/tap/client/index.js +2 -0
- package/dist/extensions/identity/tempo/Constants.d.ts +14 -0
- package/dist/extensions/identity/tempo/Constants.js +14 -0
- package/dist/extensions/identity/tempo/Types.d.ts +31 -0
- package/dist/extensions/identity/tempo/Types.js +2 -0
- package/dist/extensions/identity/tempo/client/index.d.ts +34 -0
- package/dist/extensions/identity/tempo/client/index.js +60 -0
- package/dist/extensions/identity/tempo/index.d.ts +5 -0
- package/dist/extensions/identity/tempo/index.js +4 -0
- package/dist/extensions/identity/tempo/internal/Jwt.d.ts +36 -0
- package/dist/extensions/identity/tempo/internal/Jwt.js +114 -0
- package/dist/extensions/identity/tempo/server/index.d.ts +65 -0
- package/dist/extensions/identity/tempo/server/index.js +247 -0
- package/dist/extensions/identity/web-bot-auth/client/index.d.ts +6 -4
- package/dist/extensions/identity/web-bot-auth/client/index.js +7 -5
- package/dist/extensions/identity/web-bot-auth/server/index.js +1 -1
- package/dist/extensions/identity/world/Constants.d.ts +50 -0
- package/dist/extensions/identity/world/Constants.js +50 -0
- package/dist/extensions/identity/world/Types.d.ts +52 -0
- package/dist/extensions/identity/world/Types.js +2 -0
- package/dist/extensions/identity/world/client/index.d.ts +103 -0
- package/dist/extensions/identity/world/client/index.js +208 -0
- package/dist/extensions/identity/world/index.d.ts +6 -0
- package/dist/extensions/identity/world/index.js +5 -0
- package/dist/extensions/identity/world/internal/Idp.d.ts +50 -0
- package/dist/extensions/identity/world/internal/Idp.js +265 -0
- package/dist/extensions/identity/world/issuer/index.d.ts +120 -0
- package/dist/extensions/identity/world/issuer/index.js +520 -0
- package/dist/extensions/identity/world/server/index.d.ts +49 -0
- package/dist/extensions/identity/world/server/index.js +63 -0
- package/dist/identity/Headers.d.ts +1 -1
- package/dist/identity/Headers.js +6 -1
- package/dist/identity/Types.d.ts +5 -0
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- package/dist/server/Mppx.js +2 -1
- package/dist/tempo/client/Charge.js +32 -12
- package/dist/tempo/internal/zone.d.ts +27 -0
- package/dist/tempo/internal/zone.js +54 -7
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/package.json +9 -1
- /package/dist/extensions/identity/{web-bot-auth/internal → internal}/JwkThumbprint.d.ts +0 -0
|
@@ -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 ee,sendRawTransactionSync as x,sendTransactionSync as S,signTransaction as C,signTypedData as te,waitForTransactionReceipt as w}from"viem/actions";import*as T 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;zoneId;constructor(e){let{cause:t,challengeId:n,senderTag:r,zoneId:i}=e;super(`Zone ${i} withdrawal ${r} for challenge "${n}" has not settled on Tempo yet. Retry the challenge to resume waiting instead of paying again.`),this.challengeId=n,this.senderTag=r,this.zoneId=i,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}},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(T).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,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+`
|
|
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),ee=await m(Ta(b.input),b.init),x=ee.response,S=ee.headers,C=xa(b.init,await y);if(t?.[Yi]||ui(C)||!await c.isPaymentRequired(x,C))return x;let te=t?.context,{context:w,orderChallenges:T,...ne}=C??{},E,D,O,k,A;try{for(let n=0;n<i;n++){D=await c.getChallenges(x,C);let i=(await Aa(Kr(D,a,v.entries,te),T??s))[0];if(!i){if(await $i(k,{challenges:D,response:x,status:`rejected`}),n>0)return x;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(x,{challenge:f},Pa(b.input).href);let g=await Ia(x,b.input,b.input,ne);Wi(f,()=>Pa(g),l);let _=k,y=ft(f),ee=_?.method===i.method&&_?.key===y,w=!1;if(_){let e=await $i(_,{challenges:D,response:x,status:ee?`pending`:`rejected`});w=ee&&!e}k=w?_:void 0;let j=sa(async n=>{if(n===void 0&&w&&_)return _.promise;w&&_&&(await $i(_,{status:`rejected`}),k=void 0),Ea(e,t)?.throwIfAborted();let r=n??te;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:x}))??(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:te;Da(M),await d.emit(`credential.created`,la({challenge:f,credential:M,init:t,input:e,method:i.method,response:x}));let F=e=>new Vt({cause:e,challenge:f,credential:M,transactionHash:Vi(i.method,M)});try{({response:x}=await m(g,{...c.setCredential({...ne,headers:b.headers},M,{challenge:f}),redirect:`manual`},{challenge:f,headers:S}))}catch(e){throw A=F(e),e}let I=await c.isPaymentRequired(x,C);if(I||(await $i(N,{response:x,status:x.status>=300&&x.status<400?`pending`:x.ok?`accepted`:`rejected`}),k=void 0),x.ok&&ra(d,`payment.response`)&&await d.emit(`payment.response`,ua({challenge:f,credential:M,init:t,input:e,method:i.method,response:x})),!I){if(x.status>=500&&ra(d,`payment.failed`)){try{x=await Qi(x)}catch(e){throw A=F(e),x=new Response(null,{headers:x.headers,status:x.status,statusText:x.statusText}),e}await d.emit(`payment.failed`,da({challenge:f,challenges:D,error:F(),init:t,input:e,method:i.method,response:x}))}return x.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:x,signal:Ea(e,t)}):x}}D=void 0;try{D=await c.getChallenges(x,C)}catch{}return await $i(k,{challenges:D,response:x,status:`rejected`}),x}catch(n){throw await $i(k,{challenges:D,response:x,status:`rejected`}),await d.emit(`payment.failed`,da({challenge:E,challenges:D,error:A??n,init:t,input:e,method:O,response:x})),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=o({abi:se.zonePortal,name:`WithdrawalProcessed`});function wo(e){return Number.isInteger(e)&&e>0&&e<4217e5}function To(e,t){return wo(t)?e===!0||(e?.includes(t)??!1):!1}function Eo(e){return le.zonePortal(e)}function Do(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 Oo(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 ko(e){return k.keccak256(E.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function Ao(e,t){let{timeoutMs:n=6e4}=t;if(!Number.isFinite(n)||n<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);let r=await _(e,{cacheTime:0}),i=r>So?r-So:0n,a=Date.now()+n;for(;;){if(i<=r){let n=(await v(e,{address:t.portal,event:Co,args:{senderTag:t.senderTag,...t.to?{to:t.to}:{}},fromBlock:i,toBlock:r}))[0]?.transactionHash;if(n)return n;i=r+1n}if(Date.now()+500>a)throw Error(`Zone withdrawal ${t.senderTag} did not settle on Tempo within ${n}ms.`);await new Promise(e=>setTimeout(e,500)),r=await _(e,{cacheTime:0})}}const jo=[`push`,`pull`],Mo=U.object({amount:W(),memo:U.optional(K()),recipient:U.pipe(U.string(),U.transform(e=>e))}),No=(1n<<64n)-1n,Po={dev_second:1n,day:86400n,week:604800n},Fo=U.pipe(G(),U.transform(e=>e.toLowerCase())),Io=U.object({accessKeyAddress:Fo,keyType:U.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:U.optional(U.pipe(U.string().check(U.regex(/^0x[0-9a-fA-F]{120}$/)),U.transform(e=>e)))}),Lo=U.object({accessKey:U.optional(Io),chainId:U.optional(U.number())}),Ro=at(`subscriptionExpires must be a valid date`).check(U.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),zo=U.enum([`dev_second`,`day`,`week`]),Bo=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)<=No}catch{return!1}},`periodCount exceeds uint64`));function Vo(e){return U.refine(e=>{let{amount:t,decimals:n}=e;return h(t,n)>0n},e)}function Ho(e){let{periodCount:t,periodUnit:n}=e;try{let e=Po[n];return e!==void 0&&BigInt(t)*e<=No}catch{return!1}}const Uo=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(wo,`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(Mo).check(U.minLength(1),U.maxLength(10))),supportedModes:U.optional(U.array(U.enum(jo)).check(U.minLength(1))),zones:U.optional(U.union([U.literal(!0),U.array(U.number().check(U.refine(wo,`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}}}:{}})))}}),Wo=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}}})))}}),Go=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(Io),chainId:U.optional(U.number()),currency:Fo,decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),methodDetails:U.optional(Lo),periodCount:Bo,periodUnit:zo,recipient:Fo,subscriptionExpires:Ro}).check(Vo(`Subscription amount must be greater than 0`),U.refine(Ho,`Subscription period exceeds uint64`)),U.transform(({accessKey:e,amount:t,chainId:n,decimals:r,methodDetails:i,subscriptionExpires:a,...o})=>{let s={...i,...e!==void 0&&{accessKey:e},...n!==void 0&&{chainId:n}};return{...o,amount:h(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}}),Ko=U.object({account:U.optional(U.custom()),autoSwap:U.optional(U.custom()),feeToken:U.optional(U.custom()),mode:U.optional(U.enum(jo))});function qo(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??[])ns(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});Zo(e.zone);let a=new Map,o=Kt(Uo,{canHandleChallenge({challenge:t}){try{return rs(e,n,t.request),!0}catch{return!1}},context:Ko,async createCredential({challenge:o,context:s}){rs(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&&rs(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??Do(g?.id??0):void 0,v=g?.sourceId??(g?Oo(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`)&&To(m?.zones,_)&&!m?.splits&&(a.has(es(o))||Qo(o.expires,e.zone.settlementTimeoutMs)))return Xo({challenge:o,clientId:t,client:u,pending:a,zone:e.zone,zoneId:_});let x=i(u,s),w=async t=>await e.resolveAccount?.({account:x,chainId:d,operation:t})??x;if(BigInt(p)===0n){let e=await w({kind:`signPaymentProof`});return Ft({challenge:o,payload:{signature:await te(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 T=f.currency,ne=co({chainId:d,currency:T}),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:T})),k=Qa(s?.autoSwap??e.autoSwap,Xa),A=m?.machineTokenEnabled===!0?lo({chainId:d,currency:T,transfers:D}):void 0,j=x,M,N=!1;if(A){let e=await(async()=>{try{return await w({calls:A.calls,kind:`executeCalls`})}catch{return}})();e&&(M=await uo(u,{account:e.address,chainId:d,currency:T,transfers:D}),M?j=e:N=!0)}let P;if(!M&&(j=await w({kind:`executeCalls`,...k?{}:{calls:O}}),P=k?await Za(u,{account:j.address,amountOut:BigInt(p),tokenOut:T,tokenIn:k.tokenIn,slippage:k.slippage,maxAmountIn:k.maxAmountIn}):void 0,N&&!k)){let e=await Jo(u,{account:j.address,amount:BigInt(p),chainId:d,currency:T});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 S(u,{account:j,calls:F,...L?{feeToken:L}:{},nonceKey:`expiring`,validBefore:re})]}:await ee(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 C(u,ae),type:`transaction`},source:xo({address:j.address,chainId:d})})}}),s=new Map,c=async t=>{rs(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},Yo)}async function Jo(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 Yo(e){let t=Uo.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 Xo(e){let{challenge:t,client:n,pending:r,zone:i,zoneId:a}=e,o=t.request.recipient,s=es(t),c=r.get(s);if(!c){let t={sent:!1};c=ts(e,t),r.set(s,c),c.catch(()=>{t.sent||r.delete(s)})}let l=await c,u;try{u=await Ao(n,{portal:Eo(a),senderTag:l,timeoutMs:$o(t.expires,i.settlementTimeoutMs),to:o})}catch(e){throw new Ht({cause:e,challengeId:t.id,senderTag:l,zoneId:a})}return r.delete(s),Ft({challenge:t,payload:{hash:u,senderTag:l,type:`zone`,zoneId:a}})}function Zo(e){let t=e?.settlementTimeoutMs;if(t!==void 0&&(!Number.isFinite(t)||t<0))throw Error("`zone.settlementTimeoutMs` must be a finite, non-negative number.");let n=e?.client.chain?.id;if(e?.zoneId===void 0||n===void 0||Oo(n)===void 0)return;let r=Do(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function Qo(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+15e3}function $o(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function es(e){return JSON.stringify(e)}async function ts(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 C(i.client,h);t.sent=!0;let _=f(g),v=await x(i.client,{serializedTransaction:g}).catch(e=>w(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});if(!b)throw Error("Zone withdrawal request did not emit `WithdrawalRequested`.");return ko({fallbackNonce:b.args.fallbackNonce,sender:b.args.sender,transactionHash:v.transactionHash})}function ns(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 rs(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)>ns(t.maxAmount,c?.decimals))throw Error(`Tempo charge amount exceeds maxAmount.`)}const is=(1n<<96n)-1n;function as(e){return e>=0n&&e<=is}function os(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return as(t)?t:void 0}function ss(e){return cs(e),e}function cs(e){if(!as(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const ls=new Set([`open`,`topUp`,`voucher`,`close`]);function us(e){return typeof e==`object`&&!!e}function ds(e){return typeof e==`string`&&ls.has(e)}function fs(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!ds(t.action))}function ps(e,t=`No session credential context available.`){if(!fs(e))throw Error(t);return e}function ms(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function hs(e){return us(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function gs(e){return us(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 _s(e){let t=D.toString(e),n=JSON.parse(t);if(!gs(n))throw Error(`Invalid session receipt.`);return n}function vs(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function ys(e){let t=`message`,n=[];for(let r of e.split(`
|
|
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(`
|
|
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=bs(r);return hs(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=bs(r);return gs(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function bs(e){try{return JSON.parse(e)}catch{return null}}function xs(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function Ss(){return JSON.stringify({mpp:`payment-close-request`})}function Cs(e){let t=ws(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`&&gs(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`&&hs(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&gs(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function ws(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}const Ts=`0x4d50500000000000000000000000000000000000`;function Es(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function Ds(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 Os(e){return ve.encodeForSigning(e)}function ks(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function As(e,t){return k.keccak256(A.concat(Os(e),t.sender))}const js=[{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`}],Ms=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],Ns={name:`descriptor`,type:`tuple`,components:js},Ps=[{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:[Ns,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[Ns,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[Ns,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[Ns],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[Ns],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[Ns],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:js},{name:`state`,type:`tuple`,components:Ms}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:Ms}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:Ms}]},{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 Fs(e,t){return{name:`TIP20 Channel Reserve`,version:`1`,chainId:t,verifyingContract:e}}const Is={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},Ls={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]};function Rs(e,t,n){return c({domain:Fs(e,t),types:Ls,primaryType:`CloseAuthorization`,message:n})}function zs(e,t){return he.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function Bs(e,t,n){return e.toLowerCase()===he.address.toLowerCase()?zs(t,n):c({domain:Fs(e,t),types:Is,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function Vs(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function Hs(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function Us(e,t){return ce.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function Ws(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===he.address.toLowerCase())try{return await Us(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return te(e,{account:t,domain:Fs(r,i),types:Is,primaryType:`Voucher`,message:n})})(),o=B.from(a);if(!Vs(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return B.serialize(o)}async function Gs(e,t,n,r,i){let a=Hs(t)?await t.sign({hash:Rs(r,i,n),raw:!0}):await te(e,{account:t,domain:Fs(r,i),types:Ls,primaryType:`CloseAuthorization`,message:n}),o=B.from(a);if(!Vs(o.type))throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive signature; received "${o.type}".`);return B.serialize(o)}function Ks(e,t,n,r){try{let i=B.from(n.signature);if(!Vs(i.type)||B.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=Bs(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 qs(e){return typeof e==`object`&&!!e}function Js(e){return typeof e==`string`&&u(e,{strict:!1})?e:void 0}function Ys(e){return Js(e.accessKeyAddress)}function Xs(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(A.random(8))%e)}function Zs(e){return Ys(e)??e.address}async function Qs(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 $s(e,t){return await C(e,t)}function ec(e,t,n=!1){let r=e.request.methodDetails,i=qs(r)?Js(r.escrowContract)??Js(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!nc(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!nc(i,a)?i:a}function tc(e,t,n,r){return Ft({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function nc(e,t){return e.toLowerCase()===t.toLowerCase()}async function rc(e,t,n,r,i,a=Ts){let o=Ds({...n,chainId:i,escrow:a}),s=ss(r),c=await Ws(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function ic(e,t,n,r,i,a=Ts){let o=await rc(e,t,n,r,i,a),s=await Gs(e,t,{channelId:o.channelId,cumulativeAmount:ss(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function ac(e,t,n){let i=Zs(t),a=n.escrow??`0x4d50500000000000000000000000000000000000`,o=n.operator??`0x0000000000000000000000000000000000000000`,s=A.random(32),c=ss(n.deposit),l=ss(n.initialAmount),u=r({abi:Ps,functionName:`open`,args:[n.payee,o,n.token,c,s,i]}),d=await $s(e,await Qs(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:As(ks({...n.feePayer?{feePayer:!0}:{},transaction:f}),{sender:t.address}),operator:o,payee:n.payee,payer:t.address,salt:s,token:n.token},m=Ds({...p,chainId:n.chainId,escrow:a});return{action:`open`,type:`transaction`,channelId:m,transaction:d,signature:await Ws(e,t,{channelId:m,cumulativeAmount:l},a,n.chainId),descriptor:p,cumulativeAmount:l.toString(),authorizedSigner:p.authorizedSigner}}async function oc(e,t,n,i,a,o,s=Ts,c=[],l=n.token){let u=Ds({...n,chainId:a,escrow:s}),d=ss(i);return{action:`topUp`,type:`transaction`,channelId:u,transaction:await $s(e,await Qs(e,{account:t,calls:[...c,{to:s,data:r({abi:Ps,functionName:`topUp`,args:[n,d]})}],feePayer:o,feeToken:l,validAfter:Xs()})),descriptor:n,additionalDeposit:d.toString()}}function sc(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Q(e){return sc({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function cc(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Q(t),t)},delete(t){e.delete(t)}}}const lc=new WeakMap,uc=new WeakMap;function dc(e,t){uc.set(e,uc.get(t)??t)}async function fc(e,t,n){let r=lc.get(e);r||(r=new Map,lc.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 pc(e,t,n){return fc(uc.get(e)??e,`funding:${t}`,n)}async function mc(e,t){await fc(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 hc(e,t){await fc(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}const gc=2n**96n-1n;function _c(e){if(e<0n||e>gc)throw new Y({reason:`amount exceeds uint96 range`})}async function vc(e,t,n=Ts,r){return yc(await b(e,{address:n,abi:Ps,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function yc(e){return _c(e.settled),_c(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}const bc=U.custom(e=>typeof e==`string`&&u(e,{strict:!1})),xc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),Sc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),Cc=U.object({authorizedSigner:bc,expiringNonceHash:xc,operator:bc,payee:bc,payer:bc,salt:xc,token:bc}),wc=qt(U.object({acceptedCumulative:U.string(),chainId:U.number(),channelId:xc,closeRequestedAt:U.optional(U.string()),deposit:U.string(),descriptor:Cc,escrow:bc,highestVoucher:U.optional(U.object({channelId:xc,cumulativeAmount:U.string(),signature:Sc})),requiredCumulative:U.string(),settled:U.string(),spent:U.string(),units:U.optional(U.number())}));function Tc(e){return wc.encode(e)}function Ec(e){return wc.decode(e)}const Dc={status:`idle`};function Oc(e){return{status:`active`,...e}}function kc(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:Mc(e.challengeId,t.snapshot),effects:[]}:$(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Gc({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:Nc(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:$(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Jc(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?jc({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:Nc(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:Nc(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 Ac(e,t){let n=kc(e.state,t);return e.state=n.state,n}function jc(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 Mc(e,t){return Oc({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function Nc(e,t,n,r){return Oc({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 Pc(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function Fc(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`);Pc({cumulativeAmount:i,maxVoucherCumulative:n}),Pc({cumulativeAmount:a,maxVoucherCumulative:n})}function Ic(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;Fc({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function Lc(e,t){return typeof e==`bigint`?e:h(e,t)}function Rc(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(Bc(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 zc(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;Pc({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 Bc(e,t){Pc({cumulativeAmount:e,maxVoucherCumulative:t??null})}function Vc(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 Hc(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function Uc(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!as(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>Hc({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function Wc(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=os(r),s=os(a.spent);return o===void 0||s===void 0||!as(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function Gc(e){return Oc({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 Kc(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:Dc}}function qc(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=Ic({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&Ac(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function Jc(e,t){return Oc({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function Yc(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=os(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 Xc(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 kc(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function Zc(e){return{channel:e.channel===null?null:{entry:e.channel,cumulativeAmount:e.channel.cumulativeAmount,deposit:e.channel.deposit,opened:e.channel.opened},spent:e.spent,state:e.state}}function Qc(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 $c(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(Ss()),e.waitForCloseReady()))(),a=BigInt(i.spent);Uc({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=>Wc({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(xs(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}function el(e){return`cumulativeAmount`in e}function tl(e){if(el(e))return BigInt(e.cumulativeAmount)}async function nl(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await mc(e.store,t):await hc(e.store,Q(t)),e.notifyUpdate(t)}async function rl(e,t,n){let r=tl(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 nl(e,i))}const il=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),al=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),ol=U.object({account:U.optional(U.custom()),autoSwap:U.optional(U.custom()),action:U.optional(U.enum([`open`,`topUp`,`voucher`,`close`])),channelId:U.optional(al),cumulativeAmount:U.optional(W()),cumulativeAmountRaw:U.optional(U.string()),transaction:U.optional(il),descriptor:U.optional(U.custom()),additionalDeposit:U.optional(W()),additionalDepositRaw:U.optional(U.string()),depositRaw:U.optional(U.string())});function sl(e){return e?.action!==void 0}function cl(e){return sl(e)&&e.descriptor!==void 0}function ll(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 ul(e,t,n,r){let i=ll(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function dl(e){return typeof e==`object`&&!!e}function fl(e){return typeof e==`string`&&u(e,{strict:!1})?e:void 0}function pl(e){let t=e.request.methodDetails;return dl(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:fl(t.escrowContract),escrow:fl(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:fl(t.feeToken),operator:fl(t.operator),sessionSnapshot:tt(t,$e.sessionSnapshot)}:{}}function ml(e,t){if(typeof e==`string`&&u(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function hl(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function gl(e){return typeof e==`string`?e:void 0}async function _l(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=pl(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=ec(n,r,t),d=ml(n.request.recipient,`recipient`),f=ml(n.request.currency,`currency`);return{amount:hl(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:sc({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:gl(n.request.suggestedDeposit),token:f}}async function vl(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=vc}=e,o=Ds({...r,chainId:i.chainId,escrow:i.escrow});yl({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 yl(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(!nc(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!nc(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!nc(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!nc(Es(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function bl(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function xl(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=ll(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function Sl(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(!Ks(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},Es(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await vl({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:Zs(t),token:i.descriptor.token},readChannelState:r}),p=[o,c,f.state.settled].reduce((e,t)=>t>e?t:e,0n);if(p>f.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:f.channelId,cumulativeAmount:p,deposit:f.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:d}}function Cl(e,t){return nc(e.address,t.payer)?nc(Zs(e),Es(t)):!1}function wl(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(sl(r)){if(!cl(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=bl({context:r,snapshot:o.snapshot});return!n&&s&&Cl(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&Cl(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 Tl(e,t,n=!1){switch(e.type){case`open`:return Ol(e,t,n);case`recover`:return kl(e,t);case`voucher`:return Al(e,t);case`manual`:return jl(e,t,n)}}async function El(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 Dl(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 Ol(e,t,n){let{account:r,resolved:i}=e,a=Rc({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw});await Dl(n,{account:r.address,amount:a,chainId:i.chainId,client:i.client,token:i.token});let o=await ac(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 El(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await nl(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function kl(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await vl({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:Zs(n),token:o.token}}),l=xl({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`);Bc(l,a);let u=await rc(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await nl(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 Al(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;Bc(a,e.maxDeposit);let o=await rc(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await nl(t,r),o}async function jl(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=Ds({...s,chainId:o.chainId,escrow:o.escrow});yl({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:Zs(r),token:o.token});let l=await Ml({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await rl(t,o.key,l),l}async function Ml(e,t){switch(e.context.action){case`open`:return Nl(e);case`topUp`:return Pl(e,t);case`voucher`:return Fl(e);case`close`:return Il(e)}}async function Nl(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=ul(r,i,`cumulativeAmount`,`open`),c=await rc(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 Pl(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=ul(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:(await Dl(t,{account:n.address,amount:c,chainId:s.chainId,client:s.client,token:s.token}),oc(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await El(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken))}function Fl(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return rc(a.client,t,i,ul(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function Il(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return ic(a.client,t,i,ul(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}const Ll={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function Rl(e){let t=new Map,n=!1,r=[],i=e.readyState,a=(e,n,i)=>{let a=t.get(e);if(a||(a=new Set,t.set(e,a)),a.add({once:typeof i==`object`&&i.once===!0,value:n}),e===`message`&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},o=(e,n)=>{let r=t.get(e);if(r)for(let e of r)e.value===n&&r.delete(e)};function s(e,a){if(a.type===`close`){if(n)return;n=!0,i=Ll.CLOSED,r=null}if(a.type===`open`&&(i=Ll.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 zl(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function Bl(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=Lc(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 Vl(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:Jc(s,u)}:i?{channel:u,state:Gc({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function Hl(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=zl(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:ss(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function Ul(e){return e.method===Ze.tempo&&e.intent===Qe.session}function Wl(e){return Ul(e)&&tt(e.request.methodDetails,$e.sessionProtocol)===et.v2}function Gl(e){return tt(e.request.methodDetails,$e.sessionSnapshot)}function Kl(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 ql(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 Jl(e){try{let t=typeof location>`u`?void 0:location.href,n=ql(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function Yl(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function Xl(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 Zl=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 Ql(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 $l({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 Zl&&(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?_s(i):void 0}async function $l(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(Jl(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:Cu(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new Zl(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(Wl);return r?t(r):n}async function eu(e){let t=tu({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,Kl(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(V.paymentReceipt)&&await l(),u}function tu(e){let t=xt(e.response).find(Wl);if(!t)return;let n=Gl(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function nu(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=ql(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?Jl(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:Cu(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=xt(o).find(Wl);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await Xl(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=_s(s);if(!c.txHash||!A.validate(c.txHash,{strict:!0})||A.size(c.txHash)!==32||!Wc({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 ru(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!vs(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),iu(e,c,{onReceipt:r,signal:o},n,s.headers)}function iu(e,t,n,r,i){if(!vs(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return au({onNeedVoucher:t=>uu({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*au(e){for await(let t of ou(e))t.data!==void 0&&(yield t.data)}async function*ou(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=su(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=ys(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
|
|
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]===`
|
|
11
11
|
`?1:e[t]===`\r`?e[t+1]===`
|
|
12
|
-
`?2:t+1===e.length&&!n?0:1:0}function lu(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=ou({...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 uu(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await Hl({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 $l({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 du(e){let t=new URL(e.input.toString()),n=Yl(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(Wl);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 fu(e){e.signal?.throwIfAborted();let t=await du(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function pu(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:ms(t)}}function mu(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function hu(e){if(!mu(e))return`received mismatched payment-close-ready frame`;let t=os(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 gu(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!mu(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!Wc({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function _u(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=pu({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=Rl(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===Ll.CONNECTING||s.readyState===Ll.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 yu({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await vu(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(xs(n)),await e.waitForReceipt(),l.socket}function vu(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 yu(e){let t=Cs(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`:bu(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 xu(e,t.data);return;case`payment-receipt`:Su(e,t.data);return}}function bu(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=hu({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 xu(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 Hl({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(xs(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function Su(e,t){let n=gu({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 Cu(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 wu=new WeakMap;async function Tu(e,t){let n=wu.get(e)??new Map;wu.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 Eu(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function Du(e,t,n){try{let r=e.response?.headers.get(V.paymentReceipt);if(r){let e=_s(r);if(e.challengeId===t.id&&Eu(n,e))return!0}}catch{}return e.challenges?.some(e=>Wl(e)?Eu(n,Gl(e)):!1)??!1}function Ou(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??[])ku(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 ku(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 Au(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>ku(e.maxAmount,r?.decimals))throw Error(`Tempo session amount exceeds maxAmount.`)}function ju(e,t){try{return Au(e,t),!0}catch{return!1}}function Mu(e){return typeof e==`object`&&!!e&&e.action===`close`}function Nu(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=Ou(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??cc(),b={store:y,notifyUpdate:e=>d?.(e)},ee=async(e,t,n)=>{let r=g(e.client,t),i=t?.action?t.descriptor:n?.descriptor??bl({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:Es(i)}:{}}})??r},x=async(e,t,n)=>{let{decimals:r,maxDeposit:i}=_(e.challenge.request,e.chainId);return wl({account:await ee(e,t,n),entry:n,context:t,decimals:r,maxDeposit:i,resolved:e})},S=Kt(Wo,{canHandleChallenge:({challenge:e,context:t})=>Wl(e)&&(Mu(t)||t===Vr||ju(p,e.request)),context:ol,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&Au(p,t.request);let a=await _l({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m});i?.action!==`close`&&t.request.methodDetails?.chainId===void 0&&Au(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=!sl(i)&&i?.descriptor===void 0;e&&(d=await Tu(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 x(a,i,n);if(!e&&c&&o.type===`open`){d=await Tu(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 x(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 tc(t,await Tl(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`||Du(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 mc(y,e),b.notifyUpdate(e))}return!0}finally{d()}}}else d();return p}catch(e){throw d(),e}}});function C(e,t,n){let r={challenge:e,context:t};return Hi(r,Pu(n)),S.createCredential(r)}let te=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>pc(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=zc({deposit:l,maxDeposit:u,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:d});f>0n&&await Ql({autoSwap:e,additionalDeposit:f,challenge:t,channel:n,channelId:n.channelId,createSessionCredential:(e,t)=>C(e,t,a),onUncertainFunding:async e=>{let t=await y.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await mc(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 mc(y,g),b.notifyUpdate(g)});return Di(S,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!Wl(e))return;let c=t===void 0?void 0:ol.parse(t);if(sl(c))return;Au(p,e.request);let l=await _l({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),u=await y.get(l.key);if(!u?.opened)return;let d=Pu(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+ms(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||!Cl(await ee(l,c,u),u.descriptor)||await te({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:b,fetch:r,input:i,requiredCumulative:_,signal:a})}),Fi(S,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!Wl(e))return u;if(!vs(u))return ps(jt(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await _l({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,p=await y.get(f),h={assertVoucherWithinLocalLimit:t=>Bc(t,_(e.request,p?.chainId).maxDeposit),createSessionCredential:(e,t)=>C(e,t,c),fetch:i,getChannel:()=>p??null,async topUpIfNeeded({deposit:n,requiredCumulative:r,signal:a}){p&&await te({autoSwap:t===void 0?void 0:ol.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return lu({onNeedVoucher:(t,n)=>uu({challenge:e,driver:h,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function Pu(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 Fu=new WeakMap;function Iu(e,t){Fu.set(e,t)}function Lu(e){let t=null;return{wait(n=()=>!0){if(t)throw Error(`${e} wait already in progress`);return new Promise((e,r)=>{t={predicate:n,resolve:e,reject:r}})},settle(e){if(!t||!t.predicate(e))return;let n=t;t=null,n.resolve(e)},reject(e){if(!t)return;let n=t;t=null,n.reject(e)}}}function Ru(e){let t=Lu(`close-ready`),n=Lu(`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 zu(e){return e.method===Ze.tempo&&e.intent===Qe.charge}function Bu(e){if(!zu(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Vu(e,t,n){if(!n)return t;let r={...ta(ql(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 Hu(e,t){return e===void 0?t:{...ol.parse(e),...t}}function Uu(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 Wu(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&Ua(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=Uu(e),i;function a(e){let t=new URL(ql(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??(ql(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=Kc(),f=e.credentialContext===void 0?void 0:Hu(e.credentialContext,{}),p=Ru({getSocketSession:()=>d.socketSession}),m=e.channelStore??cc(),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,mc(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=>hc(m,e)};dc(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(hc(m,t)).catch(()=>void 0)}async function ee(){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(hc(m,t)).catch(()=>void 0)}e.created.clear(),await ce(e.committed??e.previous)}}function x(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=Zc({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function S(e){return Ac(d,e)}function C(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function te(e){let t=g,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit&&!e.uncertainTopUp||(t.resumed=void 0,t.committed=Zc({channel:d.channel,spent:d.spent,state:d.state}))}let w=Nu({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&&S({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:C()}),te(e)}}),T=Ai(w);T&&Di(w,e=>ie(()=>Promise.resolve(T(e)),e.signal)),Ii(w);let E=qo({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:[w],onChallenge:async(e,t)=>{if(!Ul(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&&(x(e)||(n?.created.size?await ee():r&&await ce(n.committed??n.previous)),d.lastChallenge=e,S({type:`challengeReceived`,challengeId:e.id}))}});function O(e,t){let n={challenge:e,context:Hu(f,t)};return i&&Hi(n,i),w.createCredential(n)}function k(e){qc({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`&&S({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=Ec(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 Sl({account:await e.resolveAccount?.({account:a,chainId:r.chainId,operation:{authority:Es(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=ql(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=ql(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(zu);if(!n||!Bu(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 Yc({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=Gl(t);if(!n)return;if(Ds({...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){Pc({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 Zl&&(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 pc(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 Ql({...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),te(n)}});k(a);let o=d.channel,s=Vl({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,S({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:C()}),te(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=zc({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=Xc({channel:d.channel,channelId:e,challengeId:d.lastChallenge?.id,cumulativeAmount:t,spent:d.spent,state:d.state});n&&d.channel&&(S({type:`activated`,challengeId:n.challengeId,entry:d.channel,spent:n.spent,units:n.units}),await v(d.channel))}async function ce(e){let t=Qc(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?_s(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=Zc({channel:d.channel,spent:d.spent,state:d.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};g=i;try{await M(e,t),i.trackCreates=!0;let a=Vu(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=Vu(e,t,void 0),!0)}for(;;){let t;try{t=await D(e,a)}catch(e){if(i.created.size?await ee():await ce(i.committed??n),await s())continue;throw e}let o=z(t),c=!1;if(o.status===402){let t=await eu({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 ee():await ce(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function ue(e){let t=await nu({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(),S({type:`closeStarted`}),S({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=Bl({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=Bl({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 ru(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=Yl(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 fu({async createSessionCredential(e,i){return d.lastChallenge=e,await ki(w,{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:Vu(n,i,o),signal:t?.signal});return d.lastChallenge=s,_u({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 du({fetch:r.fetch,input:l,probeInit:Vu(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=Vc({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===Ll.OPEN){let r=await $c({activeSocket:n,createSessionCredential:O,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return A(),S({type:`closeStarted`}),S({type:`closed`,receipt:r}),r}return ue(t)}};return Iu(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 iu(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(!Ul(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,S({type:`challengeReceived`,challengeId:t.id}),S({type:`activated`,challengeId:t.id,entry:e,spent:s.toString(),units:0})}}),fe}(function(e){e.serializeSnapshot=Tc,e.deserializeSnapshot=Ec})(Wu||={});const Gu=(1n<<64n)-1n,Ku={dev_second:1n,day:86400n,week:604800n};function qu(e){return e instanceof Date?e:new Date(e)}function Ju(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 Yu(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new Y({reason:`periodCount is invalid`});let t=Ku[e.periodUnit];if(t===void 0)throw new Y({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>Gu)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 Xu(e){let{challengeExpires:t,request:n}=e;Yu(n);let r=Ju(qu(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 Zu(e){return[{address:ud(e.currency,`currency`),selector:`0x95777d59`,recipients:[ud(e.recipient,`recipient`)]}]}function Qu(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 $u(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=td({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 ed(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=nd(i.signature),s=rd(o);if(id({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==Qu(n))throw new Y({reason:`keyAuthorization challenge mismatch`});return ad(o,a),sd(od(o),a),cd(o.scopes,a),{authorization:o,source:{address:ld(o,s),chainId:r}}}function td(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return ge.from({address:ud(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:Ju(qu(i.subscriptionExpires)),limits:[{token:ud(i.currency,`currency`),limit:BigInt(i.amount),period:Yu(i)}],scopes:Zu(i),type:t.keyType,witness:Qu(n)})}function nd(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 rd(e){let t=e.signature;if(!t)throw new Y({reason:`keyAuthorization must use a primitive signature`});return t}function id(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,ud(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 ad(e,t){if(Xu({request:t}),e.expiry!==Ju(qu(t.subscriptionExpires)))throw new Y({reason:`keyAuthorization expiry mismatch`})}function od(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 sd(e,t){if(!d(e.token,ud(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!==Yu(t))throw new Y({reason:`keyAuthorization period mismatch`})}function cd(e,t){if(!e||e.length!==1)throw new Y({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=ud(t.currency,`currency`),r=ud(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=dd(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 ld(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 ud(e,t){if(!u(e))throw new Y({reason:`${t} must be an address`});return e.toLowerCase()}function dd(e){return typeof e==`string`?e.toLowerCase():``}const fd=U.object({accessKey:U.optional(U.custom()),account:U.optional(U.custom())});function pd(e={}){let t=Va({chain:R,getClient:e.getClient,rpcUrl:ir}),n=La({account:e.account});return Kt(Go,{context:fd,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.");hd(r.request),await e.validateRequest?.(r.request);let l=await md(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=ed({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 md(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await $u({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:Ju(qu(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:A.fromNumber(BigInt(o.amount)),period:Yu(o)}],scopes:Zu(o),witness:Qu(i)}]});return ge.fromRpc(c.keyAuthorization)}function hd(e){Yu(e),Ju(qu(e.subscriptionExpires))}const gd=Object.assign(Nu,{manager:Wu});function _d(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[qo(e),gd(n)]}(function(e){e.charge=qo,e.common=_d,e.session=gd,e.subscription=pd})(_d||={});const vd=L.union([L.boolean(),L.literal(`true`).transform(()=>!0),L.literal(`false`).transform(()=>!1)]);async function yd(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}const bd=L.object({allowCustomEscrow:L.optional(vd),autoSwap:L.optional(vd),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())}),xd=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`];function Sd(){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=Od(i),u=Md({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)&&Vd()){g=!0;let t=zd(a);if(t){let i=lr(r.rpcUrl,{network:r.network});h=e({chain:await ur({network:r.network,rpcUrl:i}),transport:l(i)}),Ad({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=Ud();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)}),Ad({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 Hd(t)}};if(!m||!h)throw new $n({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let v=_d({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=Pd(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 Ws(h,m,c,i,a);return Ft({challenge:n,payload:{action:o,channelId:e,...o===`close`?{closeSignature:await Gs(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,ee=BigInt(g.amount),x=`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 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?``:`
|
|
13
13
|
`}${Z.dim(`Channel opened ${h.payload.channelId}`)}${t}\n`)}else m(`${l?``:`
|
|
14
|
-
`}${Z.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let
|
|
15
|
-
`})}catch{}return(
|
|
16
|
-
`),l&&!await e.confirm(`Close channel?`,!0)?s>=1&&m(`${Z.dim(`Kept channel open.`)}\n`):await
|
|
17
|
-
`)}function
|
|
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:`
|
|
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
|
|
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
|
|
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};
|