mppx 0.22.1 → 0.22.2

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.
@@ -4,7 +4,7 @@ import{createClient as e,createTransport as t,custom as n,decodeErrorResult as r
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
6
  `,i))}t=t.slice(i)}}}const ta=[U.authorization,U.paymentAuthorization,In,Rn,Ln];function na(e,t,n){let r=new Headers(e.headers);for(let e of ta){let t=r.get(e);if(t===null)continue;if(!aa(e)){r.delete(e);continue}let n=ra(t);n!==t&&(n?r.set(e,n):r.delete(e))}return r.set(t,n),{...e,headers:r}}function ra(e){let t=e.split(`,`).map(e=>e.trim()),n=t.filter(e=>!ia.test(e));return n.length===t.length?e:n.filter(Boolean).join(`, `)}const ia=RegExp(`^${st.payment}(?:\\s|$)`,`i`);function aa(e){return e===U.authorization||e===U.paymentAuthorization}function oa(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 sa(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}}function ca(e){if(typeof e?.body!=`string`)return!1;try{let t=JSON.parse(e.body);return t?.jsonrpc===`2.0`&&t.params?._meta?.[`org.paymentauth/credential`]!=null}catch{return!1}}const la=1048576,ua=new WeakMap;function da(e){let t=oa(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 fa(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 pa(e){if(!e||typeof e!=`object`)return;let t=e?.challenges;if(!Array.isArray(t)||t.length===0)return;let n=[];for(let e of t){if(!Bt.safeParse(e).success)return;if(dn(e))continue;let t=zt.safeParse(e);if(!t.success)return;n.push(t.data)}if(n.length===0)return;let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function ma(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:pa(e.error.data):pa(e.result?._meta?.[`org.paymentauth/payment-required`])}function ha(e,t){return!e||e.id!==t?[]:ma(e)?.challenges??[]}async function ga(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=ea(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=fa(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>la)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function _a(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 fa(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>la)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function va(e){let t=ua.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>la)){if(t.includes(`application/json`))return _a(e);if(t.includes(`text/event-stream`))return ga(e)}})();return ua.set(e,n),n}function ya(){return{getChallenges(e,t){let n=da(t);return e.status===402||n===void 0?[]:va(e).then(e=>ha(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=yn(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}async function ba(e,t){let n=da(t);if(e.status===402||n===void 0)return!1;let r=await va(e);return!r||r.id!==n?!1:ma(r)?.problem?.type===xa}const xa=`https://paymentauth.org/problems/invalid-challenge`;function Sa(){return{getChallenges(e){let t=e.headers.get(U.wwwAuthenticate);return e.status!==402||!t||!en(t)?[]:nn(e)},setCredential(e,t,n){let r=n?.challenge??wa(t);return na(e,r?un(r):U.authorization,t)}}}const Ca=/^Payment [A-Za-z0-9_-]+={0,2}$/;function wa(e){if(Ca.test(e))try{return yn(e).challenge}catch{return}}function Ta(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(In);if(!t)return[];let n=ar(t);return n.accepts.flatMap((e,t)=>{let r=Gn.safeParse(e);if(!r.success)return[];let i=r.data;return Dn(Vt({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 na(e,Ln,t)}}}function Ea(e){return e}function Da(){let e=[Sa(),Ta(),ya()],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 Ea({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 Oa=new WeakMap;function ka(e,t){return Oa.set(e,t),e}function Aa(e){return Oa.has(e)}function ja(e,t){return Promise.resolve(Oa.get(e)?.(t))}function Ma(e){return Oa.get(e)}const Na=new WeakMap,Pa=new WeakMap,Fa=new WeakMap,Ia=new WeakMap;function La(e,t){return Na.set(e,t),e}function Ra(e){Na.delete(e)}function za(e,t,n){Na.has(e)&&Pa.set(t,n)}function Ba(e){return Pa.get(e)}function Va(e,t){return Promise.resolve(Na.get(e)?.(t)??t.response)}function Ha(e,t){return Ia.set(e,t),e}function Ua(e,t){try{return Ia.get(e)?.(t)}catch{return}}function Wa(e,t){Fa.set(e,t)}function Ga(e){return Fa.get(e)??Pa.get(e)?.origin}async function Ka(e,t){let{attempts:n,signal:r}=t;for(let t=1;;t++){r?.throwIfAborted();try{return await e()}catch(e){if(!(e instanceof Ct)||t>=n)throw e;r?.throwIfAborted()}}}function qa(e,t,n){if(!Ja(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&&Ya(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 Ja(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Ya(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}const Xa=Symbol.for(`mppx.client.fundsMayHaveMoved`);function Za(e){return Object.defineProperty(e,Xa,{value:!0}),e}function Qa(e){return typeof e==`object`&&!!e&&e[Xa]===!0}const $a=[4217,42431],eo=[ie,ae,oe],to=[{network:`stripe`,asset:`usd`,currency:`USD`,decimals:2}],no=`charge`,ro=new WeakSet,io=new WeakMap,ao=new WeakSet,oo=/^(\d+)(?:\.(\d+))?$/;function so(e){let{authorize:t,funders:n=[],maxPayment:r,tokens:i}=e;if(r!==void 0&&ko(r),t!==void 0&&typeof t!=`function`)throw TypeError(`authorize must be a function.`);if(!Array.isArray(n)||n.some(e=>typeof e?.fund!=`function`))throw TypeError(`funders must be an array of objects with a fund function.`);let a=Ro(i),o=e=>jo(e,a),s=r!==void 0||t!==void 0||n.length>0,c=r===void 0?`budget`:`maxPayment`;return{limit:c,resolve(e){if(e.intent===no)try{return o(e)}catch{return}},prepare:s?async(e,{method:i,signal:a}={})=>{if(a?.throwIfAborted(),e.intent!==no)throw new wt({limit:c,reason:`intent`});e.expires&&kn(e.expires,e.id);let s=i&&nt(i);if(s?.resumes?.(e))return Object.freeze({settlement:zo(void 0),constraints:l(!0)});let u=ho(e),d=o(e);r!==void 0&&Ao(d,r),s?.assert?.(e);let f=Object.freeze({challenge:Co(e),...a?{signal:a}:{}}),p=Object.freeze({requirement:d});ro.add(p);let m=zo(await t?.(p,f)??void 0);try{for(let e of n)a?.throwIfAborted(),await e.fund(d,f);if(a?.throwIfAborted(),ho(e)!==u)throw Error(`Cannot check spending limits: the challenge changed while checked.`);e.expires&&kn(e.expires,e.id)}catch(e){throw m.release(),e}return Object.freeze({settlement:m,constraints:l(!1)})}:void 0};function l(e){let n=Object.freeze({limit:c,resume:e});return io.set(n,t),n}}function co(e){let t=ot(e);return t!==void 0&&ao.has(t)&&io.has(t)&&io.get(t)===io.get(e)}function lo(e){return e!==void 0&&(e.maxPayment!==void 0||e.authorize!==void 0||e.funders!==void 0&&e.funders.length>0||e.tokens!==void 0)}function uo(e){let{authorize:t,funders:n,maxPayment:r,tokens:i}=e;return{...t!==void 0&&{authorize:t},...n!==void 0&&{funders:n},...r!==void 0&&{maxPayment:r},...i!==void 0&&{tokens:i}}}function fo(e,t){if(!lo(t))return uo(e);if(lo(e))throw TypeError(`The fetch passed in already has spending options (maxPayment, authorize, funders or tokens). Set them on one fetch only.`);return t}function po(e,t){return t?e.then(e=>(t.commit(),e),e=>{throw e instanceof Ct||e instanceof vt||Qa(e)?t.commit():t.release(),e}):e}function mo(e,t,n,r){let i,a=!1,o,s=()=>i??=Promise.resolve(e.prepare?.(t,{method:r,signal:n})),c=async()=>{if(!e.prepare)return;n?.throwIfAborted();let r=a?void 0:await s();if(r&&!r.constraints.resume)return r.settlement.commit();(await e.prepare(t,{signal:n})).settlement.commit()},l=async()=>{await o,(await i?.catch(()=>void 0))?.settlement.release()};return{prepare:s,async track(e){let r=await s();if(r&&n?.aborted&&(r.settlement.release(),n.throwIfAborted()),r&&!r.constraints.resume&&t.expires)try{kn(t.expires,t.id)}catch(e){throw r.settlement.release(),e}let i=po(e(r?.constraints),r&&{commit(){a=!0,co(r.constraints)?r.settlement.release():(r.settlement.commit(),r.constraints.resume||ao.add(r.constraints))},release(){}});return o=i.then(()=>{},()=>{}),i},commit:c,async commitReplacement(r,i){if(!e.prepare)return;let a=_o(r,i);if(!a)throw So(e);return go(a)===go(t)?(await c(),a):(await l(),await mo(e,a,n).commit(),a)},release:l}}function ho(e){let{digest:t,expires:n,id:r,intent:i,meta:a,method:o,opaque:s,realm:c,request:l}=e;return JSON.stringify([On(e),r,c,o,i,G(l),n??null,t??null,s??(a===void 0?null:G(a))])}function go(e){try{return ho(e)}catch{return}}function _o(e,t){let n=vo(e,t)??yo(e,t);return n?.length===1?n[0]:void 0}function vo(e,t){let n;try{n=yn(e).challenge}catch{return}let r=go(n);return r===void 0?[]:t.filter(e=>go(e)===r)}function yo(e,t){let n;try{n=sr(e)}catch{return}return t.filter(e=>On(e)&&bo(n,e))}function bo(e,t){let n=Gn.safeParse(t.request);if(!n.success)return!1;let r=n.data;try{if(G(r)!==G(e.accepted))return!1;let t=BigInt(r.amount),n=e.payload;if(`authorization`in n)return xo(n.authorization.to,r.payTo)&&BigInt(n.authorization.value)===t;let{permitted:i,witness:a}=n.permit2Authorization;return xo(i.token,r.asset)&&BigInt(i.amount)===t&&xo(a.to,r.payTo)}catch{return!1}}function xo(e,t){return e.toLowerCase()===t.toLowerCase()}function So(e){return new wt({limit:e.limit,reason:`credential`})}function Co(e){let t;try{t=structuredClone(e)}catch{t=JSON.parse(JSON.stringify(e))}return On(e)&&Dn(t),wo(t)}function wo(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))wo(t);return e}function To(e,t){let n=/^0x[\da-fA-F]{40}$/.test(t)||e===`stripe`?t.toLowerCase():t;return JSON.stringify([e,n])}function Eo(e,t){let[,n=`0`,r=``]=oo.exec(e)??[];return BigInt(`${n}${r.slice(0,t).padEnd(t,`0`)}`)}function Do(e,t){let{currency:n,value:r}=e??{};if(typeof n!=`string`||!n.trim())throw TypeError(`${t} currency must be a non-empty string.`);if(typeof r!=`string`||r.length>1024||!oo.test(r))throw TypeError(`${t} value must be a non-negative decimal string.`)}function Oo(e){if(typeof e!=`object`||!e)return!1;let{amount:t,asset:n,network:r}=e;return typeof r==`string`&&r.length>0&&typeof n==`string`&&n.length>0&&typeof t==`bigint`&&t>=0n}function ko(e){if(!Array.isArray(e))return Do(e,`maxPayment`);let t=new Set;for(let n of e){if(!Oo(n))throw TypeError(`Each maxPayment limit needs a network, an asset and a bigint amount.`);let e=To(n.network,n.asset);if(t.has(e))throw TypeError(`Duplicate maxPayment limit for ${n.asset}.`);t.add(e)}}function Ao(e,t){let n=e=>new wt({limit:`maxPayment`,reason:e});if(Array.isArray(t)){let r=To(e.network,e.asset),i=t.find(e=>To(e.network,e.asset)===r);if(!i)throw n(`asset`);if(e.amount>i.amount)throw n(`amount`);return}let r=t,{currency:i,decimals:a}=e;if(i===void 0||a===void 0||i.toUpperCase()!==r.currency.toUpperCase())throw n(`asset`);if(e.amount>Eo(r.value,a))throw n(`amount`)}function jo(e,t){let n=On(e)?No(e):Po(e),r=t.get(To(n.network,n.asset)),i={method:e.method,intent:e.intent,...n,...r?{currency:r.currency,decimals:r.decimals}:{}};return Object.defineProperty(i,"toJSON",{value:Mo}),Object.freeze(i)}function Mo(){return{...this,amount:this.amount.toString(),...this.splits&&{splits:this.splits.map(e=>({...e,amount:e.amount.toString()}))}}}function No(e){let t=Gn.safeParse(e.request);if(!t.success)throw Error(`Cannot check spending limits: invalid x402 requirements.`);let{amount:n,asset:r,network:i,payTo:a}=t.data;return{protocol:`x402`,network:i,asset:r,amount:Lo(n),recipient:a}}function Po(e){let t=e.request,n=typeof t.methodDetails==`object`&&t.methodDetails!==null?t.methodDetails:{},r=n.chainId;if(r!==void 0&&(!Number.isSafeInteger(r)||r<=0))throw Error(`Cannot check spending limits: invalid challenge chain ID.`);if(t.chainId!==void 0&&t.chainId!==r)throw Error(`Cannot check spending limits: challenge names a chain outside methodDetails.chainId.`);let i=t.currency;if(typeof i!=`string`||!i)throw Error(`Cannot check spending limits: challenge names no currency.`);let a=Lo(t.amount),o=Fo(e.method,t,n),s=Io(n.splits,a);return{protocol:`mpp`,network:r===void 0?e.method:`eip155:${r}`,asset:i,amount:a,...o===void 0?{}:{recipient:o},...s?{splits:s}:{}}}function Fo(e,t,n){if(e===`stripe`){if(typeof n.networkId!=`string`||!n.networkId)throw Error(`Cannot check spending limits: Stripe challenge names no networkId.`);return n.networkId}return typeof t.recipient==`string`?t.recipient:void 0}function Io(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)throw Error(`Cannot check spending limits: invalid payment splits.`);let n=0n,r=e.map(e=>{let{amount:t,recipient:r}=e??{};if(typeof r!=`string`||!r)throw Error(`Cannot check spending limits: payment split names no recipient.`);let i=Lo(t);return n+=i,Object.freeze({recipient:r,amount:i})});if(n>=t)throw Error(`Cannot check spending limits: payment splits are not less than the amount.`);return Object.freeze(r)}function Lo(e){if(typeof e!=`string`||!/^\d+$/.test(e))throw Error(`Cannot check spending limits: challenge amount is not an atomic integer.`);return BigInt(e)}function Ro(e){let t=new Map;for(let e of eo)for(let n of $a){let r=e.addresses[n];r&&t.set(To(`eip155:${n}`,r),{currency:e.currency,decimals:e.decimals})}for(let{asset:e,currency:n,decimals:r,network:i}of to)t.set(To(i,e),{currency:n,decimals:r});if(e===void 0)return t;if(!Array.isArray(e))throw TypeError(`tokens must be an array.`);let n=new Map;for(let t of e){let{currency:e,decimals:r}=t??{};if(typeof e!=`string`||!e.trim())throw TypeError(`Each token needs a currency, such as USD.`);if(typeof r!=`number`||!Number.isInteger(r)||r<0||r>255)throw TypeError(`Token decimals must be an integer from 0 to 255.`);let i=typeof t==`function`?Object.entries(t.addresses).map(([e,t])=>[Number(e),t]):[[t.chainId,t.address]];for(let[t,a]of i){if(!Number.isSafeInteger(t)||t<=0||typeof a!=`string`||!a)throw TypeError(`Each token needs an address and a chain ID.`);let i=To(`eip155:${t}`,a),o=n.get(i);if(o&&(o.currency.toUpperCase()!==e.toUpperCase()||o.decimals!==r))throw TypeError(`tokens configure conflicting metadata for ${a}.`);n.set(i,Object.freeze({currency:e,decimals:r}))}}for(let[e,r]of n)t.set(e,r);return t}function zo(e){let t=!0,n=n=>{t&&(t=!1,n?.call(e))};return Object.freeze({commit:()=>n(e?.commit),release:()=>n(e?.release)})}const Bo=Symbol.for(`mppx.fetch.wrapper`),Vo=Symbol.for(`mppx.fetch.identity`),Ho=Symbol.for(`mppx.fetch.spend`),Uo=Symbol.for(`mppx.fetch.skipPayment`);function Wo(e={}){return{...e,[Uo]:!0}}const Go=65536,Ko=new WeakMap;async function qo(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>Go){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,Go),{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 Jo(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 Yo(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=Da(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&vs(e.fetch)),d=e.eventDispatcher??Zo(),f=t??Ai(a),p=fo(e,e.fetch&&ys(e.fetch)),m=so(p),h=bs(r),g=async(e,t,n)=>u?u.send((e,n)=>h(e,t?.[Uo]?Wo(n):n),new Request(e,t),n):{response:await h(e,t),headers:[]},_=async(e,t,r)=>{let p=_s(e,t?.headers),v=p.has(U.acceptPayment),y=Es(p,f),b=Ss(e,t),x=hs(e,t,p,m.prepare?b:void 0),S=ms(e,t,p,y.header,v,n);if(m.prepare){let e=await x;if(b?.throwIfAborted(),sa(gs(S.init,e)))throw TypeError(`This fetch has spending options (maxPayment, authorize or funders), but McpClient.wrap pays MCP tool calls itself. Set them on McpClient.wrap and give its transport a fetch without them.`)}let C=await g(xs(S.input),S.init),w=C.response,ee=C.headers,T=gs(S.init,await x);if(t?.[Uo]||sa(T)||!await c.isPaymentRequired(w,T))return w;let te=t?.context,{context:ne,orderChallenges:re,...E}=T??{},D=Rs(p)||ca(T),O,k,A,j,M;try{for(let n=0;n<i;n++){if(k=await c.getChallenges(w,T),(n>0||D)&&await Ls(w,T))return await Jo(j,{challenges:k,response:w,status:`rejected`}),w;let f=(await Ds(Ni(k,a,y.entries,te),re??s))[0];if(!f){if(await Jo(j,{challenges:k,response:w,status:`rejected`}),n>0)return w;throw Error(sn(`No method found for challenges: ${k.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`,Fs(w)))}let p=f.challenge;O=p,A=f.method,O.expires&&kn(O.expires,O.id),await u?.challenge(w,{challenge:p},js(S.input).href);let v=await Ps(w,S.input,S.input,E);qa(p,()=>js(v),l);let b=j,x=Is(p),C=b?.method===f.method&&b?.key===x,ne=!1;if(b){let e=await Jo(b,{challenges:k,response:w,status:C?`pending`:`rejected`});ne=C&&!e}j=ne?b:void 0;let N=mo(m,p,Ss(e,t),f.method),P,F=ns(async n=>{if(n===void 0&&ne&&b)return P=b.promise,b.promise;ne&&b&&(await Jo(b,{status:`rejected`}),j=void 0),Ss(e,t)?.throwIfAborted();let r=n??te;if(!Aa(f.method))return P=N.track(n=>Ka(()=>Ts(p,f.method,r,Ms(v),n),{attempts:i,signal:Ss(e,t)})),P;let a={origin:js(v).origin,prepare:()=>ja(f.method,{challenge:p,context:r,fetch:u?Ti(h,u,{challenge:p}):h,input:v,signal:Ss(e,t)})},o=N.track(e=>a.prepare().then(()=>Ts(p,f.method,r,a,e)));return P=o,j={context:r,attempt:a,key:n===void 0?x:void 0,method:f.method,promise:o},o}),I,L,R,z=!1;try{let n=await d.emit(`challenge.received`,rs({challenge:p,challenges:k,createCredential:F,init:t,input:e,method:f.method,response:w}))??(o?await o(O,{createCredential:F}):void 0);if(n===!1)return await N.release(),await Jo(j,{challenges:k,response:w,status:`rejected`}),j=void 0,w;I=n??await F(),L=j,L&&await L.promise.catch(()=>void 0)!==I&&(await Jo(L,{status:`rejected`}),j=void 0),ws(I),z=P!==void 0&&await P.catch(()=>void 0)===I,z||(R=await N.commitReplacement(I,k))}catch(e){throw await N.release(),e}let ie=j?j.context:te,ae=Cs(I,p);await d.emit(`credential.created`,is({challenge:p,credential:I,init:t,input:e,method:f.method,response:w}));let oe=e=>new _t({cause:e,challenge:p,credential:I,transactionHash:Ua(f.method,I)});try{({response:w,headers:ee}=await g(v,{...c.setCredential({...E,headers:S.headers},I,{challenge:R??p}),redirect:`manual`},{challenge:ae,headers:ee}))}catch(e){throw M=oe(e),e}let B=await c.isPaymentRequired(w,T);if(B||(await Jo(L,{response:w,status:w.status>=300&&w.status<400?`pending`:w.ok?`accepted`:`rejected`}),j=void 0),w.ok&&Qo(d,`payment.response`)){let n=z?p:R??_o(I,k);await d.emit(`payment.response`,as({challenge:p,credential:I,init:t,input:e,method:f.method,requirement:n&&m.resolve(n),response:w}))}if(!B){if(w.status>=500&&Qo(d,`payment.failed`)){try{w=await qo(w)}catch(e){throw M=oe(e),w=new Response(null,{headers:w.headers,status:w.status,statusText:w.statusText}),e}await d.emit(`payment.failed`,os({challenge:p,challenges:k,error:oe(),init:t,input:e,method:f.method,response:w}))}return w.ok?Va(f.method,{context:ie,challenge:p,credential:I,fetch:h,headers:S.headers,input:v,...r?{refetch:()=>_(xs(S.input),t,!1)}:{},response:w,signal:Ss(e,t)}):w}}k=void 0;try{k=await c.getChallenges(w,T)}catch{}return await Jo(j,{challenges:k,response:w,status:`rejected`}),w}catch(n){throw await Jo(j,{challenges:k,response:w,status:`rejected`}),await d.emit(`payment.failed`,os({challenge:O,challenges:k,error:M??n,init:t,input:e,method:A,response:w})),n}},v=(e,t)=>_(e,t,!0);return v[Bo]=h,u&&(v[Vo]=u),lo(p)&&(v[Ho]=p),v}function Xo(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 Zo(){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 $o(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await ts(e[`*`],t,n),r}case`credential.created`:await es(e[`credential.created`],n),await ts(e[`*`],t,n);return;case`payment.failed`:await es(e[`payment.failed`],n),await ts(e[`*`],t,n);return;case`payment.response`:await es(e[`payment.response`],n),await ts(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 Ko.set(t,t=>e[t].size>0||e[`*`].size>0),t}function Qo(e,t){return Ko.get(e)?.(t)??!0}async function $o(e,t){try{return await e(t)}catch{return}}async function es(e,t){for(let n of e)try{await n(t)}catch{}}async function ts(e,t,n){await es(e,Object.freeze({name:t,payload:n}))}function ns(e){let t;return n=>(t??=e(n),t)}function rs(e){return Object.freeze({challenge:ds(e.challenge),challenges:e.challenges.map(e=>ds(e)),createCredential:e.createCredential,init:ss(e.init),input:cs(e.input),method:ls(e.method),response:us(e.response)})}function is(e){return Object.freeze({challenge:ds(e.challenge),credential:e.credential,init:ss(e.init),input:cs(e.input),method:ls(e.method),...e.response===void 0?{}:{response:us(e.response)}})}function as(e){let{requirement:t,response:n}=e,r=n instanceof Response?Qi(n):void 0;return Object.freeze({...t?{amount:t.amount.toString(),requirement:t}:{},...r?{receipt:r}:{},challenge:ds(e.challenge),credential:e.credential,init:ss(e.init),input:cs(e.input),method:ls(e.method),response:us(e.response)})}function os(e){return Object.freeze({...e.challenge?{challenge:ds(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>ds(e))}:{},error:e.error,init:ss(e.init),input:cs(e.input),...e.method?{method:ls(e.method)}:{},...e.response===void 0?{}:{response:us(e.response)}})}function ss(e){if(e)return ps({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function cs(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function ls(e){return ps(Object.assign({},e))}function us(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 ds(e)}function ds(e){try{return fs(structuredClone(e))}catch{return ps(e)}}function fs(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))fs(t);return e}function ps(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function ms(e,t,n,r,i,a){let o=!!r&&!i&&Os(e,a);if(!o)return{headers:n,init:t,input:e};let s=new Headers(e instanceof Request?e.headers:void 0);return n.forEach((e,t)=>{s.set(t,e)}),s.set(U.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function hs(e,t,n,r){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{let t=e.clone();return(r&&t.body?new Response(t.body.pipeThrough(new TransformStream,{signal:r})):t).text().catch(()=>void 0)}catch{return}}}function gs(e,t){return t===void 0?e:{...e,body:t}}function _s(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function vs(e){return e[Vo]}function ys(e){return e[Ho]}function bs(e){let t=e;for(;t[Bo];)t=t[Bo];return t}function xs(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function Ss(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function Cs(e,t){try{let{challenge:n}=yn(e);return n.id===t.id?t:{...n,...t.header!==void 0&&{header:t.header}}}catch{return t}}function ws(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 Ts(e,t,n,r,i){let a=t.context&&n!==void 0?t.context.parse(n):void 0,o=a===void 0?{challenge:e}:{challenge:e,context:a};return i&&rt(o,i),r?.origin&&Wa(o,r.origin),r&&`prepare`in r&&za(t,o,r),t.createCredential(o)}function Es(e,t){let n=e.get(U.acceptPayment);if(!n)return t;try{return{...t,entries:ji(n),header:n}}catch{return t}}async function Ds(e,t){return t?t(e):e}function Os(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=js(e);return t===`same-origin`?!As()||n.origin===globalThis.location.origin:t.origins.some(e=>ks(n,e))}function ks(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 As(){return globalThis.location!==void 0}function js(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,As()?globalThis.location.href:void 0)}function Ms(e){try{return{origin:js(e).origin}}catch{return}}function Ns(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 Ps(e,t,n,r){if(Ns(t,r),!e.url)return t;let i=new URL(e.url),a=js(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 Fs(e){return!(e instanceof Response)||e.status!==402?0:on(e.headers.get(U.wwwAuthenticate))}function Is(e){let{description:t,...n}=e;return j.canonicalize(n)}async function Ls(e,t){if(!(e instanceof globalThis.Response))return!1;if(await ba(e,t))return!0;if(!e.headers.get(`Content-Type`)?.includes(`application/problem+json`))return!1;try{return(await e.clone().json()).type===`https://paymentauth.org/problems/invalid-challenge`}catch{return!1}}function Rs(e){return e.get(U.paymentAuthorization)?!0:/(^|,)\s*Payment\s+\S/i.test(e.get(U.authorization)??``)}function zs(e={}){let{account:t}=e;return(e,{account:n}={})=>{let r=n??t;if(!r){if(!e.account)throw Error("No `account` provided. Pass `account` to parameters or context.");return e.account}return fe(r)}}function Bs(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}const Vs={[R.id]:R,[z.id]:z};function Hs(e,t={}){return u(e.url,{fetchFn:e.fetch,fetchOptions:{headers:Bs(e)},...t})}function Us(r){let{chain:i,getClient:a,remoteFeePayer:o,rpcUrl:s}=r;return a?!i?.serializers&&!o&&!r.requireChain?a:async e=>{let s=await a(e);if(r.requireChain&&(s.chain?.id===void 0||s.chain.id!==e.chainId))throw Error(`Subscription chain mismatch: expected ${e.chainId}, got ${s.chain?.id??`unknown`}.`);let c=s;if(o&&s.transport.key!==`feePayer`){let e=s.request.bind(s),r=de(n({request:t=>e(t)},{retryCount:0}),Hs(o,{retryCount:s.transport.retryCount}))({account:s.account,chain:s.chain,pollingInterval:s.pollingInterval,retryCount:0}),i=t({...r.config,retryCount:0},r.value);c=Object.assign({},s,{request:i.request,transport:{...i.config,...i.value}})}return!i?.serializers||c.chain?.serializers?.transaction?c:Object.assign({},c,{chain:{...i,...e.chainId===void 0?{}:{id:e.chainId},...c.chain,formatters:c.chain?.formatters??i.formatters,prepareTransactionRequest:c.chain?.prepareTransactionRequest??i.prepareTransactionRequest,serializers:c.chain?.serializers?.transaction?c.chain.serializers:i.serializers}})}:({chainId:t})=>{if(!s)throw Error("No `rpcUrl` provided.");let n=t||Number(Object.keys(s)[0]),r=s[n];if(!r)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let a=o?de(u(r),Hs(o)):u(r);return e({chain:Vs[n]??{...i,id:n},transport:a})}}function Ws(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 Gs(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}const Ks=A.slice(k.keccak256(O.fromString(`mpp`),{as:`Hex`}),0,4);function qs(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,10))}function Js(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(A.toBytes(Ks),0),i[4]=1,i.set(qs(t),5),n&&i.set(qs(n),15),i.set(Ys(r),25),A.fromBytes(i)}function Ys(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,7))}function Xs(e,t){return _e.resolve(e).toLowerCase()===_e.resolve(t).toLowerCase()}const Zs=10000n,Qs=[Vr.pathUsd,Vr.usdc,Vr.ousd];async function $s(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||Xs(t,i)||c.some(e=>Xs(e,t))||c.push(t)}let l=await Promise.allSettled([x(e,{...V.token.getBalance.call(e,{account:n,token:i}),account:null}),...c.map(t=>x(e,{...V.token.getBalance.call(e,{account:n,token:t}),account:null}))]),u=l[0];if(u.status!==`fulfilled`)throw u.reason;let d=u.value;if(d>=r)return;let f=r-d,p=BigInt(Math.round(o*100)),m=t.maxAmountIn??f+f*p/Zs;for(let t=0;t<c.length;t++){let n=l[t+1];if(n.status!==`fulfilled`)continue;let r=n.value;if(r<=0n)continue;let a=c[t];try{let t=await V.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:f});if(t<=0n||t>m)continue;let n=t+t*p/Zs,o=n<m?n:m;if(r>=o)return[V.token.approve.call(e,{amount:o,spender:ce.stablecoinDex,token:a}),V.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:f,maxAmountIn:o})]}catch{}}throw new tc({currency:i})}function ec(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`&&Xs(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var tc=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}};function nc(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 rc(e,t,n){t&&(n&&!n.some(e=>Xs(e,t))||e.some(e=>Xs(e,t))||e.push(t))}async function ic(e,t,n){try{return(await V.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function ac(e){let t=e.chain?.feeToken;if(t)return le.toAddress(t);let n=e.chain?.id;return n?Hr[n]:void 0}function oc(e){let t=[];return rc(t,Vr.pathUsd),rc(t,Hr[e]),t}async function sc(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])rc(o,e,n);if(rc(o,await V.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),rc(o,ac(i),n),!a)for(let e of r??[])rc(o,e,n);for(let e of o)if(await ic(i,t,e))return e;return o[0]}const cc=m([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]);function lc(e){if(e!==void 0)return Ur[e]}function uc(e){let t=lc(e.chainId);return!!t&&d(e.currency,{strict:!1})&&f(e.currency,t.token)}function dc(e){let t=lc(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let r=BigInt(n.amount),a=n.memo;return{calls:[{data:i({abi:B.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:i({abi:cc,functionName:`swapTo`,args:[t.token,r,e.currency,n.recipient,a]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:r,memo:a,recipient:n.recipient}]}}async function fc(e,t){let n=dc(t);if(n)try{return await x(e,V.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await _(e,{account:t.account,calls:n.calls}),n)}catch{return}}const pc=10n**BigInt(4);function mc(e={}){let{address:t,amount:n,chainId:r=Z.mainnet}=e;if(r!==Z.mainnet)return;let i=new URL(`https://wallet.tempo.xyz/agent?action=fund&intent=mach&chainId=4217`);if(t&&d(t,{strict:!1})&&i.searchParams.set(`address`,c(t)),n!==void 0&&n>0n){let e=(n+pc-1n)/pc,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 hc(e,t){let n=lc(t.chainId);if(!n)return;let r=await x(e,V.token.getBalance.call(e,{account:t.account,token:n.token})).catch(()=>void 0);return typeof r==`bigint`?r:void 0}async function gc(e,t){let{account:n,amount:r,chainId:i}=t,a=await hc(e,{account:n,chainId:i});if(a===void 0||a>=r)return;let s=e=>`${o(e,6)} MACH`,c=r-a;return{fundingUrl:mc({address:n,amount:c,chainId:i}),reason:`requested ${s(r)}, available ${s(a)}`,shortfall:c}}async function _c(e,t){let n=await gc(e,t);if(n)return new Tt({fundingUrl:n.fundingUrl,reason:n.reason})}const vc={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]};function yc(e){return{name:`MPP`,version:`3`,chainId:e}}function bc(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function xc(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:yc(n),types:vc,primaryType:`Proof`,message:bc({account:t,challengeId:r,realm:i})}}function Sc(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const Cc=[...B.accountKeychain.filter(e=>e.type===`error`),...B.tip20.filter(e=>e.type===`error`)];function wc(e){let t=new Set,n=e;for(;typeof n==`object`&&n&&!t.has(n);){t.add(n);let e=n.data;if(Dc(e))return e;let r=e?.data;if(Dc(r))return r;n=n.cause}}function Tc(e,t){let n=wc(e);if(!n)return;let i=(()=>{try{return r({abi:Cc,data:n})}catch{return}})();if(i?.errorName===`SpendingLimitExceeded`){let n=t.account.accessKeyAddress;return new St({accessKey:typeof n==`string`?n:void 0,account:t.account.address,cause:e})}if(i?.errorName===`InsufficientBalance`){let[n,r,a]=i.args;return new Tt({cause:e,reason:`${t.account.address} holds ${n} of token ${a}, but the payment requires ${r}`})}}async function Ec(e,t){try{return await t()}catch(t){throw Tc(t,e)??t}}function Dc(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{8}/.test(e)}const Oc=7200n,kc=64n,Ac=s({abi:B.zonePortal,name:`WithdrawalProcessed`});function jc(e){return Number.isInteger(e)&&e>0&&e<4217e5}function Mc(e,t){return jc(t)?e===!0||(e?.includes(t)??!1):!1}function Nc(e){return ce.zonePortal(e)}Nc(0).slice(0,-16).toLowerCase();function Pc(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 Fc(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 Ic(e){return k.keccak256(E.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function Lc(e,t){let{blockNumber:n,sender:r,transactionHash:i}=t,a=t=>x(e,{abi:B.zoneOutbox,address:ce.zoneOutbox,blockNumber:t,functionName:`lastFallbackNonce`}),[o,s]=await Promise.all([a(n-1n),a(n)]);if(s<=o)throw Error(`Zone withdrawal transaction ${i} did not request a withdrawal from the outbox.`);if(s-o>kc)throw Error(`Zone withdrawal transaction ${i} has ${s-o} candidate sender tags, more than ${kc}.`);let c=[];for(let e=o+1n;e<=s;e++)c.push(Ic({fallbackNonce:e,sender:r,transactionHash:i}));return c}async function Rc(e,t){let{senderTags:n,timeoutMs:r=6e4}=t;if(!Number.isFinite(r)||r<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);if(n.length===0)throw Error(`Zone settlement needs at least one sender tag.`);let i=await v(e,{cacheTime:0}),a=i>Oc?i-Oc:0n,o=Date.now()+r;for(;;){if(a<=i){let[r]=await y(e,{address:t.portal,event:Ac,args:{senderTag:[...n],...t.to?{to:t.to}:{}},fromBlock:a,toBlock:i});if(r?.transactionHash&&r.args.senderTag)return{hash:r.transactionHash,senderTag:r.args.senderTag};a=i+1n}if(Date.now()+500>o)throw Error(`Zone withdrawal ${n.join(` or `)} did not settle on Tempo within ${r}ms.`);await new Promise(e=>setTimeout(e,500)),i=await v(e,{cacheTime:0})}}const zc=[`push`,`pull`],Bc=K.object({amount:q(),memo:K.optional(Mt()),recipient:K.pipe(K.string(),K.transform(e=>e))}),Vc=(1n<<64n)-1n,Hc={dev_second:1n,day:86400n,week:604800n},Uc=K.pipe(J(),K.transform(e=>e.toLowerCase())),Wc=K.object({accessKeyAddress:Uc,keyType:K.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:K.optional(K.pipe(K.string().check(K.regex(/^0x[0-9a-fA-F]{120}$/)),K.transform(e=>e)))}),Gc=K.object({accessKey:K.optional(Wc),chainId:K.optional(K.number())}),Kc=kt(`subscriptionExpires must be a valid date`).check(K.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),qc=K.enum([`dev_second`,`day`,`week`]),Jc=K.pipe(K.union([K.string(),K.bigint(),K.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),K.transform(e=>e.toString())).check(K.regex(/^[1-9]\d*$/,`Invalid periodCount`),K.refine(e=>{try{return BigInt(e)<=Vc}catch{return!1}},`periodCount exceeds uint64`));function Yc(e){return K.refine(e=>{let{amount:t,decimals:n}=e;return g(t,n)>0n},e)}function Xc(e){let{periodCount:t,periodUnit:n}=e;try{let e=Hc[n];return e!==void 0&&BigInt(t)*e<=Vc}catch{return!1}}const Zc=jn({name:`tempo`,intent:`charge`,schema:{credential:{payload:K.discriminatedUnion(`type`,[K.object({hash:Mt(),type:K.literal(`hash`)}),K.object({signature:Y(),type:K.literal(`transaction`)}),K.object({signature:Y(),type:K.literal(`proof`)}),K.object({hash:Mt(),senderTag:Mt(),type:K.literal(`zone`),zoneId:K.number().check(K.refine(jc,`Invalid Zone ID`))})])},request:K.pipe(K.object({machineTokenEnabled:K.optional(K.boolean()),amount:q(),chainId:K.optional(K.number()),currency:K.string(),decimals:K.number(),description:K.optional(K.string()),externalId:K.optional(K.string()),feePayer:K.optional(K.pipe(K.union([K.boolean(),K.custom()]),K.transform(e=>typeof e==`object`||e))),memo:K.optional(K.never()),recipient:K.optional(K.string()),splits:K.optional(K.array(Bc).check(K.minLength(1),K.maxLength(10))),supportedModes:K.optional(K.array(K.enum(zc)).check(K.minLength(1))),zones:K.optional(K.union([K.literal(!0),K.array(K.number().check(K.refine(jc,`Invalid Zone ID`))).check(K.minLength(1))]))}).check(K.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=g(e,t),i=n.reduce((e,n)=>e+g(n.amount,t),0n);return n.every(e=>g(e.amount,t)>0n)&&i<r},`Invalid splits`)),K.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,zones:c,...l})=>({...l,amount:g(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0||c!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:g(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),Qc=jn({name:`tempo`,intent:`session`,schema:{credential:{payload:K.discriminatedUnion(`action`,[K.object({action:K.literal(`open`),authorizedSigner:K.optional(K.string()),channelId:Mt(),cumulativeAmount:q(),descriptor:K.optional(K.custom()),signature:Y(),transaction:Y(),type:K.literal(`transaction`)}),K.object({action:K.literal(`topUp`),additionalDeposit:q(),channelId:Mt(),descriptor:K.optional(K.custom()),transaction:Y(),type:K.literal(`transaction`)}),K.object({action:K.literal(`voucher`),channelId:Mt(),cumulativeAmount:q(),descriptor:K.optional(K.custom()),signature:Y()}),K.object({action:K.literal(`close`),channelId:Mt(),closeSignature:Y(),cumulativeAmount:q(),descriptor:K.optional(K.custom()),signature:Y()})])},request:K.pipe(K.object({amount:q(),chainId:K.optional(K.number()),channelId:K.optional(Mt()),configurableVouchers:K.optional(K.boolean()),currency:K.string(),decimals:K.number(),escrowContract:K.optional(K.string()),feePayer:K.optional(K.pipe(K.union([K.boolean(),K.custom()]),K.transform(e=>typeof e==`object`||e))),feeToken:K.optional(J()),minVoucherDelta:K.optional(q()),operator:K.optional(J()),recipient:K.optional(K.string()),sessionProtocol:K.optional(K.enum([dt.v2,dt.v1])),sessionSnapshot:K.optional(K.custom()),suggestedDeposit:K.optional(q()),unitType:K.string()}).check(K.refine(({amount:e,decimals:t})=>g(e,t)>0n,`Session amount must be greater than 0`)),K.transform(({amount:e,chainId:t,channelId:n,configurableVouchers:r,decimals:i,escrowContract:a,feePayer:o,feeToken:s,minVoucherDelta:c,operator:l,sessionProtocol:u,sessionSnapshot:d,suggestedDeposit:f,...p})=>({...p,amount:g(e,i).toString(),...f?{suggestedDeposit:g(f,i).toString()}:{},methodDetails:{escrowContract:a,...n!==void 0&&{channelId:n},...c!==void 0&&{minVoucherDelta:g(c,i).toString()},...t!==void 0&&{chainId:t},...o!==void 0&&{feePayer:o},...s!==void 0&&{feeToken:s},...l!==void 0&&{operator:l},...r!==void 0&&{configurableVouchers:r},...u!==void 0&&{[ut.sessionProtocol]:u},...d!==void 0&&{[ut.sessionSnapshot]:d}}})))}}),$c=jn({name:`tempo`,intent:`subscription`,schema:{credential:{payload:K.object({signature:Y(),type:K.literal(`keyAuthorization`)})},request:K.pipe(K.object({amount:q(),accessKey:K.optional(Wc),chainId:K.optional(K.number()),currency:Uc,decimals:K.number(),description:K.optional(K.string()),externalId:K.optional(K.string()),methodDetails:K.optional(Gc),periodCount:Jc,periodUnit:qc,recipient:Uc,subscriptionExpires:Kc}).check(Yc(`Subscription amount must be greater than 0`),K.refine(Xc,`Subscription period exceeds uint64`)),K.transform(({accessKey:e,amount:t,chainId:n,decimals:r,methodDetails:i,subscriptionExpires:a,...o})=>{let s={...i,...e!==void 0&&{accessKey:e},...n!==void 0&&{chainId:n}};return{...o,amount:g(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}}),el=K.object({account:K.optional(K.custom()),autoSwap:K.optional(K.custom()),feeToken:K.optional(K.custom()),mode:K.optional(K.enum(zc))});function tl(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??[])vl(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=Us({chain:R,getClient:e.getClient,rpcUrl:Wr}),i=zs({account:e.account});ul(e.zone);let a=new Map,o=Mn(Zc,{canHandleChallenge({challenge:t}){try{return yl(e,n,t.request),!0}catch{return!1}},context:el,async createCredential(o){let{challenge:s,context:c}=o,l=it(o),u=()=>Error(`The Zone withdrawal this challenge resumes is no longer outstanding. Retry the request to pay it.`);yl(e,n,s.request);let d=s.request.methodDetails?.chainId,f=d??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),p=await r({chainId:f});Ws(p,f);let m=f??p.chain?.id;if(Gs(e.allowedChainIds,m),m===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");d===void 0&&yl(e,n,s.request,m);let{request:h}=s,{amount:g,methodDetails:_}=h,v=_?.supportedModes??[`pull`,`push`],y=e.zone?.client.chain,x=e.zone?e.zone.zoneId??Pc(y?.id??0):void 0,C=y?.sourceId??(y?Fc(y.id):void 0),te=c?.mode??e.mode;if(BigInt(g)>0n&&e.zone&&x!==void 0&&C===m&&v.includes(`push`)&&(te===void 0||te===`push`)&&Mc(_?.zones,x)&&!_?.splits){let r={assertFee:t=>yl(e,n,h,m,t),challenge:s,clientId:t,client:p,origin:ll(Ga(o)),pending:a,zone:e.zone,zoneId:x},i=al(r);if(i)return sl(r,i);if(l?.resume)throw u();if(s.expires&&kn(s.expires,s.id),dl(s.expires,e.zone.settlementTimeoutMs))return il(r)}if(l?.resume)throw u();let ne=i(p,c),re=async t=>await e.resolveAccount?.({account:ne,chainId:m,operation:t})??ne;if(BigInt(g)===0n){let e=await re({kind:`signPaymentProof`});return wn({challenge:s,payload:{signature:await T(p,{account:e,...xc({account:e.address,chainId:m,challengeId:s.id,realm:s.realm})}),type:`proof`},source:Sc({address:e.address,chainId:m})})}let E=h.currency,D=uc({chainId:m,currency:E}),O=_?.memo??Js({challengeId:s.id,clientId:t,serverId:s.realm}),k=nc({amount:g,methodDetails:{..._,memo:O},recipient:h.recipient}),A=k.map(e=>V.token.transfer.call(p,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:E})),j=ec(c?.autoSwap??e.autoSwap,Qs),M=_?.machineTokenEnabled===!0&&!l?dc({chainId:m,currency:E,transfers:k}):void 0,N=ne,P,F=!1;if(M){let e=await(async()=>{try{return await re({calls:M.calls,kind:`executeCalls`})}catch{return}})();e&&(P=await fc(p,{account:e.address,chainId:m,currency:E,transfers:k}),P?N=e:F=!0)}let I;if(!P){if(N=await re({kind:`executeCalls`,...j?{}:{calls:A}}),I=j?await $s(p,{account:N.address,amountOut:BigInt(g),tokenOut:E,tokenIn:j.tokenIn,slippage:j.slippage,maxAmountIn:j.maxAmountIn}):void 0,l&&I)throw new wt({limit:l.limit,reason:`asset`});if(F&&!j){let e=await nl(p,{account:N.address,amount:BigInt(g),chainId:m,currency:E});if(e)throw e}}let L=P?.calls??[...I??[],...A],R=oc(m),z=(c?.feeToken??e.feeToken)||(P||D?await sc({account:N.address,allowedTokens:R,candidateTokens:R,client:p,prioritizeCandidates:!0}):void 0),ie=(()=>{let t=c?.mode??e.mode;if(t){if(!v.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=N.type===`json-rpc`?`push`:`pull`;return v.includes(n)?n:v[0]})(),ae=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!s.expires)return e;let t=Math.floor(new Date(s.expires).getTime()/1e3)+1;return Math.min(e,t)})(),oe=()=>{l&&s.expires&&kn(s.expires,s.id)};if(ie===`push`){oe();let{receipts:e}=N.type===`local`?{receipts:[await Ec({account:N},()=>w(p,{account:N,calls:L,...z?{feeToken:z}:{},nonceKey:`expiring`,validBefore:ae}))]}:await S(p,{account:N,...z?{capabilities:{feeToken:z}}:{},calls:L,experimental_fallback:L.length===1,forceAtomic:L.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Za(Error(`No transaction receipt returned.`));return wn({challenge:s,payload:{hash:t,type:`hash`},source:Sc({address:N.address,chainId:m})})}let B=()=>{if(_?.feePayer!==!0)return;let e=15e3,t=s.expires?new Date(s.expires).getTime():1/0,n=Date.now();if(!(t-n>=e))throw Error(`Sponsored challenge expires in less than 15 seconds; the fee payer would reject the transaction. Request a new challenge.`);if(!(ae*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.`)};B();let se=await Ec({account:N},()=>b(p,{account:N,calls:L,...z?{feeToken:z}:{},nonceKey:`expiring`,validBefore:ae}));if(se.gas=(se.gas??0n)+5000n,_?.feePayer){let e=se;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return B(),oe(),wn({challenge:s,payload:{signature:await ee(p,se),type:`transaction`},source:Sc({address:N.address,chainId:m})})}}),s=new Map,c=async t=>{yl(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,a=it(t),c=s.get(i);if(a&&at(a,c?.constraints),c)return c.promise;let l=o.createCredential(t).finally(()=>s.delete(i));return s.set(i,{constraints:a,promise:l}),l};return tt(Ha({...o,createCredential:c},rl),{assert:t=>yl(e,n,t.request),resumes:t=>ol(a,t,e.zone&&(e.zone.zoneId??Pc(e.zone.client.chain?.id??0)))})}async function nl(e,t){let{account:n,amount:r,chainId:i,currency:a}=t,o=await x(e,V.token.getBalance.call(e,{account:n,token:a})).catch(()=>void 0);if(!(typeof o!=`bigint`||o>=r))return _c(e,{account:n,amount:r,chainId:i})}function rl(e){let t=Zc.schema.credential.payload.safeParse(yn(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`||n.type===`zone`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(ve.serializedType))return;let i=ve.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&ve.serialize(i)===r)return p(r)}function il(e){let{challenge:t,origin:n,pending:r,zoneId:i}=e,a={sent:!1},o={challenge:t,origin:n,terms:ml(t,i),waiters:0,withdrawal:_l(e,a)},s=pl(t);return r.set(s,o),o.withdrawal.catch(()=>{!a.sent&&r.get(s)===o&&r.delete(s)}),sl(e,o)}function al(e){let{challenge:t,pending:n,zoneId:r}=e,i=n.get(pl(t));if(i)return i;let a=ml(t,r);if(a!==void 0){for(let[e,t]of n)if(t.terms===a){if(!gl(t.challenge.expires)){n.delete(e);continue}if(t.redeemedLate)throw new Ct({challengeId:t.challenge.id,senderTags:t.senderTags,zoneId:r});if(!(t.waiters>0))return t}}}function ol(e,t,n){if(n===void 0||e.size===0)return!1;if(e.has(pl(t)))return!0;let r=ml(t,n);if(r===void 0)return!1;for(let t of e.values())if(t.terms===r&&gl(t.challenge.expires)&&(t.redeemedLate||t.waiters===0))return!0;return!1}async function sl(e,t){t.waiters++;try{return await cl(e,t)}finally{t.waiters--}}async function cl(e,t){let{client:n,origin:r,pending:i,zone:a,zoneId:o}=e,{challenge:s}=t,c=s.request.recipient,l=pl(s);if((l===pl(e.challenge)?r!==void 0&&t.origin!==void 0&&r!==t.origin:!r||r!==t.origin)||!gl(s.expires))throw new Ct({challengeId:s.id,zoneId:o});let u=await t.withdrawal,d=u.senderTags??await Lc(a.client,u).catch(e=>{let t=Error(`Zone withdrawal transaction ${u.transactionHash} was sent, but its sender tag could not be read from the Zone. Retry the challenge to resume without withdrawing again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),Za(t)}),f;try{f=await Rc(n,{portal:Nc(o),senderTags:d,timeoutMs:fl(s.expires,a.settlementTimeoutMs),to:c})}catch(e){throw new Ct({cause:e,challengeId:s.id,senderTags:d,zoneId:o})}i.get(l)===t&&(hl(s.expires)?(t.redeemedLate=!0,t.senderTags=[f.senderTag]):i.delete(l));let{hash:p,senderTag:m}=f;return wn({challenge:s,payload:{hash:p,senderTag:m,type:`zone`,zoneId:o}})}function ll(e){if(e)try{let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`?void 0:t.origin}catch{return}}function ul(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||Fc(n)===void 0)return;let r=Pc(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function dl(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+15e3}function fl(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function pl(e){return JSON.stringify(e)}function ml(e,t){let n;try{n=e.opaque===void 0?e.meta:Et(e.opaque)}catch{return}let{digest:r,intent:i,method:a,realm:o,request:s}=e;return G({digest:r,intent:i,meta:An(n),method:a,realm:o,request:s,zoneId:t})}function hl(e){if(!e)return!1;let t=new Date(e).getTime();return!Number.isNaN(t)&&Date.now()>=t}function gl(e){if(!e)return!0;let t=new Date(e).getTime();return Number.isNaN(t)||Date.now()<t+3e5}async function _l(e,t){let{assertFee:n,challenge:r,clientId:i,zone:a}=e,o=r.request,s=a.client.account;if(!s)throw Error("`zone.client` requires an account.");let c=BigInt(o.amount),l=o.currency,u=o.recipient,d=Js({challengeId:r.id,clientId:i,serverId:r.realm}),f=await V.zone.getWithdrawalFee(a.client);n(f);let[,m]=V.zone.requestWithdrawal.calls({amount:c,fallbackRecipient:s.address,memo:d,to:u,token:l}),g=await b(a.client,{account:s,calls:[V.token.approve.call({amount:c+f,spender:ce.zoneOutbox,token:l}),m]}),_=await ee(a.client,g);t.sent=!0;let v=p(_),y=await C(a.client,{serializedTransaction:_}).catch(e=>te(a.client,{hash:v,timeout:15e3}).catch(()=>{let t=new vt({cause:e,transactionHash:v});throw t.message=`Zone withdrawal outcome is unknown: transaction ${v} may have been sent. Retrying this challenge does not withdraw again.`,t}));if(y.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${y.transactionHash} reverted.`);let[x]=h({abi:B.zoneOutbox,eventName:`WithdrawalRequested`,logs:y.logs});return{blockNumber:y.blockNumber,sender:s.address,senderTags:x?[Ic({fallbackNonce:x.args.fallbackNonce,sender:x.args.sender,transactionHash:y.transactionHash})]:void 0,transactionHash:y.transactionHash}}function vl(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo charge maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo charge maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return g(e,t)}}function yl(e,t,n,r,i){let{methodDetails:a,recipient:o}=n,s=a?.chainId;if(e.expectedChainId!==void 0&&s!==void 0&&s!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${s}.`);(s!==void 0||e.allowedChainIds?.length===0)&&Gs(e.allowedChainIds,s);let c=e.currencies?Oe(e.currencies,n.currency,{chainId:s??r??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),decimals:e.decimals}):void 0;if(e.currencies&&!c)throw Error(`Tempo charge currency is not allowed: ${n.currency}.`);if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!o||!t.has(o.toLowerCase()))throw Error(`Unexpected primary recipient: ${o}`);let n=a?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}if(t.maxAtomicAmount===void 0&&t.maxAmount===void 0)return;let l=BigInt(n.amount)+(i??0n),u=i===void 0?`amount exceeds`:`amount plus Zone withdrawal fee exceeds`;if(t.maxAtomicAmount!==void 0&&l>t.maxAtomicAmount)throw Error(`Tempo charge ${u} maxAtomicAmount.`);if(t.maxAmount!==void 0&&l>vl(t.maxAmount,c?.decimals))throw Error(`Tempo charge ${u} maxAmount.`)}const bl=(1n<<96n)-1n;function xl(e){return e>=0n&&e<=bl}function Sl(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return xl(t)?t:void 0}function Cl(e){return wl(e),e}function wl(e){if(!xl(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const Tl=new Set([`open`,`topUp`,`voucher`,`close`]);function El(e){return typeof e==`object`&&!!e}function Dl(e){return typeof e==`string`&&Tl.has(e)}function Ol(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!Dl(t.action))}function kl(e,t=`No session credential context available.`){if(!Ol(e))throw Error(t);return e}function Al(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function jl(e){return El(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function Ml(e){return El(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 Nl(e){let t=D.toString(e),n=JSON.parse(t);if(!Ml(n))throw Error(`Invalid session receipt.`);return n}function Pl(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function Fl(e){let t=`message`,n=[];for(let r of e.split(`
7
+ `))throw Error(`Credential header value contains illegal newline characters`)}async function Ts(e,t,n,r,i){let a=t.context&&n!==void 0?t.context.parse(n):void 0,o=a===void 0?{challenge:e}:{challenge:e,context:a};return i&&rt(o,i),r?.origin&&Wa(o,r.origin),r&&`prepare`in r&&za(t,o,r),t.createCredential(o)}function Es(e,t){let n=e.get(U.acceptPayment);if(!n)return t;try{return{...t,entries:ji(n),header:n}}catch{return t}}async function Ds(e,t){return t?t(e):e}function Os(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=js(e);return t===`same-origin`?!As()||n.origin===globalThis.location.origin:t.origins.some(e=>ks(n,e))}function ks(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 As(){return globalThis.location!==void 0}function js(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,As()?globalThis.location.href:void 0)}function Ms(e){try{return{origin:js(e).origin}}catch{return}}function Ns(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 Ps(e,t,n,r){if(Ns(t,r),!e.url)return t;let i=new URL(e.url),a=js(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 Fs(e){return!(e instanceof Response)||e.status!==402?0:on(e.headers.get(U.wwwAuthenticate))}function Is(e){let{description:t,...n}=e;return j.canonicalize(n)}async function Ls(e,t){if(!(e instanceof globalThis.Response))return!1;if(await ba(e,t))return!0;if(!e.headers.get(`Content-Type`)?.includes(`application/problem+json`))return!1;try{return(await e.clone().json()).type===`https://paymentauth.org/problems/invalid-challenge`}catch{return!1}}function Rs(e){return e.get(U.paymentAuthorization)?!0:/(^|,)\s*Payment\s+\S/i.test(e.get(U.authorization)??``)}function zs(e={}){let{account:t}=e;return(e,{account:n}={})=>{let r=n??t;if(!r){if(!e.account)throw Error("No `account` provided. Pass `account` to parameters or context.");return e.account}return fe(r)}}function Bs(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}const Vs={[R.id]:R,[z.id]:z};function Hs(e,t={}){return u(e.url,{fetchFn:e.fetch,fetchOptions:{headers:Bs(e)},...t})}function Us(r){let{chain:i,getClient:a,remoteFeePayer:o,rpcUrl:s}=r;return a?!i?.serializers&&!o&&!r.requireChain?a:async e=>{let s=await a(e);if(r.requireChain&&(s.chain?.id===void 0||s.chain.id!==e.chainId))throw Error(`Subscription chain mismatch: expected ${e.chainId}, got ${s.chain?.id??`unknown`}.`);let c=s;if(o&&s.transport.key!==`feePayer`){let e=s.request.bind(s),r=de(n({request:t=>e(t)},{retryCount:0}),Hs(o,{retryCount:s.transport.retryCount}))({account:s.account,chain:s.chain,pollingInterval:s.pollingInterval,retryCount:0}),i=t({...r.config,retryCount:0},r.value);c=Object.assign({},s,{request:i.request,transport:{...i.config,...i.value}})}return!i?.serializers||c.chain?.serializers?.transaction?c:Object.assign({},c,{chain:{...i,...e.chainId===void 0?{}:{id:e.chainId},...c.chain,formatters:c.chain?.formatters??i.formatters,prepareTransactionRequest:c.chain?.prepareTransactionRequest??i.prepareTransactionRequest,serializers:c.chain?.serializers?.transaction?c.chain.serializers:i.serializers}})}:({chainId:t})=>{if(!s)throw Error("No `rpcUrl` provided.");let n=t||Number(Object.keys(s)[0]),r=s[n];if(!r)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let a=o?de(u(r),Hs(o)):u(r);return e({chain:Vs[n]??{...i,id:n},transport:a})}}function Ws(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 Gs(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}const Ks=A.slice(k.keccak256(O.fromString(`mpp`),{as:`Hex`}),0,4);function qs(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,10))}function Js(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(A.toBytes(Ks),0),i[4]=1,i.set(qs(t),5),n&&i.set(qs(n),15),i.set(Ys(r),25),A.fromBytes(i)}function Ys(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,7))}function Xs(e,t){return _e.resolve(e).toLowerCase()===_e.resolve(t).toLowerCase()}const Zs=10000n,Qs=[Vr.pathUsd,Vr.usdc,Vr.ousd];async function $s(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||Xs(t,i)||c.some(e=>Xs(e,t))||c.push(t)}let l=await Promise.allSettled([x(e,{...V.token.getBalance.call(e,{account:n,token:i}),account:null}),...c.map(t=>x(e,{...V.token.getBalance.call(e,{account:n,token:t}),account:null}))]),u=l[0];if(u.status!==`fulfilled`)throw u.reason;let d=u.value;if(d>=r)return;let f=r-d,p=BigInt(Math.round(o*100)),m=t.maxAmountIn??f+f*p/Zs;for(let t=0;t<c.length;t++){let n=l[t+1];if(n.status!==`fulfilled`)continue;let r=n.value;if(r<=0n)continue;let a=c[t];try{let t=await V.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:f});if(t<=0n||t>m)continue;let n=t+t*p/Zs,o=n<m?n:m;if(r>=o)return[V.token.approve.call(e,{amount:o,spender:ce.stablecoinDex,token:a}),V.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:f,maxAmountIn:o})]}catch{}}throw new tc({currency:i})}function ec(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`&&Xs(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var tc=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}};function nc(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 rc(e,t,n){t&&(n&&!n.some(e=>Xs(e,t))||e.some(e=>Xs(e,t))||e.push(t))}async function ic(e,t,n){try{return(await V.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function ac(e){let t=e.chain?.feeToken;if(t)return le.toAddress(t);let n=e.chain?.id;return n?Hr[n]:void 0}function oc(e){let t=[];return rc(t,Vr.pathUsd),rc(t,Hr[e]),t}async function sc(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])rc(o,e,n);if(rc(o,await V.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),rc(o,ac(i),n),!a)for(let e of r??[])rc(o,e,n);for(let e of o)if(await ic(i,t,e))return e;return o[0]}const cc=m([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]);function lc(e){if(e!==void 0)return Ur[e]}function uc(e){let t=lc(e.chainId);return!!t&&d(e.currency,{strict:!1})&&f(e.currency,t.token)}function dc(e){let t=lc(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let r=BigInt(n.amount),a=n.memo;return{calls:[{data:i({abi:B.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:i({abi:cc,functionName:`swapTo`,args:[t.token,r,e.currency,n.recipient,a]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:r,memo:a,recipient:n.recipient}]}}async function fc(e,t){let n=dc(t);if(n)try{return await x(e,V.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await _(e,{account:t.account,calls:n.calls}),n)}catch{return}}const pc=10n**BigInt(4);function mc(e={}){let{address:t,amount:n,chainId:r=Z.mainnet}=e;if(r!==Z.mainnet)return;let i=new URL(`https://wallet.tempo.xyz/agent?action=fund&intent=mach&chainId=4217`);if(t&&d(t,{strict:!1})&&i.searchParams.set(`address`,c(t)),n!==void 0&&n>0n){let e=(n+pc-1n)/pc,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 hc(e,t){let n=lc(t.chainId);if(!n)return;let r=await x(e,V.token.getBalance.call(e,{account:t.account,token:n.token})).catch(()=>void 0);return typeof r==`bigint`?r:void 0}async function gc(e,t){let{account:n,amount:r,chainId:i}=t,a=await hc(e,{account:n,chainId:i});if(a===void 0||a>=r)return;let s=e=>`${o(e,6)} MACH`,c=r-a;return{fundingUrl:mc({address:n,amount:c,chainId:i}),reason:`requested ${s(r)}, available ${s(a)}`,shortfall:c}}async function _c(e,t){let n=await gc(e,t);if(n)return new Tt({fundingUrl:n.fundingUrl,reason:n.reason})}const vc={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]};function yc(e){return{name:`MPP`,version:`3`,chainId:e}}function bc(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function xc(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:yc(n),types:vc,primaryType:`Proof`,message:bc({account:t,challengeId:r,realm:i})}}function Sc(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const Cc=[...B.accountKeychain.filter(e=>e.type===`error`),...B.tip20.filter(e=>e.type===`error`)];function wc(e){let t=new Set,n=e;for(;typeof n==`object`&&n&&!t.has(n);){t.add(n);let e=n.data;if(Dc(e))return e;let r=e?.data;if(Dc(r))return r;n=n.cause}}function Tc(e,t){let n=wc(e);if(!n)return;let i=(()=>{try{return r({abi:Cc,data:n})}catch{return}})();if(i?.errorName===`SpendingLimitExceeded`){let n=t.account.accessKeyAddress;return new St({accessKey:typeof n==`string`?n:void 0,account:t.account.address,cause:e})}if(i?.errorName===`InsufficientBalance`){let[n,r,a]=i.args;return new Tt({cause:e,reason:`${t.account.address} holds ${n} of token ${a}, but the payment requires ${r}`})}}async function Ec(e,t){try{return await t()}catch(t){throw Tc(t,e)??t}}function Dc(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{8}/.test(e)}const Oc=7200n,kc=64n,Ac=s({abi:B.zonePortal,name:`WithdrawalProcessed`});function jc(e){return Number.isInteger(e)&&e>0&&e<4217e5}function Mc(e,t){return jc(t)?e===!0||(e?.includes(t)??!1):!1}function Nc(e){return ce.zonePortal(e)}Nc(0).slice(0,-16).toLowerCase();function Pc(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 Fc(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 Ic(e){return k.keccak256(E.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function Lc(e,t){let{blockNumber:n,sender:r,transactionHash:i}=t,a=t=>x(e,{abi:B.zoneOutbox,address:ce.zoneOutbox,blockNumber:t,functionName:`lastFallbackNonce`}),[o,s]=await Promise.all([a(n-1n),a(n)]);if(s<=o)throw Error(`Zone withdrawal transaction ${i} did not request a withdrawal from the outbox.`);if(s-o>kc)throw Error(`Zone withdrawal transaction ${i} has ${s-o} candidate sender tags, more than ${kc}.`);let c=[];for(let e=o+1n;e<=s;e++)c.push(Ic({fallbackNonce:e,sender:r,transactionHash:i}));return c}async function Rc(e,t){let{senderTags:n,timeoutMs:r=6e4}=t;if(!Number.isFinite(r)||r<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);if(n.length===0)throw Error(`Zone settlement needs at least one sender tag.`);let i=await v(e,{cacheTime:0}),a=i>Oc?i-Oc:0n,o=Date.now()+r;for(;;){if(a<=i){let[r]=await y(e,{address:t.portal,event:Ac,args:{senderTag:[...n],...t.to?{to:t.to}:{}},fromBlock:a,toBlock:i});if(r?.transactionHash&&r.args.senderTag)return{hash:r.transactionHash,senderTag:r.args.senderTag};a=i+1n}if(Date.now()+500>o)throw Error(`Zone withdrawal ${n.join(` or `)} did not settle on Tempo within ${r}ms.`);await new Promise(e=>setTimeout(e,500)),i=await v(e,{cacheTime:0})}}const zc=[`push`,`pull`],Bc=K.object({amount:q(),memo:K.optional(Mt()),recipient:K.pipe(K.string(),K.transform(e=>e))}),Vc=(1n<<64n)-1n,Hc={dev_second:1n,day:86400n,week:604800n},Uc=K.pipe(J(),K.transform(e=>e.toLowerCase())),Wc=K.object({accessKeyAddress:Uc,keyType:K.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:K.optional(K.pipe(K.string().check(K.regex(/^0x[0-9a-fA-F]{120}$/)),K.transform(e=>e)))}),Gc=K.object({accessKey:K.optional(Wc),chainId:K.optional(K.number())}),Kc=kt(`subscriptionExpires must be a valid date`).check(K.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),qc=K.enum([`dev_second`,`day`,`week`]),Jc=K.pipe(K.union([K.string(),K.bigint(),K.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),K.transform(e=>e.toString())).check(K.regex(/^[1-9]\d*$/,`Invalid periodCount`),K.refine(e=>{try{return BigInt(e)<=Vc}catch{return!1}},`periodCount exceeds uint64`));function Yc(e){return K.refine(e=>{let{amount:t,decimals:n}=e;return g(t,n)>0n},e)}function Xc(e){let{periodCount:t,periodUnit:n}=e;try{let e=Hc[n];return e!==void 0&&BigInt(t)*e<=Vc}catch{return!1}}const Zc=jn({name:`tempo`,intent:`charge`,schema:{credential:{payload:K.discriminatedUnion(`type`,[K.object({hash:Mt(),type:K.literal(`hash`)}),K.object({signature:Y(),type:K.literal(`transaction`)}),K.object({signature:Y(),type:K.literal(`proof`)}),K.object({hash:Mt(),senderTag:Mt(),type:K.literal(`zone`),zoneId:K.number().check(K.refine(jc,`Invalid Zone ID`))})])},request:K.pipe(K.object({machineTokenEnabled:K.optional(K.boolean()),amount:q(),chainId:K.optional(K.number()),currency:K.string(),decimals:K.number(),description:K.optional(K.string()),externalId:K.optional(K.string()),feePayer:K.optional(K.pipe(K.union([K.boolean(),K.custom()]),K.transform(e=>typeof e==`object`||e))),memo:K.optional(K.never()),recipient:K.optional(K.string()),splits:K.optional(K.array(Bc).check(K.minLength(1),K.maxLength(10))),supportedModes:K.optional(K.array(K.enum(zc)).check(K.minLength(1))),zones:K.optional(K.union([K.literal(!0),K.array(K.number().check(K.refine(jc,`Invalid Zone ID`))).check(K.minLength(1))]))}).check(K.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=g(e,t),i=n.reduce((e,n)=>e+g(n.amount,t),0n);return n.every(e=>g(e.amount,t)>0n)&&i<r},`Invalid splits`)),K.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,zones:c,...l})=>({...l,amount:g(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0||c!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:g(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),Qc=jn({name:`tempo`,intent:`session`,schema:{credential:{payload:K.discriminatedUnion(`action`,[K.object({action:K.literal(`open`),authorizedSigner:K.optional(K.string()),channelId:Mt(),cumulativeAmount:q(),descriptor:K.optional(K.custom()),signature:Y(),transaction:Y(),type:K.literal(`transaction`)}),K.object({action:K.literal(`topUp`),additionalDeposit:q(),channelId:Mt(),descriptor:K.optional(K.custom()),transaction:Y(),type:K.literal(`transaction`)}),K.object({action:K.literal(`voucher`),channelId:Mt(),cumulativeAmount:q(),descriptor:K.optional(K.custom()),signature:Y()}),K.object({action:K.literal(`close`),channelId:Mt(),closeSignature:Y(),cumulativeAmount:q(),descriptor:K.optional(K.custom()),signature:Y()})])},request:K.pipe(K.object({amount:q(),chainId:K.optional(K.number()),channelId:K.optional(Mt()),configurableVouchers:K.optional(K.boolean()),currency:K.string(),decimals:K.number(),escrowContract:K.optional(K.string()),feePayer:K.optional(K.pipe(K.union([K.boolean(),K.custom()]),K.transform(e=>typeof e==`object`||e))),feeToken:K.optional(J()),minVoucherDelta:K.optional(q()),operator:K.optional(J()),recipient:K.optional(K.string()),sessionProtocol:K.optional(K.enum([dt.v2,dt.v1])),sessionSnapshot:K.optional(K.custom()),suggestedDeposit:K.optional(q()),unitType:K.string()}).check(K.refine(({amount:e,decimals:t})=>g(e,t)>0n,`Session amount must be greater than 0`)),K.transform(({amount:e,chainId:t,channelId:n,configurableVouchers:r,decimals:i,escrowContract:a,feePayer:o,feeToken:s,minVoucherDelta:c,operator:l,sessionProtocol:u,sessionSnapshot:d,suggestedDeposit:f,...p})=>({...p,amount:g(e,i).toString(),...f?{suggestedDeposit:g(f,i).toString()}:{},methodDetails:{escrowContract:a,...n!==void 0&&{channelId:n},...c!==void 0&&{minVoucherDelta:g(c,i).toString()},...t!==void 0&&{chainId:t},...o!==void 0&&{feePayer:o},...s!==void 0&&{feeToken:s},...l!==void 0&&{operator:l},...r!==void 0&&{configurableVouchers:r},...u!==void 0&&{[ut.sessionProtocol]:u},...d!==void 0&&{[ut.sessionSnapshot]:d}}})))}}),$c=jn({name:`tempo`,intent:`subscription`,schema:{credential:{payload:K.object({signature:Y(),type:K.literal(`keyAuthorization`)})},request:K.pipe(K.object({amount:q(),accessKey:K.optional(Wc),chainId:K.optional(K.number()),currency:Uc,decimals:K.number(),description:K.optional(K.string()),externalId:K.optional(K.string()),methodDetails:K.optional(Gc),periodCount:Jc,periodUnit:qc,recipient:Uc,subscriptionExpires:Kc}).check(Yc(`Subscription amount must be greater than 0`),K.refine(Xc,`Subscription period exceeds uint64`)),K.transform(({accessKey:e,amount:t,chainId:n,decimals:r,methodDetails:i,subscriptionExpires:a,...o})=>{let s={...i,...e!==void 0&&{accessKey:e},...n!==void 0&&{chainId:n}};return{...o,amount:g(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}}),el=K.object({account:K.optional(K.custom()),autoSwap:K.optional(K.custom()),feeToken:K.optional(K.custom()),mode:K.optional(K.enum(zc))});function tl(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??[])vl(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=Us({chain:R,getClient:e.getClient,rpcUrl:Wr}),i=zs({account:e.account});ul(e.zone);let a=new Map,o=Mn(Zc,{canHandleChallenge({challenge:t}){try{yl(e,n,t.request);let{amount:r,methodDetails:i}=t.request,a=i?.supportedModes;return!(i?.memo!==void 0&&a&&!a.includes(`pull`)&&BigInt(r)>0n)}catch{return!1}},context:el,async createCredential(o){let{challenge:s,context:c}=o,l=it(o),u=()=>Error(`The Zone withdrawal this challenge resumes is no longer outstanding. Retry the request to pay it.`);yl(e,n,s.request);let d=s.request.methodDetails?.chainId,f=d??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),p=await r({chainId:f});Ws(p,f);let m=f??p.chain?.id;if(Gs(e.allowedChainIds,m),m===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");d===void 0&&yl(e,n,s.request,m);let{request:h}=s,{amount:g,methodDetails:_}=h,v=_?.supportedModes??[`pull`,`push`],y=e.zone?.client.chain,x=e.zone?e.zone.zoneId??Pc(y?.id??0):void 0,C=y?.sourceId??(y?Fc(y.id):void 0),te=c?.mode??e.mode;if(BigInt(g)>0n&&e.zone&&x!==void 0&&C===m&&v.includes(`push`)&&(te===void 0||te===`push`)&&Mc(_?.zones,x)&&!_?.splits){let r={assertFee:t=>yl(e,n,h,m,t),challenge:s,clientId:t,client:p,origin:ll(Ga(o)),pending:a,zone:e.zone,zoneId:x},i=al(r);if(i)return sl(r,i);if(l?.resume)throw u();if(s.expires&&kn(s.expires,s.id),dl(s.expires,e.zone.settlementTimeoutMs))return il(r)}if(l?.resume)throw u();let ne=i(p,c),re=async t=>await e.resolveAccount?.({account:ne,chainId:m,operation:t})??ne;if(BigInt(g)===0n){let e=await re({kind:`signPaymentProof`});return wn({challenge:s,payload:{signature:await T(p,{account:e,...xc({account:e.address,chainId:m,challengeId:s.id,realm:s.realm})}),type:`proof`},source:Sc({address:e.address,chainId:m})})}let E=h.currency,D=uc({chainId:m,currency:E}),O=_?.memo??Js({challengeId:s.id,clientId:t,serverId:s.realm}),k=nc({amount:g,methodDetails:{..._,memo:O},recipient:h.recipient}),A=k.map(e=>V.token.transfer.call(p,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:E})),j=ec(c?.autoSwap??e.autoSwap,Qs),M=_?.machineTokenEnabled===!0&&!l?dc({chainId:m,currency:E,transfers:k}):void 0,N=ne,P,F=!1;if(M){let e=await(async()=>{try{return await re({calls:M.calls,kind:`executeCalls`})}catch{return}})();e&&(P=await fc(p,{account:e.address,chainId:m,currency:E,transfers:k}),P?N=e:F=!0)}let I;if(!P){if(N=await re({kind:`executeCalls`,...j?{}:{calls:A}}),I=j?await $s(p,{account:N.address,amountOut:BigInt(g),tokenOut:E,tokenIn:j.tokenIn,slippage:j.slippage,maxAmountIn:j.maxAmountIn}):void 0,l&&I)throw new wt({limit:l.limit,reason:`asset`});if(F&&!j){let e=await nl(p,{account:N.address,amount:BigInt(g),chainId:m,currency:E});if(e)throw e}}let L=P?.calls??[...I??[],...A],R=oc(m),z=(c?.feeToken??e.feeToken)||(P||D?await sc({account:N.address,allowedTokens:R,candidateTokens:R,client:p,prioritizeCandidates:!0}):void 0),ie=(()=>{let t=c?.mode??e.mode,n=_?.memo!==void 0;if(t){if(!v.includes(t))throw Error(`Challenge does not support ${t} mode.`);if(n&&t===`push`)throw Error(`Push mode is not supported for a challenge with a memo.`);return t}if(n){if(!v.includes(`pull`))throw Error(`Challenge has a memo but does not support pull mode.`);return`pull`}let r=N.type===`json-rpc`?`push`:`pull`;return v.includes(r)?r:v[0]})(),ae=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!s.expires)return e;let t=Math.floor(new Date(s.expires).getTime()/1e3)+1;return Math.min(e,t)})(),oe=()=>{l&&s.expires&&kn(s.expires,s.id)};if(ie===`push`){oe();let{receipts:e}=N.type===`local`?{receipts:[await Ec({account:N},()=>w(p,{account:N,calls:L,...z?{feeToken:z}:{},nonceKey:`expiring`,validBefore:ae}))]}:await S(p,{account:N,...z?{capabilities:{feeToken:z}}:{},calls:L,experimental_fallback:L.length===1,forceAtomic:L.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Za(Error(`No transaction receipt returned.`));return wn({challenge:s,payload:{hash:t,type:`hash`},source:Sc({address:N.address,chainId:m})})}let B=()=>{if(_?.feePayer!==!0)return;let e=15e3,t=s.expires?new Date(s.expires).getTime():1/0,n=Date.now();if(!(t-n>=e))throw Error(`Sponsored challenge expires in less than 15 seconds; the fee payer would reject the transaction. Request a new challenge.`);if(!(ae*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.`)};B();let se=await Ec({account:N},()=>b(p,{account:N,calls:L,...z?{feeToken:z}:{},nonceKey:`expiring`,validBefore:ae}));if(se.gas=(se.gas??0n)+5000n,_?.feePayer){let e=se;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return B(),oe(),wn({challenge:s,payload:{signature:await ee(p,se),type:`transaction`},source:Sc({address:N.address,chainId:m})})}}),s=new Map,c=async t=>{yl(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,a=it(t),c=s.get(i);if(a&&at(a,c?.constraints),c)return c.promise;let l=o.createCredential(t).finally(()=>s.delete(i));return s.set(i,{constraints:a,promise:l}),l};return tt(Ha({...o,createCredential:c},rl),{assert:t=>yl(e,n,t.request),resumes:t=>ol(a,t,e.zone&&(e.zone.zoneId??Pc(e.zone.client.chain?.id??0)))})}async function nl(e,t){let{account:n,amount:r,chainId:i,currency:a}=t,o=await x(e,V.token.getBalance.call(e,{account:n,token:a})).catch(()=>void 0);if(!(typeof o!=`bigint`||o>=r))return _c(e,{account:n,amount:r,chainId:i})}function rl(e){let t=Zc.schema.credential.payload.safeParse(yn(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`||n.type===`zone`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(ve.serializedType))return;let i=ve.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&ve.serialize(i)===r)return p(r)}function il(e){let{challenge:t,origin:n,pending:r,zoneId:i}=e,a={sent:!1},o={challenge:t,origin:n,terms:ml(t,i),waiters:0,withdrawal:_l(e,a)},s=pl(t);return r.set(s,o),o.withdrawal.catch(()=>{!a.sent&&r.get(s)===o&&r.delete(s)}),sl(e,o)}function al(e){let{challenge:t,pending:n,zoneId:r}=e,i=n.get(pl(t));if(i)return i;let a=ml(t,r);if(a!==void 0){for(let[e,t]of n)if(t.terms===a){if(!gl(t.challenge.expires)){n.delete(e);continue}if(t.redeemedLate)throw new Ct({challengeId:t.challenge.id,senderTags:t.senderTags,zoneId:r});if(!(t.waiters>0))return t}}}function ol(e,t,n){if(n===void 0||e.size===0)return!1;if(e.has(pl(t)))return!0;let r=ml(t,n);if(r===void 0)return!1;for(let t of e.values())if(t.terms===r&&gl(t.challenge.expires)&&(t.redeemedLate||t.waiters===0))return!0;return!1}async function sl(e,t){t.waiters++;try{return await cl(e,t)}finally{t.waiters--}}async function cl(e,t){let{client:n,origin:r,pending:i,zone:a,zoneId:o}=e,{challenge:s}=t,c=s.request.recipient,l=pl(s);if((l===pl(e.challenge)?r!==void 0&&t.origin!==void 0&&r!==t.origin:!r||r!==t.origin)||!gl(s.expires))throw new Ct({challengeId:s.id,zoneId:o});let u=await t.withdrawal,d=u.senderTags??await Lc(a.client,u).catch(e=>{let t=Error(`Zone withdrawal transaction ${u.transactionHash} was sent, but its sender tag could not be read from the Zone. Retry the challenge to resume without withdrawing again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),Za(t)}),f;try{f=await Rc(n,{portal:Nc(o),senderTags:d,timeoutMs:fl(s.expires,a.settlementTimeoutMs),to:c})}catch(e){throw new Ct({cause:e,challengeId:s.id,senderTags:d,zoneId:o})}i.get(l)===t&&(hl(s.expires)?(t.redeemedLate=!0,t.senderTags=[f.senderTag]):i.delete(l));let{hash:p,senderTag:m}=f;return wn({challenge:s,payload:{hash:p,senderTag:m,type:`zone`,zoneId:o}})}function ll(e){if(e)try{let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`?void 0:t.origin}catch{return}}function ul(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||Fc(n)===void 0)return;let r=Pc(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function dl(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+15e3}function fl(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function pl(e){return JSON.stringify(e)}function ml(e,t){let n;try{n=e.opaque===void 0?e.meta:Et(e.opaque)}catch{return}let{digest:r,intent:i,method:a,realm:o,request:s}=e;return G({digest:r,intent:i,meta:An(n),method:a,realm:o,request:s,zoneId:t})}function hl(e){if(!e)return!1;let t=new Date(e).getTime();return!Number.isNaN(t)&&Date.now()>=t}function gl(e){if(!e)return!0;let t=new Date(e).getTime();return Number.isNaN(t)||Date.now()<t+3e5}async function _l(e,t){let{assertFee:n,challenge:r,clientId:i,zone:a}=e,o=r.request,s=a.client.account;if(!s)throw Error("`zone.client` requires an account.");let c=BigInt(o.amount),l=o.currency,u=o.recipient,d=Js({challengeId:r.id,clientId:i,serverId:r.realm}),f=await V.zone.getWithdrawalFee(a.client);n(f);let[,m]=V.zone.requestWithdrawal.calls({amount:c,fallbackRecipient:s.address,memo:d,to:u,token:l}),g=await b(a.client,{account:s,calls:[V.token.approve.call({amount:c+f,spender:ce.zoneOutbox,token:l}),m]}),_=await ee(a.client,g);t.sent=!0;let v=p(_),y=await C(a.client,{serializedTransaction:_}).catch(e=>te(a.client,{hash:v,timeout:15e3}).catch(()=>{let t=new vt({cause:e,transactionHash:v});throw t.message=`Zone withdrawal outcome is unknown: transaction ${v} may have been sent. Retrying this challenge does not withdraw again.`,t}));if(y.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${y.transactionHash} reverted.`);let[x]=h({abi:B.zoneOutbox,eventName:`WithdrawalRequested`,logs:y.logs});return{blockNumber:y.blockNumber,sender:s.address,senderTags:x?[Ic({fallbackNonce:x.args.fallbackNonce,sender:x.args.sender,transactionHash:y.transactionHash})]:void 0,transactionHash:y.transactionHash}}function vl(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo charge maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo charge maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return g(e,t)}}function yl(e,t,n,r,i){let{methodDetails:a,recipient:o}=n,s=a?.chainId;if(e.expectedChainId!==void 0&&s!==void 0&&s!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${s}.`);(s!==void 0||e.allowedChainIds?.length===0)&&Gs(e.allowedChainIds,s);let c=e.currencies?Oe(e.currencies,n.currency,{chainId:s??r??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),decimals:e.decimals}):void 0;if(e.currencies&&!c)throw Error(`Tempo charge currency is not allowed: ${n.currency}.`);if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!o||!t.has(o.toLowerCase()))throw Error(`Unexpected primary recipient: ${o}`);let n=a?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}if(t.maxAtomicAmount===void 0&&t.maxAmount===void 0)return;let l=BigInt(n.amount)+(i??0n),u=i===void 0?`amount exceeds`:`amount plus Zone withdrawal fee exceeds`;if(t.maxAtomicAmount!==void 0&&l>t.maxAtomicAmount)throw Error(`Tempo charge ${u} maxAtomicAmount.`);if(t.maxAmount!==void 0&&l>vl(t.maxAmount,c?.decimals))throw Error(`Tempo charge ${u} maxAmount.`)}const bl=(1n<<96n)-1n;function xl(e){return e>=0n&&e<=bl}function Sl(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return xl(t)?t:void 0}function Cl(e){return wl(e),e}function wl(e){if(!xl(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const Tl=new Set([`open`,`topUp`,`voucher`,`close`]);function El(e){return typeof e==`object`&&!!e}function Dl(e){return typeof e==`string`&&Tl.has(e)}function Ol(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!Dl(t.action))}function kl(e,t=`No session credential context available.`){if(!Ol(e))throw Error(t);return e}function Al(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function jl(e){return El(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function Ml(e){return El(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 Nl(e){let t=D.toString(e),n=JSON.parse(t);if(!Ml(n))throw Error(`Invalid session receipt.`);return n}function Pl(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function Fl(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
9
  `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=Il(r);return jl(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=Il(r);return Ml(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function Il(e){try{return JSON.parse(e)}catch{return null}}function Ll(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function Rl(){return JSON.stringify({mpp:`payment-close-request`})}function zl(e){let t=Bl(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`&&Ml(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`&&jl(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&Ml(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function Bl(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}const Vl=`0x4d50500000000000000000000000000000000000`;function Hl(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function Ul(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 Wl(e){return ve.encodeForSigning(e)}function Gl(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function Kl(e,t){return k.keccak256(A.concat(Wl(e),t.sender))}const ql=[{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`}],Jl=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],Yl={name:`descriptor`,type:`tuple`,components:ql},Xl=[{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:[Yl,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[Yl,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[Yl,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[Yl],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[Yl],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[Yl],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:ql},{name:`state`,type:`tuple`,components:Jl}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:Jl}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:Jl}]},{type:`function`,name:`computeChannelId`,stateMutability:`view`,inputs:[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`getVoucherDigest`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`verifyVoucher`,stateMutability:`view`,inputs:[Yl,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[{name:`valid`,type:`bool`}]},{type:`function`,name:`domainSeparator`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`event`,name:`ChannelOpened`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`authorizedSigner`,type:`address`},{name:`salt`,type:`bytes32`},{name:`expiringNonceHash`,type:`bytes32`},{name:`deposit`,type:`uint96`}]},{type:`event`,name:`OpeningCommitmentRecorded`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`signer`,type:`address`,indexed:!0},{name:`commitment`,type:`bytes32`}]},{type:`event`,name:`Settled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`cumulativeAmount`,type:`uint96`},{name:`deltaPaid`,type:`uint96`},{name:`newSettled`,type:`uint96`}]},{type:`event`,name:`TopUp`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`additionalDeposit`,type:`uint96`},{name:`newDeposit`,type:`uint96`}]},{type:`event`,name:`CloseRequested`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`closeGraceEnd`,type:`uint256`}]},{type:`event`,name:`ChannelClosed`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`settledToPayee`,type:`uint96`},{name:`refundedToPayer`,type:`uint96`}]},{type:`event`,name:`CloseRequestCancelled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0}]},{type:`error`,name:`RootKeyRetired`,inputs:[{name:`account`,type:`address`}]},{type:`error`,name:`SignerConfigChanged`,inputs:[{name:`signer`,type:`address`}]},{type:`error`,name:`SaltNotSignerCommitment`,inputs:[{name:`signer`,type:`address`},{name:`commitment`,type:`bytes32`}]}];function Zl(e){return e.type===`secp256k1`?e.signature.s<=57896044618658097711785492504343953926418782139537452191302581570759080747168n:e.type===`p256`||e.type===`webAuthn`?e.signature.s<=57896044605178124381348723474703786764998477612067880171211129530534256022184n:!0}function Ql(e){if(e.type===`configurable`)return{...e,signatures:e.signatures.map(e=>Ql(e))};if(Zl(e))return e;if(e.type===`secp256k1`){let{r:t,s:n,yParity:r}=e.signature;return{...e,signature:{r:t,s:115792089237316195423570985008687907852837564279074904382605163141518161494337n-n,yParity:+(r===0)}}}return e.type===`p256`||e.type===`webAuthn`?{...e,signature:{...e.signature,s:115792089210356248762697446949407573529996955224135760342422259061068512044369n-e.signature.s}}:e}function $l(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function eu(e){return e===void 0||BigInt(e)===0n}function tu(e,t){let{account:n,config:r,signatures:i}=e,a=me.getSignPayload({account:n,config:r,payload:t}),o=Number(r.threshold),s,c=0,l;for(let[e,t]of i.entries()){if(!$l(t.type)||!Zl(t)||e>0&&c>=o)return!1;let n=H.extractAddress({payload:a,signature:t});if(!H.verify(t,{address:n,payload:a}))return!1;let i=r.owners.find(e=>Xs(e.owner,n));if(!i)return!1;let u=Number(i.weight);if(u===0)return!1;let d=BigInt(n);if(s!==void 0&&s>=d)return!1;s=d,c+=u,l=l===void 0?u:Math.min(l,u)}return!(i.length===0||c<o||l!==void 0&&c>=o+l)}function nu(e,t){let{account:n,commitment:r,payload:i}=t;if(!Xs(e.account,n)||BigInt(e.config.version??0n)===0n&&e.config.owners.some(({owner:t})=>Xs(t,e.account)))return!1;if(eu(r)){if(BigInt(e.config.version??0n)!==0n||!Xs(me.getAddress(e.config),n))return!1}else if(me.getCommitment(e.config).toLowerCase()!==r.toLowerCase())return!1;return tu(e,i)}function ru(e,t){return{name:`TIP20 Channel Reserve`,version:`1`,chainId:t,verifyingContract:e}}const iu={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},au={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]};function ou(e,t,n){return l({domain:ru(e,t),types:au,primaryType:`CloseAuthorization`,message:n})}function su(e,t){return he.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function cu(e,t,n){return e.toLowerCase()===he.address.toLowerCase()?su(t,n):l({domain:ru(e,t),types:iu,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function lu(e,t,n,r){let i=uu(e);return i?du(i,t,n,r):!1}function uu(e){let t=H.from(e);if(H.serialize(t).toLowerCase()===e.toLowerCase())return t}function du(e,t,n,r){if(e.type===`configurable`)return r.configurable?nu(e,{account:n,commitment:r.openingCommitment,payload:t}):!1;if(!$l(e.type)||!Zl(e)||!eu(r.openingCommitment))return!1;let i=H.extractAddress({payload:t,signature:e});return H.verify(e,{address:i,payload:t})&&Xs(i,n)}function fu(e){return e.source===`configurable`}function pu(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function mu(e,t){return se.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function hu(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===he.address.toLowerCase())try{return await mu(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return T(e,{account:t,domain:ru(r,i),types:iu,primaryType:`Voucher`,message:n})})(),o=H.from(a);if(!$l(o.type)&&o.type!==`configurable`)throw Error(`TIP-1034 vouchers require a TIP-1020 primitive or TIP-1166 configurable account signature; received "${o.type}".`);return H.serialize(Ql(o))}async function gu(e,t,n,r,i){let a=pu(t)?await t.sign({hash:ou(r,i,n),raw:!0}):await T(e,{account:t,domain:ru(r,i),types:au,primaryType:`CloseAuthorization`,message:n}),o=H.from(a);if(!$l(o.type)&&o.type!==`configurable`)throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive or TIP-1166 configurable account signature; received "${o.type}".`);return H.serialize(Ql(o))}function _u(e,t,n,r,i={}){try{let a=cu(e,t,n);return lu(n.signature,a,r,i)}catch{return!1}}function vu(e){return typeof e==`object`&&!!e}function yu(e){return typeof e==`string`&&d(e,{strict:!1})?e:void 0}function bu(e){return yu(e.accessKeyAddress)}function xu(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(A.random(8))%e)}function Su(e){return bu(e)??e.address}function Cu(e){return wu(e)!==void 0}function wu(e){let t=bu(e);if(t===void 0)return fu(e)?e:void 0;let n=e.delegate;if(n&&fu(n)&&n.address.toLowerCase()===t.toLowerCase())return n}async function Tu(e,t){let n=wu(t);if(!n)return A.random(32);let{config:r}=n,i=await V.accounts.getConfigCommitment(e,{account:n.address}),a=r?me.getCommitment(r):void 0;if(BigInt(i)!==0n){if(a&&a.toLowerCase()!==i.toLowerCase())throw Error(`Configurable account ${n.address} holds a config whose commitment ${a} does not match its on-chain commitment ${i}. Use the account's current config.`);return i}if(!a||BigInt(r.version??0n)!==0n)throw Error(`Configurable account ${n.address} is not registered, so it needs its version-zero config to open a channel.`);return a}function Eu(e,t){let n=wc(e);if(n)try{let i=r({abi:Xl,data:n});if(i.errorName!==`SignerConfigChanged`&&i.errorName!==`RootKeyRetired`)return;let[a]=i.args;return a.toLowerCase()===t.signer.toLowerCase()?new xt({cause:e,channelId:t.channelId,reason:i.errorName,signer:a}):void 0}catch{return}}async function Du(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return Ec({account:n},()=>b(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}}))}async function Ou(e,t){return await ee(e,t)}function ku(e,t,n=!1){let r=e.request.methodDetails,i=vu(r)?yu(r.escrowContract)??yu(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!ju(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!ju(i,a)?i:a}function Au(e,t,n,r){return wn({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${t.descriptor?.payer??r.address}`})}function ju(e,t){return e.toLowerCase()===t.toLowerCase()}function Mu(e,t){let n=wu(e);if(!n?.config)return;let{config:r}=n;if(me.getCommitment(r).toLowerCase()!==t.salt.toLowerCase()&&(BigInt(r.version??0n)!==0n||me.getAddress(r).toLowerCase()!==n.address.toLowerCase()))throw Error(`Configurable account ${n.address} holds a config that does not match the channel's opening commitment (salt ${t.salt}), so it cannot sign a voucher the channel settles. Sign with the config the channel opened with, or close the channel and open a new one.`)}async function Nu(e,t,n,r,i,a=Vl){let o=Ul({...n,chainId:i,escrow:a}),s=Cl(r);Mu(t,n);let c=await hu(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function Pu(e,t,n,r,i,a=Vl){let o=await Nu(e,t,n,r,i,a),s=await gu(e,t,{channelId:o.channelId,cumulativeAmount:Cl(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function Fu(e,t,n){let r=Su(t),a=n.escrow??`0x4d50500000000000000000000000000000000000`,o=n.operator??`0x0000000000000000000000000000000000000000`,s=n.salt??await Tu(e,t),c=Cl(n.deposit),l=Cl(n.initialAmount),u=i({abi:Xl,functionName:`open`,args:[n.payee,o,n.token,c,s,r]}),d=await Ou(e,await Du(e,{account:t,calls:[...n.prefixCalls??[],{to:a,data:u}],feePayer:n.feePayer,feeToken:n.feeToken??n.token,validAfter:xu()})),f=ue.deserialize(d),p={authorizedSigner:r,expiringNonceHash:Kl(Gl({...n.feePayer?{feePayer:!0}:{},transaction:f}),{sender:t.address}),operator:o,payee:n.payee,payer:t.address,salt:s,token:n.token},m=Ul({...p,chainId:n.chainId,escrow:a});return{action:`open`,type:`transaction`,channelId:m,transaction:d,signature:await hu(e,t,{channelId:m,cumulativeAmount:l},a,n.chainId),descriptor:p,cumulativeAmount:l.toString(),authorizedSigner:p.authorizedSigner}}async function Iu(e,t,n,r,a,o,s=Vl,c=[],l=n.token){let u=Ul({...n,chainId:a,escrow:s}),d=Cl(r);return{action:`topUp`,type:`transaction`,channelId:u,transaction:await Ou(e,await Du(e,{account:t,calls:[...c,{to:s,data:i({abi:Xl,functionName:`topUp`,args:[n,d]})}],feePayer:o,feeToken:l,validAfter:xu()}).catch(e=>{throw Eu(e,{channelId:u,signer:Hl(n)})??e})),descriptor:n,additionalDeposit:d.toString()}}function Lu(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Q(e){return Lu({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function Ru(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Q(t),t)},delete(t){e.delete(t)}}}const zu=new WeakMap,Bu=new WeakMap;function Vu(e,t){Bu.set(e,Bu.get(t)??t)}async function Hu(e,t,n){let r=zu.get(e);r||(r=new Map,zu.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 Uu(e,t,n){return Hu(Bu.get(e)??e,`funding:${t}`,n)}async function Wu(e,t){await Hu(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 Gu(e,t){await Hu(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}const Ku=2n**96n-1n;function qu(e){if(e<0n||e>Ku)throw new W({reason:`amount exceeds uint96 range`})}async function Ju(e,t,n=Vl){let{cumulativeAmount:r,descriptor:i,signature:a}=t;return x(e,{address:n,abi:Xl,functionName:`verifyVoucher`,args:[Zu(i),r,a]})}async function Yu(e,t,n=Vl,r){return Xu(await x(e,{address:n,abi:Xl,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function Xu(e){return qu(e.settled),qu(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}function Zu(e){return{payer:e.payer,payee:e.payee,operator:e.operator,token:e.token,salt:e.salt,authorizedSigner:e.authorizedSigner,expiringNonceHash:e.expiringNonceHash}}const Qu=K.custom(e=>typeof e==`string`&&d(e,{strict:!1})),$u=K.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),ed=K.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),td=K.object({authorizedSigner:Qu,expiringNonceHash:$u,operator:Qu,payee:Qu,payer:Qu,salt:$u,token:Qu}),nd=Nn(K.object({acceptedCumulative:K.string(),chainId:K.number(),channelId:$u,closeRequestedAt:K.optional(K.string()),deposit:K.string(),descriptor:td,escrow:Qu,highestVoucher:K.optional(K.object({channelId:$u,cumulativeAmount:K.string(),signature:ed})),requiredCumulative:K.string(),settled:K.string(),spent:K.string(),units:K.optional(K.number())}));function rd(e){return nd.encode(e)}function id(e){return nd.decode(e)}const ad={status:`idle`};function od(e){return{status:`active`,...e}}function sd(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:ud(e.challengeId,t.snapshot),effects:[]}:$(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Cd({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:dd(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:$(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Ed(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?ld({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:dd(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:dd(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 cd(e,t){let n=sd(e.state,t);return e.state=n.state,n}function ld(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 ud(e,t){return od({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function dd(e,t,n,r){return od({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 fd(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function pd(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`);fd({cumulativeAmount:i,maxVoucherCumulative:n}),fd({cumulativeAmount:a,maxVoucherCumulative:n})}function md(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;pd({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function hd(e,t){return typeof e==`bigint`?e:g(e,t)}function gd(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(vd(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 _d(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;fd({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 vd(e,t){fd({cumulativeAmount:e,maxVoucherCumulative:t??null})}function yd(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 bd(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function xd(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!xl(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>bd({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function Sd(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=Sl(r),s=Sl(a.spent);return o===void 0||s===void 0||!xl(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function Cd(e){return od({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 wd(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:ad}}function Td(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=md({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&cd(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function Ed(e,t){return od({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function Dd(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=Sl(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 Od(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 sd(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function kd(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 Ad(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 jd(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(Rl()),e.waitForCloseReady()))(),a=BigInt(i.spent);xd({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=>Sd({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(Ll(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}function Md(e){return`cumulativeAmount`in e}function Nd(e){if(Md(e))return BigInt(e.cumulativeAmount)}async function Pd(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await Wu(e.store,t):await Gu(e.store,Q(t)),e.notifyUpdate(t)}async function Fd(e,t,n){let r=Nd(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 Pd(e,i))}const Id=K.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),Ld=K.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),Rd=K.object({account:K.optional(K.custom()),autoSwap:K.optional(K.custom()),action:K.optional(K.enum([`open`,`topUp`,`voucher`,`close`])),channelId:K.optional(Ld),cumulativeAmount:K.optional(q()),cumulativeAmountRaw:K.optional(K.string()),transaction:K.optional(Id),descriptor:K.optional(K.custom()),additionalDeposit:K.optional(q()),additionalDepositRaw:K.optional(K.string()),depositRaw:K.optional(K.string())});function zd(e){return e?.action!==void 0}function Bd(e){return zd(e)&&e.descriptor!==void 0}function Vd(e,t,n){let r=n===`additionalDeposit`?e.additionalDepositRaw:e.cumulativeAmountRaw,i=n===`additionalDeposit`?e.additionalDeposit:e.cumulativeAmount;if(r)return BigInt(r);if(i)return g(i,t)}function Hd(e,t,n,r){let i=Vd(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function Ud(e){return typeof e==`object`&&!!e}function Wd(e){return typeof e==`string`&&d(e,{strict:!1})?e:void 0}function Gd(e){let t=e.request.methodDetails;return Ud(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:Wd(t.escrowContract),escrow:Wd(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:Wd(t.feeToken),operator:Wd(t.operator),configurableVouchers:typeof t.configurableVouchers==`boolean`?t.configurableVouchers:void 0,sessionSnapshot:ft(t,ut.sessionSnapshot)}:{}}function Kd(e,t){if(typeof e==`string`&&d(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function qd(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function Jd(e){return typeof e==`string`?e:void 0}async function Yd(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=Gd(n);(o.chainId!==void 0||i?.length===0)&&Gs(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});Ws(c,s);let l=s??c.chain?.id;if(Gs(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=ku(n,r,t),d=Kd(n.request.recipient,`recipient`),f=Kd(n.request.currency,`currency`);return{amount:qd(n.request.amount),challenge:n,chainId:l,client:c,...o.configurableVouchers===void 0?{}:{configurableVouchers:o.configurableVouchers},escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:Lu({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:Jd(n.request.suggestedDeposit),token:f}}async function Xd(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=Yu}=e,o=Ul({...r,chainId:i.chainId,escrow:i.escrow});Zd({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 Zd(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(!ju(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!ju(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!ju(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!ju(Hl(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function Qd(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function $d(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=Vd(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function ef(e){let{account:t,client:n,readChannelState:r,snapshot:i,verifyVoucherOnChain:a=Ju}=e,o=i.highestVoucher;if(!o)throw Error(`session snapshot is missing its highest signed voucher`);if(o.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let s=BigInt(i.acceptedCumulative),c=BigInt(o.cumulativeAmount),l=BigInt(i.requiredCumulative),u=BigInt(i.deposit),d=BigInt(i.settled),f=BigInt(i.spent);if(c!==s)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(f>s)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(d>u)throw Error(`session snapshot settled amount exceeds deposit`);let p={channelId:o.channelId,cumulativeAmount:c,signature:o.signature},m=Hl(i.descriptor),h=Cu(t);if(!(_u(i.escrow,i.chainId,p,m,h?{configurable:!0,openingCommitment:i.descriptor.salt}:{})||h&&await a(n,{descriptor:i.descriptor,cumulativeAmount:c,signature:p.signature},i.escrow).catch(()=>!1)))throw Error(`session snapshot highest voucher signature is invalid`);let g=await Xd({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:Su(t),token:i.descriptor.token},readChannelState:r}),_=[s,l,g.state.settled].reduce((e,t)=>t>e?t:e,0n);if(_>g.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:g.channelId,cumulativeAmount:_,deposit:g.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:f}}function tf(e,t){return ju(e.address,t.payer)?ju(Su(e),Hl(t)):!1}function nf(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(zd(r)){if(!Bd(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=Qd({context:r,snapshot:o.snapshot});return!n&&s&&tf(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&tf(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 rf(e,t,n=!1){switch(e.type){case`open`:return sf(e,t,n);case`recover`:return cf(e,t);case`voucher`:return lf(e,t);case`manual`:return uf(e,t,n)}}async function af(e,t){if(e)return await $s(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function of(e,t){let{account:n,amount:r,chainId:i,client:a,token:o}=t;if(e||!uc({chainId:i,currency:o}))return;let s=await _c(a,{account:n,amount:r,chainId:i});if(s)throw s}async function sf(e,t,n){let{account:r,resolved:i}=e;if(Cu(r)&&i.configurableVouchers!==!0)throw new bt({signer:r.address});let a=gd({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw});await of(n,{account:r.address,amount:a,chainId:i.chainId,client:i.client,token:i.token});let o=await Fu(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 af(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await Pd(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function cf(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await Xd({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:Su(n),token:o.token}}),l=$d({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`);vd(l,a);let u=await Nu(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await Pd(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 lf(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;vd(a,e.maxDeposit);let o=await Nu(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await Pd(t,r),o}async function uf(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=Ul({...s,chainId:o.chainId,escrow:o.escrow});Zd({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:Su(r),token:o.token});let l=await df({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await Fd(t,o.key,l),l}async function df(e,t){switch(e.context.action){case`open`:return ff(e);case`topUp`:return pf(e,t);case`voucher`:return mf(e);case`close`:return hf(e)}}async function ff(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=Hd(r,i,`cumulativeAmount`,`open`),c=await Nu(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 pf(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=Hd(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:(await of(t,{account:n.address,amount:c,chainId:s.chainId,client:s.client,token:s.token}),Iu(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await af(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken))}function mf(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Nu(a.client,t,i,Hd(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function hf(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Pu(a.client,t,i,Hd(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}const gf={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function _f(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=gf.CLOSED,r=null}if(a.type===`open`&&(i=gf.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 vf(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function yf(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=hd(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 bf(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:Ed(s,u)}:i?{channel:u,state:Cd({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function xf(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=vf(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:Cl(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function Sf(e){return e.method===ct.tempo&&e.intent===lt.session}function Cf(e){return Sf(e)&&ft(e.request.methodDetails,ut.sessionProtocol)===dt.v2}function wf(e){return ft(e.request.methodDetails,ut.sessionSnapshot)}function Tf(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return na({...t,redirect:`manual`,headers:{...Xo(i),...Xo(t?.headers)}},un(r),n)}function Ef(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 Df(e){try{let t=typeof location>`u`?void 0:location.href,n=Ef(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function Of(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function kf(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 Af=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 jf(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 Mf({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 Af&&(t.uncertainTopUp=!0,await e.onUncertainFunding?.(t)),n});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(U.paymentReceipt);return i?Nl(i):void 0}async function Mf(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(Df(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:np(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new Af(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=nn(n).find(Cf);return r?t(r):n}async function Nf(e){let t=Pf({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,Tf(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(U.paymentReceipt)&&await l(),u}function Pf(e){let t=nn(e.response).find(Cf);if(!t)return;let n=wf(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function Ff(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=Ef(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?Df(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:np(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=nn(o).find(Cf);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await kf(o),t=o.headers.get(U.wwwAuthenticate)??``;throw Error(`Close request failed with status ${o.status}${e?`: ${e}`:``}${t?` [${U.wwwAuthenticate}: ${t}]`:``}`)}let s=o.headers.get(U.paymentReceipt);if(!s)return;let c=Nl(s);if(!c.txHash||!A.validate(c.txHash,{strict:!0})||A.size(c.txHash)!==32||!Sd({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 If(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...Xo(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!Pl(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),Lf(e,c,{onReceipt:r,signal:o},n,s.headers)}function Lf(e,t,n,r,i){if(!Pl(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return Rf({onNeedVoucher:t=>Uf({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*Rf(e){for await(let t of zf(e))t.data!==void 0&&(yield t.data)}async function*zf(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=Bf(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=Fl(i.replace(/\r\n|\r/g,`
10
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 Bf(e,t){for(let n=0;n<e.length;n++){let r=Vf(e,n,t);if(!r)continue;let i=Vf(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function Vf(e,t,n){return e[t]===`
@@ -1,5 +1,5 @@
1
1
  /** Current mppx package version. */
2
- export declare const version = "0.22.1";
2
+ export declare const version = "0.22.2";
3
3
  /** Canonical SDK identifier for this mppx release. */
4
- export declare const sdkIdentifier = "mppx/0.22.1";
4
+ export declare const sdkIdentifier = "mppx/0.22.2";
5
5
  //# sourceMappingURL=version.d.ts.map
@@ -1,6 +1,6 @@
1
1
  // Generated by scripts/sync-version.ts.
2
2
  /** Current mppx package version. */
3
- export const version = '0.22.1';
3
+ export const version = '0.22.2';
4
4
  /** Canonical SDK identifier for this mppx release. */
5
5
  export const sdkIdentifier = `mppx/${version}`;
6
6
  //# sourceMappingURL=version.js.map
@@ -83,6 +83,15 @@ export function charge(parameters = {}) {
83
83
  canHandleChallenge({ challenge }) {
84
84
  try {
85
85
  assertChallengePolicy(parameters, caps, challenge.request);
86
+ // A challenge with a server memo can't be paid by push, so one that takes only push
87
+ // can't be paid at all: leave it for another offer.
88
+ const { amount, methodDetails } = challenge.request;
89
+ const modes = methodDetails?.supportedModes;
90
+ if (methodDetails?.memo !== undefined &&
91
+ modes &&
92
+ !modes.includes('pull') &&
93
+ BigInt(amount) > 0n)
94
+ return false;
86
95
  return true;
87
96
  }
88
97
  catch {
@@ -299,11 +308,21 @@ export function charge(parameters = {}) {
299
308
  : undefined;
300
309
  const mode = (() => {
301
310
  const explicitMode = context?.mode ?? parameters.mode;
311
+ // A server memo is shared by every payer of a route, so the server refuses a pushed payment
312
+ // that carries it: pay such a challenge with a transaction.
313
+ const serverMemo = methodDetails?.memo !== undefined;
302
314
  if (explicitMode) {
303
315
  if (!supportedModes.includes(explicitMode))
304
316
  throw new Error(`Challenge does not support ${explicitMode} mode.`);
317
+ if (serverMemo && explicitMode === 'push')
318
+ throw new Error('Push mode is not supported for a challenge with a memo.');
305
319
  return explicitMode;
306
320
  }
321
+ if (serverMemo) {
322
+ if (!supportedModes.includes('pull'))
323
+ throw new Error('Challenge has a memo but does not support pull mode.');
324
+ return 'pull';
325
+ }
307
326
  const preferredMode = account.type === 'json-rpc' ? 'push' : 'pull';
308
327
  if (supportedModes.includes(preferredMode))
309
328
  return preferredMode;
@@ -206,6 +206,13 @@ export declare namespace charge {
206
206
  type ExpectedTransfer = {
207
207
  amount: string;
208
208
  allowAnyMemo?: boolean | undefined;
209
+ /**
210
+ * Push payments: whether a memo is this challenge's attribution memo. Matching prefers such a
211
+ * transfer and skips one carrying another challenge's attribution memo.
212
+ */
213
+ isBound?: ((memo: `0x${string}`) => boolean) | undefined;
214
+ /** The transfer must carry this challenge's attribution memo (the primary of a push payment). */
215
+ requireBound?: boolean | undefined;
209
216
  memo?: `0x${string}` | undefined;
210
217
  recipient: `0x${string}`;
211
218
  };
@@ -186,11 +186,19 @@ export function charge(parameters = {}) {
186
186
  const { amount, chainId, challenge, client, currency, methodDetails, recipient, settlementSenders, supportedModes, } = context;
187
187
  if (supportedModes && !supportedModes.includes('push'))
188
188
  throw new MismatchError('Hash credentials are not supported for this challenge.', {});
189
+ // Read from the signed Challenge, which can differ from the route's current request.
190
+ const offered = credential.challenge.request.methodDetails;
191
+ // A server memo is shared by every payer of a route, so it can't bind a pushed transfer
192
+ // to the client that claims it.
193
+ if (offered?.memo !== undefined)
194
+ throw new MismatchError('Hash credentials are not supported for a challenge with a memo.', {});
189
195
  const source = parseHashCredentialSource({
190
196
  chainId: chainId ?? client.chain?.id,
191
197
  source: credential.source,
192
198
  });
193
- const transfers = getExpectedTransfers({ amount, methodDetails, recipient });
199
+ // Only a primary transfer carrying this challenge's attribution memo counts toward it.
200
+ const isBound = boundMemoMatcher({ challengeId: challenge.id, realm: challenge.realm });
201
+ const transfers = getExpectedTransfers({ amount, isBound, methodDetails, recipient });
194
202
  const receipt = await getTransactionReceipt(client, {
195
203
  hash: payload.hash,
196
204
  });
@@ -209,6 +217,11 @@ export function charge(parameters = {}) {
209
217
  realm: challenge.realm,
210
218
  required: true,
211
219
  });
220
+ // A counted transfer without this challenge's attribution memo (a plain split) isn't tied to
221
+ // it, so another challenge paid in the same transaction could count it again once this hash
222
+ // claim expires. Count such a transfer only when the transaction pays no other challenge.
223
+ if (matchedLogs.some((log) => log.kind !== 'memo' || !isBound(log.args.memo)))
224
+ assertNoOtherChallenge(receipt, { currency, isBound });
212
225
  // The payer is the account the matched transfers debited, not the submitter.
213
226
  // Settlement-contract transfers are funded by the transaction sender.
214
227
  const payers = new Set(matchedLogs.map(({ args }) => (settlementSenders.some((settlementSender) => TempoAddress.isEqual(settlementSender, args.from))
@@ -955,6 +968,11 @@ function chargeBinding(request) {
955
968
  zones,
956
969
  };
957
970
  }
971
+ /**
972
+ * The transfers a charge expects. With isBound (push payments), the primary transfer must carry
973
+ * this challenge's attribution memo, and no transfer counts one carrying another challenge's,
974
+ * so transfers for other challenges in the same transaction are skipped rather than matched.
975
+ */
958
976
  function getExpectedTransfers(parameters) {
959
977
  return Charge_internal.getTransfers({
960
978
  amount: parameters.amount,
@@ -962,10 +980,17 @@ function getExpectedTransfers(parameters) {
962
980
  splits: parameters.methodDetails?.splits,
963
981
  },
964
982
  recipient: parameters.recipient,
965
- }).map((transfer) => ({
966
- ...transfer,
967
- ...(!transfer.memo ? { allowAnyMemo: true } : {}),
968
- }));
983
+ }).map((transfer, index) => {
984
+ const { isBound } = parameters;
985
+ // Matching checks requireBound first; allowAnyMemo keeps the fee-payer route check accepting it.
986
+ if (index === 0 && isBound)
987
+ return { ...transfer, allowAnyMemo: true, isBound, requireBound: true };
988
+ return {
989
+ ...transfer,
990
+ ...(!transfer.memo ? { allowAnyMemo: true } : {}),
991
+ ...(isBound ? { isBound } : {}),
992
+ };
993
+ });
969
994
  }
970
995
  function assertTransferCalls(calls, parameters) {
971
996
  const transferCalls = getTransferCalls(calls);
@@ -977,9 +1002,11 @@ function assertTransferCalls(calls, parameters) {
977
1002
  // Match memo-specific transfers before wildcards to avoid greedy
978
1003
  // consumption of memo-bearing calls by allowAnyMemo entries.
979
1004
  const sorted = [...parameters.transfers].sort((a, b) => {
980
- if (a.memo && !b.memo)
1005
+ const aSpecific = !!(a.memo || a.requireBound);
1006
+ const bSpecific = !!(b.memo || b.requireBound);
1007
+ if (aSpecific && !bSpecific)
981
1008
  return -1;
982
- if (!a.memo && b.memo)
1009
+ if (!aSpecific && bSpecific)
983
1010
  return 1;
984
1011
  return 0;
985
1012
  });
@@ -996,6 +1023,8 @@ function assertTransferCalls(calls, parameters) {
996
1023
  return false;
997
1024
  if (decoded.amount !== expected.amount)
998
1025
  return false;
1026
+ if (expected.requireBound)
1027
+ return !!decoded.memo && !!expected.isBound?.(decoded.memo);
999
1028
  if (expected.memo) {
1000
1029
  return decoded.memo?.toLowerCase() === expected.memo.toLowerCase();
1001
1030
  }
@@ -1057,14 +1086,20 @@ async function assertTransferLogs(receipt, parameters) {
1057
1086
  // Match memo-specific transfers before wildcards to avoid greedy
1058
1087
  // consumption of memo-bearing logs by allowAnyMemo entries.
1059
1088
  const sorted = [...parameters.transfers].sort((a, b) => {
1060
- if (a.memo && !b.memo)
1089
+ const aSpecific = !!(a.memo || a.requireBound);
1090
+ const bSpecific = !!(b.memo || b.requireBound);
1091
+ if (aSpecific && !bSpecific)
1061
1092
  return -1;
1062
- if (!a.memo && b.memo)
1093
+ if (!aSpecific && bSpecific)
1063
1094
  return 1;
1064
1095
  return 0;
1065
1096
  });
1066
1097
  for (const transfer of sorted) {
1067
1098
  let matchIndex = -1;
1099
+ // An eligible transfer without this challenge's attribution memo, used when none carries it.
1100
+ let fallbackIndex = -1;
1101
+ // A transfer with the right amount and recipient whose memo isn't bound to this challenge.
1102
+ let unboundIndex = -1;
1068
1103
  for (const [index, log] of logs.entries()) {
1069
1104
  if (used.has(index))
1070
1105
  continue;
@@ -1074,19 +1109,34 @@ async function assertTransferLogs(receipt, parameters) {
1074
1109
  continue;
1075
1110
  if (log.args.amount.toString() !== transfer.amount)
1076
1111
  continue;
1112
+ const memo = log.kind === 'memo' ? log.args.memo : undefined;
1113
+ const bound = !!memo && !!transfer.isBound?.(memo);
1077
1114
  const memoMatches = (() => {
1115
+ if (transfer.requireBound)
1116
+ return bound;
1078
1117
  if (transfer.memo)
1079
- return log.kind === 'memo' && log.args.memo.toLowerCase() === transfer.memo.toLowerCase();
1118
+ return !!memo && memo.toLowerCase() === transfer.memo.toLowerCase();
1119
+ // Another challenge's attribution memo never counts toward this one.
1120
+ if (transfer.isBound && memo && Attribution.isMppMemo(memo) && !bound)
1121
+ return false;
1080
1122
  if (transfer.allowAnyMemo)
1081
- return log.kind === 'transfer' || log.kind === 'memo';
1123
+ return true;
1082
1124
  return log.kind === 'transfer';
1083
1125
  })();
1084
- if (!memoMatches)
1126
+ if (!memoMatches) {
1127
+ if (transfer.isBound && !transfer.memo && unboundIndex === -1)
1128
+ unboundIndex = index;
1085
1129
  continue;
1130
+ }
1086
1131
  // A Zone portal's payout settles a Zone withdrawal, which pays only through its `zone`
1087
1132
  // credential, so the same settlement can't also be redeemed by transaction hash.
1088
1133
  if (Zone.isPortalAddress(log.args.from))
1089
1134
  continue;
1135
+ // A wildcard prefers a transfer carrying this challenge's attribution memo: keep the first
1136
+ // usable one without it as a fallback, and don't check the sender of any later one.
1137
+ const fallback = !!transfer.isBound && !transfer.requireBound && !transfer.memo && !bound;
1138
+ if (fallback && fallbackIndex !== -1)
1139
+ continue;
1090
1140
  if (!(await isValidTransferSender({
1091
1141
  expectedSender: parameters.sender,
1092
1142
  sender: log.args.from,
@@ -1096,10 +1146,18 @@ async function assertTransferLogs(receipt, parameters) {
1096
1146
  validateSender: parameters.validateSender,
1097
1147
  })))
1098
1148
  continue;
1149
+ if (fallback) {
1150
+ fallbackIndex = index;
1151
+ continue;
1152
+ }
1099
1153
  matchIndex = index;
1100
1154
  break;
1101
1155
  }
1156
+ if (matchIndex === -1)
1157
+ matchIndex = fallbackIndex;
1102
1158
  if (matchIndex === -1) {
1159
+ if (unboundIndex !== -1)
1160
+ throw new MismatchError('Payment verification failed: memo is not bound to this challenge.', {});
1103
1161
  throw new MismatchError('Payment verification failed: no matching transfer found.', {
1104
1162
  amount: transfer.amount,
1105
1163
  currency: parameters.currency,
@@ -1111,6 +1169,36 @@ async function assertTransferLogs(receipt, parameters) {
1111
1169
  }
1112
1170
  return matched;
1113
1171
  }
1172
+ /**
1173
+ * Returns whether a memo is an attribution memo bound to this challenge's realm and ID, whatever
1174
+ * its client. The expected segments are hashed once, not per transfer.
1175
+ */
1176
+ function boundMemoMatcher(binding) {
1177
+ const expected = Attribution.encode({
1178
+ challengeId: binding.challengeId,
1179
+ serverId: binding.realm,
1180
+ }).toLowerCase();
1181
+ const server = expected.slice(12, 32);
1182
+ const nonce = expected.slice(52);
1183
+ return (memo) => {
1184
+ if (!Attribution.isMppMemo(memo))
1185
+ return false;
1186
+ const lower = memo.toLowerCase();
1187
+ return lower.slice(12, 32) === server && lower.slice(52) === nonce;
1188
+ };
1189
+ }
1190
+ /**
1191
+ * Rejects a transaction that carries an attribution memo for any other challenge, in any realm.
1192
+ * @internal
1193
+ */
1194
+ function assertNoOtherChallenge(receipt, parameters) {
1195
+ for (const log of getTransferLogEffects(receipt)) {
1196
+ if (log.kind !== 'memo' || !TempoAddress.isEqual(log.address, parameters.currency))
1197
+ continue;
1198
+ if (Attribution.isMppMemo(log.args.memo) && !parameters.isBound(log.args.memo))
1199
+ throw new MismatchError('Payment verification failed: memo is not bound to this challenge.', {});
1200
+ }
1201
+ }
1114
1202
  function getTransferLogEffects(receipt) {
1115
1203
  const transferLogs = parseEventLogs({
1116
1204
  abi: Abis.tip20,