mppx 0.22.0 → 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.
Files changed (32) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/cli/account.d.ts +2 -1
  3. package/dist/cli/account.js +22 -11
  4. package/dist/cli/cli.js +18 -18
  5. package/dist/cli/plugins/index.js +12 -12
  6. package/dist/extensions/identity/attestation/client/index.js +1 -0
  7. package/dist/extensions/identity/attestation/server/index.js +1 -0
  8. package/dist/extensions/identity/email-otp/server/index.js +1 -0
  9. package/dist/extensions/identity/erc8004/client/index.js +1 -0
  10. package/dist/extensions/identity/erc8004/server/index.js +3 -1
  11. package/dist/extensions/identity/link/server/index.js +1 -0
  12. package/dist/extensions/identity/poppy/server/index.js +1 -0
  13. package/dist/extensions/identity/tempo/client/index.js +1 -0
  14. package/dist/extensions/identity/tempo/server/index.js +7 -1
  15. package/dist/extensions/identity/world/server/index.js +1 -0
  16. package/dist/identity/Headers.d.ts +3 -2
  17. package/dist/identity/Headers.js +3 -2
  18. package/dist/identity/Server.d.ts +8 -0
  19. package/dist/identity/Server.js +18 -0
  20. package/dist/identity/Types.d.ts +16 -2
  21. package/dist/internal/version.d.ts +2 -2
  22. package/dist/internal/version.js +1 -1
  23. package/dist/proxy/Proxy.js +59 -46
  24. package/dist/proxy/internal/Headers.d.ts +9 -2
  25. package/dist/proxy/internal/Headers.js +16 -3
  26. package/dist/server/Mppx.d.ts +2 -0
  27. package/dist/server/Mppx.js +1 -0
  28. package/dist/tempo/client/Charge.js +19 -0
  29. package/dist/tempo/server/Charge.d.ts +7 -0
  30. package/dist/tempo/server/Charge.js +100 -12
  31. package/dist/tempo/server/internal/html.gen.js +1 -1
  32. package/package.json +1 -1
package/dist/cli/cli.js CHANGED
@@ -234,26 +234,26 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
234
234
  `?2:t+1===e.length&&!n?0:1:0}function Mj(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=kj({...e,signal:t.signal}),i=new TextEncoder,a=new Headers(e.response.headers);a.delete(`content-length`);let o=()=>e.signal?.removeEventListener(`abort`,n),s=new Response(new ReadableStream({async pull(e){try{let t=await r.next();if(t.done)return o(),e.close();e.enqueue(i.encode(t.value.raw))}catch(e){throw o(),e}},async cancel(){o(),t.abort(),await r.return(void 0)}}),{headers:a,status:e.response.status,statusText:e.response.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{configurable:!0,get:()=>e.response[t]});return s}async function Nj(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await fj({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,headers:e.headers,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await Sj({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,headers:e.headers,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function Pj(e){let t=new URL(e.input.toString()),n=yj(t);e.onProbeUrl?.(n);let r=await e.fetch(n,{...e.probeInit,...e.signal?{signal:e.signal}:{}});if(r.status!==402)throw Error(`Expected a 402 payment challenge from ${n}, received ${r.status} instead.`);let i=RS(r).find(mj);if(!i)throw Error(`No payment challenge received from HTTP endpoint for this WebSocket URL. The server may not require payment or did not advertise a challenge.`);return{challenge:i,httpUrl:n,wsUrl:t}}async function Fj(e){e.signal?.throwIfAborted();let t=await Pj(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function Ij(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:cC(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:lA(t)}}function Lj(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function Rj(e){if(!Lj(e))return`received mismatched payment-close-ready frame`;let t=nA(e.receipt.spent);if(t===void 0)return`received invalid payment-close-ready spend`;if(t>e.cumulativeAmount)return`received payment-close-ready beyond local voucher state`}function zj(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!Lj(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!XA({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function Bj(e){let{challenge:t,credential:n,options:r,WebSocket:i,wsUrl:a}=e,o=r?.signal;o?.throwIfAborted();let s=new i(a,r?.protocols),c=Ij({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=cj(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===qj.CONNECTING||s.readyState===qj.OPEN)&&s.close(Jj,t)},d=()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),s.close()};s.addEventListener(`close`,t=>{o?.removeEventListener(`abort`,d),c.socket=null,c.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),l.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),s.addEventListener(`error`,()=>{l.emit(`error`,{type:`error`})}),s.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await Hj({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await Vj(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(gA(n)),await e.waitForReceipt(),l.socket}function Vj(e,t,n,r){return new Promise((i,a)=>{let o=()=>{e.removeEventListener(`open`,s),e.removeEventListener(`error`,c),e.removeEventListener(`close`,c),r?.removeEventListener(`abort`,l)},s=()=>{o(),t(`open`,{type:`open`}),i()},c=()=>{o(),a(Error(`WebSocket connection to ${n} failed to open.`))},l=()=>{o(),a(r?.reason)};e.addEventListener(`open`,s,{once:!0}),e.addEventListener(`error`,c,{once:!0}),e.addEventListener(`close`,c,{once:!0}),r?.addEventListener(`abort`,l,{once:!0}),r?.aborted&&l()})}async function Hj(e){let t=vA(e.message);if(!t){e.managedEmit(`message`,{data:e.message,type:`message`});return}switch(t.mpp){case`authorization`:return;case`message`:e.socketState.deliveredChunks+=1n,e.managedEmit(`message`,{data:t.data,type:`message`});return;case`payment-close-ready`:Uj(e,t.data);return;case`payment-error`:e.driver.rejectReceipt(Error(t.message)),e.driver.rejectCloseReady(Error(t.message));return;case`payment-need-voucher`:await Wj(e,t.data);return;case`payment-receipt`:Gj(e,t.data);return}}function Uj(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=Rj({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,cumulativeAmount:n,receipt:t});if(r){e.failSocketFlow(r);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleCloseReady(t),e.managedEmit(`close`,{code:1e3,reason:`stream complete`,type:`close`,wasClean:!0})}async function Wj(e,t){try{let n=e.driver.challenge;n.expires&&new Date(n.expires).getTime()<=Date.now()+Yj&&(n=await e.driver.refreshChallenge(),e.driver.challenge=n,e.socketState.challenge=n);let r=await fj({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:n,event:t,expectedChannelId:e.socketState.channelId,getChannel:e.driver.getChannel,input:e.driver.httpUrl,signal:e.driver.options?.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status===`ignored`){e.failSocketFlow(r.reason===`channel-mismatch`?`received mismatched payment-need-voucher frame`:`cannot create voucher: no active channel`);return}let i=await e.driver.createSessionCredential(n,r.context);e.rawSocket.send(gA(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function Gj(e,t){let n=zj({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,expectedCloseAmount:e.socketState.expectedCloseAmount,receipt:t});if(n){e.failSocketFlow(n);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleReceipt(t)}function Kj(e,t,n,r){let i=GS(e),a=new Headers;if(i.toLowerCase()!==q.authorization.toLowerCase()){let e=new Headers(r).get(q.authorization)??(n instanceof Request?n.headers.get(q.authorization):null);e&&!e.startsWith(`${Bx.payment} `)&&a.set(q.authorization,e)}return a.set(i,t),a}var qj,Jj,Yj,Xj,Zj=z((()=>{sC(),DO(),lT(),Gx(),vC(),CA(),sj(),qj={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},Jj=3008,Yj=5e3,Xj=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`}}})),X,Qj=z((()=>{X=(()=>{let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes(`--no-color`))&&(!!n.FORCE_COLOR||t.includes(`--color`)||(e.stdout||{}).isTTY&&n.TERM!==`dumb`||!!n.CI),i=(e,t,n,r)=>{let i=``,a=0,o=r;do i+=e.substring(a,o)+n,a=o+t.length,o=e.indexOf(t,a);while(~o);return i+e.substring(a)},a=r?(e,t,n=e)=>r=>{let a=`${r}`,o=a.indexOf(t,e.length);return~o?e+i(a,t,n,o)+t:e+a+t}:()=>String;return{isColorSupported:r,reset:a(`\x1B[0m`,`\x1B[0m`),bold:a(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:a(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:a(`\x1B[3m`,`\x1B[23m`),underline:a(`\x1B[4m`,`\x1B[24m`),inverse:a(`\x1B[7m`,`\x1B[27m`),hidden:a(`\x1B[8m`,`\x1B[28m`),strikethrough:a(`\x1B[9m`,`\x1B[29m`),black:a(`\x1B[30m`,`\x1B[39m`),red:a(`\x1B[31m`,`\x1B[39m`),green:a(`\x1B[32m`,`\x1B[39m`),yellow:a(`\x1B[33m`,`\x1B[39m`),blue:a(`\x1B[34m`,`\x1B[39m`),magenta:a(`\x1B[35m`,`\x1B[39m`),cyan:a(`\x1B[36m`,`\x1B[39m`),white:a(`\x1B[37m`,`\x1B[39m`),gray:a(`\x1B[90m`,`\x1B[39m`),bgBlack:a(`\x1B[40m`,`\x1B[49m`),bgRed:a(`\x1B[41m`,`\x1B[49m`),bgGreen:a(`\x1B[42m`,`\x1B[49m`),bgYellow:a(`\x1B[43m`,`\x1B[49m`),bgBlue:a(`\x1B[44m`,`\x1B[49m`),bgMagenta:a(`\x1B[45m`,`\x1B[49m`),bgCyan:a(`\x1B[46m`,`\x1B[49m`),bgWhite:a(`\x1B[47m`,`\x1B[49m`),blackBright:a(`\x1B[90m`,`\x1B[39m`),redBright:a(`\x1B[91m`,`\x1B[39m`),greenBright:a(`\x1B[92m`,`\x1B[39m`),yellowBright:a(`\x1B[93m`,`\x1B[39m`),blueBright:a(`\x1B[94m`,`\x1B[39m`),magentaBright:a(`\x1B[95m`,`\x1B[39m`),cyanBright:a(`\x1B[96m`,`\x1B[39m`),whiteBright:a(`\x1B[97m`,`\x1B[39m`),bgBlackBright:a(`\x1B[100m`,`\x1B[49m`),bgRedBright:a(`\x1B[101m`,`\x1B[49m`),bgGreenBright:a(`\x1B[102m`,`\x1B[49m`),bgYellowBright:a(`\x1B[103m`,`\x1B[49m`),bgBlueBright:a(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:a(`\x1B[105m`,`\x1B[49m`),bgCyanBright:a(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:a(`\x1B[107m`,`\x1B[49m`),link(e,t,n){return r?`\x1b]8;;${e}\x07${n?t:X.underline(t)}\x1b]8;;\x07`:t}}})()})),$j,eM,tM,nM,rM,iM,aM=z((()=>{$j={mainnet:4217,testnet:42431},eM={ousd:we($j.mainnet).address,usdc:I(Ee($j.mainnet).address),pathUsd:Te($j.mainnet).address},tM={[$j.mainnet]:eM.usdc,[$j.testnet]:eM.pathUsd},nM=Object.freeze({[$j.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[$j.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})}),rM=`https://wallet.tempo.xyz/agent?action=fund&intent=mach&chainId=4217`,$j.mainnet,$j.testnet,iM={[$j.mainnet]:`https://rpc.tempo.xyz`,[$j.testnet]:`https://rpc.moderato.tempo.xyz`}})),oM=it({chainName:()=>CM,confirm:()=>vM,decodeMemo:()=>uM,fetchBalanceLines:()=>DM,fetchTokenInfo:()=>EM,fmtBalance:()=>yM,fmtChallengeValue:()=>dM,fmtProblemValue:()=>fM,fmtRequestValue:()=>lM,isAgentEnvironment:()=>hM,isTempoAccount:()=>gM,isTestnet:()=>TM,link:()=>pM,mainnetTokens:()=>MM,networkRpcUrls:()=>kM,parseMethodOpts:()=>mM,pathUsd:()=>AM,pc:()=>X,printRequestHeaders:()=>sM,printResponseHeaders:()=>cM,prompt:()=>_M,resolveChain:()=>SM,resolveFundingNetwork:()=>xM,resolveRpcUrl:()=>bM,testnetTokens:()=>NM,usdc:()=>jM});function sM(e,t,n){let{pathname:r,host:i}=new URL(e);n(`> ${(t.method??`GET`).toUpperCase()} ${r} HTTP/1.1\n`),n(`> Host: ${i}\n`);for(let[e,r]of Object.entries(t.headers??{}))n(`> ${e}: ${r}\n`);n(`>
235
235
  `)}function cM(e,t){if(!t.include&&t.verbose<2||t.silent)return;let n=`HTTP/1.1 ${e.status} ${e.statusText}`,r=t.verbose>=2?process.stderr:process.stdout,i=t.verbose>=2?`< `:``;r.write(`${i}${n}\n`);for(let[t,n]of e.headers)r.write(`${i}${t}: ${n}\n`);r.write(t.verbose>=2?`<
236
236
  `:`
237
- `)}function lM(e,t,n){if(OM.has(e)&&typeof t==`string`)return`${t} ${X.dim(`(${yM(BigInt(t),n.tokenSymbol,n.tokenDecimals)})`)}`;if(e===`chainId`&&typeof t==`number`){let e=CM({id:t,name:``});return e?`${t} ${X.dim(`(${e})`)}`:String(t)}return typeof t==`string`&&/^0x[0-9a-fA-F]{40}$/.test(t)?n.explorerUrl?pM(`${n.explorerUrl}/address/${t}`,t):t:typeof t==`string`&&/^https?:\/\//.test(t)?X.link(t,t):String(t)}function uM(e){try{let t=e.replace(/^0x0*/,``);if(!t)return;let n=Uint8Array.from(t.match(/.{1,2}/g).map(e=>Number.parseInt(e,16))),r=new TextDecoder().decode(n);return/^[\x20-\x7e]+$/.test(r)?r:void 0}catch{return}}function dM(e,t){if(e===`realm`&&typeof t==`string`)try{let e=new URL(t.includes(`://`)?t:`https://${t}`);return X.link(e.href,t)}catch{}return String(t)}function fM(e){return typeof e==`object`&&e?JSON.stringify(e):String(e)}function pM(e,t){return X.link(e,t)}function mM(e){if(!e)return{};let t=Array.isArray(e)?e:[e],n={};for(let e of t){let t=e.indexOf(`=`);if(t===-1)throw Error(`Invalid method option format: ${e} (expected key=value)`);n[e.slice(0,t)]=e.slice(t+1)}return n}function hM(e=process.env){if(e.CLAUDECODE)return!0;for(let[t,n]of Object.entries(e))if(n&&(t===`CODEX`||t.startsWith(`CODEX_`)))return!0;return!1}function gM(e){return e.startsWith(`tempo:`)}function _M(e){let t=Ze.createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.on(`close`,()=>n(void 0)),t.question(`${X.bold(`▸ ${e}:`)} `,e=>{t.close(),n(e.trim()||void 0)})})}function vM(e,t=!1){let n=Ze.createInterface({input:process.stdin,output:process.stderr});return new Promise(r=>{let i=t?`(Y/n)`:`(y/N)`;n.question(`${X.bold(`▸ ${e}`)} ${X.dim(i)} `,e=>{n.close();let i=e.trim().toLowerCase();r(i===``?t:i===`y`)})})}function yM(e,t,n=6,r){let[i,a]=(Number(e)/10**n).toString().split(`.`),o=i.replace(/\B(?=(\d{3})+(?!\d))/g,`_`),s=r?.explorerUrl&&r.token?X.dim(X.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):X.dim(t);return`${a?`${o}.${a}`:o} ${s}`}function bM(e,t={}){return e??(t.network?kM[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}function xM(e={}){if(e.network)return e.network;if(!e.rpcUrl&&!(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()))return`testnet`}async function SM(e={}){let t=bM(e.rpcUrl,{network:e.network});if(!t)return ve;let{getChainId:n}=await import(`viem/actions`),r=await n(N({transport:L(t)})),i=Object.values(await import(`viem/tempo/chains`)).filter(e=>typeof e==`object`&&!!e&&`id`in e&&e.id===r),a=i.find(e=>`serializers`in e&&e.serializers)??i[0];if(!a)throw Error(`Unknown chain ID ${r} from RPC ${t}`);return a}function CM(e){return{[ve.id]:`mainnet`,[ye.id]:`testnet`}[e.id]??e.name}function wM(e){return typeof e==`bigint`?e:e.amount}function TM(e){return e.id!==ve.id}async function EM(e,t,n,r={}){let{Actions:i}=await import(`viem/tempo`),[a,o]=await Promise.all([i.token.getBalance(e,{account:n,token:t}).then(wM).catch(()=>0n),i.token.getMetadata(e,{token:t}).catch(e=>{if(r.requireDecimals)throw e;return{symbol:t}})]),s={"0x20c0000000000000000000000000000000000000":`PathUSD`,"0x20C000000000000000000000b9537d11c60E8b50":`USDC`}[t]??o.symbol,c=`decimals`in o&&typeof o.decimals==`number`?o.decimals:6;if(r.requireDecimals&&!(`decimals`in o&&typeof o.decimals==`number`))throw Error(`Token decimals are unavailable.`);return{balance:a,symbol:s,decimals:c,token:t}}async function DM(e,t){if(t?.chain){let n=N({chain:t.chain,transport:L(t.rpcUrl)}),r=t.chain.blockExplorers?.default?.url,i=X.dim(`(${CM(t.chain)})`);return TM(t.chain)?(await Promise.all(NM.map(t=>EM(n,t,e)))).filter(e=>e.balance>0n).map(e=>`${yM(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`):(await Promise.all(MM.map(t=>EM(n,t,e)))).map(e=>`${yM(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`)}let n=N({chain:ve,transport:L(bM())}),r=ve.blockExplorers?.default?.url,i=(await Promise.all(MM.map(t=>EM(n,t,e)))).map(e=>yM(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token}));if(t?.includeTestnet!==!1){let t=N({chain:ye,transport:L()}),n=ye.blockExplorers?.default?.url,r=await Promise.all(NM.map(n=>EM(t,n,e)));for(let e of r)e.balance>0n&&i.push(`${yM(e.balance,e.symbol,e.decimals,{explorerUrl:n,token:e.token})} ${X.dim(`(testnet)`)}`)}return i}var OM,kM,AM,jM,MM,NM,PM=z((()=>{Qj(),aM(),OM=new Set([`amount`,`suggestedDeposit`,`minVoucherDelta`]),kM={mainnet:iM[$j.mainnet],testnet:iM[$j.testnet]},AM=`0x20c0000000000000000000000000000000000000`,jM=`0x20C000000000000000000000b9537d11c60E8b50`,MM=[AM,jM],NM=[`0x20c0000000000000000000000000000000000000`,`0x20c0000000000000000000000000000000000001`,`0x20c0000000000000000000000000000000000002`,`0x20c0000000000000000000000000000000000003`]}));function FM(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:qM}function IM(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function LM(e){return new B({code:`KEYCHAIN_UNAVAILABLE`,message:`Linux keyring requires secret-tool. Install libsecret-tools.`,hint:`On Debian/Ubuntu, run: sudo apt install libsecret-tools gnome-keyring dbus-x11`,exitCode:69,cause:e})}function RM(e){if(e&&IM(e,`secret-tool`))throw LM(e)}function zM(e,t){return new Promise(n=>{m.execFile(e,t,{timeout:FM()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function BM(){let e=c.join(process.env.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`mppx`,`default`);return{get(){try{return t.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(n){t.mkdirSync(c.dirname(e),{recursive:!0}),t.writeFileSync(e,n,`utf-8`)},clear(){try{t.unlinkSync(e)}catch{}}}}function VM(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:BM().get())}function HM(e=`main`){let t=KM;return{async list(){let e=x.platform();if(e===`darwin`){let{stdout:e,error:n}=await zM(`security`,[`dump-keychain`]);if(n)return[];let r=[],i=e.split(`keychain:`);for(let e of i){let n=e.match(/"svce"<blob>="([^"]*)"/),i=e.match(/"acct"<blob>="([^"]*)"/);n?.[1]===t&&i?.[1]&&r.push(i[1])}return r}if(e===`linux`){let{stdout:e,stderr:n,error:r}=await zM(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(RM(r),r)return[];let i=`${e}\n${n}`,a=[],o=i.matchAll(/\baccount = (.+)/g);for(let e of o)e[1]&&a.push(e[1]);return a}throw Error(`Unsupported platform: ${e}`)},async get(){let n=x.platform();if(n===`darwin`){let{stdout:n,error:r}=await zM(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await zM(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return RM(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=x.platform();if(r===`darwin`){await zM(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await zM(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=m.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),FM());return r.stdin?.write(n),r.stdin?.end(),new Promise((e,t)=>{r.on(`close`,n=>{clearTimeout(i),n===0?e():t(Error(`secret-tool exited with code ${n}`))}),r.on(`error`,e=>{clearTimeout(i),t(IM(e,`secret-tool`)?LM(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=x.platform();if(n===`darwin`){await zM(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await zM(`secret-tool`,[`clear`,`service`,t,`account`,e]);RM(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function UM(e){let{privateKeyToAccount:t}=await import(`viem/accounts`),n=process.env.MPPX_PRIVATE_KEY?.trim();if(n)return{account:t(n),source:`environment`};let r=VM(e),i=await HM(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function WM(e){let t=VM(e);if(!process.env.MPPX_PRIVATE_KEY?.trim()&&gM(t))throw new B({code:`UNSUPPORTED_ACCOUNT`,message:`Persistent sessions require an mppx account or MPPX_PRIVATE_KEY.`,exitCode:2});return UM(e).catch(e=>{throw new B({code:`ACCOUNT_NOT_FOUND`,message:e instanceof Error?e.message:`No account found.`,exitCode:69,...e instanceof Error&&{cause:e}})})}async function GM(e){return(await UM(e)).account}var KM,qM,JM=z((()=>{PM(),KM=`mppx`,qM=1e4}));Zj(),JM();const YM=[[`ANTIGRAVITY_CLI_ALIAS`,`antigravity`],[`CLAUDECODE`,`claude_code`],[`CLINE_ACTIVE`,`cline`],[`CODEX_SANDBOX`,`codex_cli`],[`CODEX_THREAD_ID`,`codex_cli`],[`CODEX_SANDBOX_NETWORK_DISABLED`,`codex_cli`],[`CODEX_CI`,`codex_cli`],[`CURSOR_AGENT`,`cursor`],[`GEMINI_CLI`,`gemini_cli`],[`OPENCODE`,`open_code`],[`OPENCLAW_SHELL`,`openclaw`],[`CLAUDE_CODE_ENTRYPOINT`,`claude_code`],[`CODEX_INTERNAL_ORIGINATOR_OVERRIDE`,`codex_cli`]];function XM(e=process.env){return YM.find(([t])=>e[t])?.[1]}function ZM(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function QM(e,t){let{chainId:n,decimals:r}=t;if(typeof e==`string`)return{address:e,chainId:n,decimals:r};if(ZM(e))return e.addresses[n]?e(n):void 0;if(e.chainId===n)return e}function $M(e,t,n={}){let{chainId:r,decimals:i}=n,a=e=>e.toLowerCase()===t.toLowerCase();for(let t of e){if(typeof t==`string`){if(a(t))return{currency:t,decimals:i};continue}if((r===void 0?ZM(t)?Object.keys(t.addresses).map(e=>QM(t,{chainId:Number(e)})):[t]:[QM(t,{chainId:r})]).some(e=>e&&a(e.address)))return{currency:t,decimals:t.decimals}}}var eN=z((()=>{}));eN();const tN=Symbol(`mppx.x402.asset`);function nN(e){return{[tN]:!0,address:e.address,chainId:gN(e.network),decimals:e.decimals,network:e.network,transfer:e.transfer}}function rN(e,t){let n=e(t.chainId);return nN({address:n.address,decimals:n.decimals,network:hN(t.chainId),transfer:_N(t.transfer,n)})}const iN={USDC:nN({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},aN={USDC:nN({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},oN={USDC:nN({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:nN({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},sN={USDC:nN({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},cN=[iN,aN,oN,sN].flatMap(e=>Object.values(e));function lN(e,t){let n=e.toLowerCase();return cN.find(e=>e.network===t&&e.address.toLowerCase()===n)}function uN(e){return typeof e!=`object`||!e?!1:e[tN]===!0}const dN=ZM;function fN(e){return typeof e==`string`}function pN(e,t){if(uN(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(typeof e==`string`)return{address:e};let n=QM(e,{chainId:gN(t)});if(n)return{address:n.address,decimals:n.decimals,name:n.name}}function mN(e,t,n){let r=pN(e,n);return r?I(r.address)===I(t):!1}function hN(e){return`eip155:${e}`}function gN(e){return Number(e.slice(7))}function _N(e,t){if(e.type!==`eip3009`)return e;if(e.name)return{...e,name:e.name};if(!t.name)throw Error(`EIP-3009 token assets require a token name.`);return{...e,name:t.name}}var vN=it({base:()=>iN,baseSepolia:()=>aN,celo:()=>oN,celoSepolia:()=>sN,define:()=>nN,fromToken:()=>rN,isAsset:()=>uN,isRawAddress:()=>fN,isToken:()=>dN,lookup:()=>lN,matches:()=>mN,resolve:()=>pN,toChainId:()=>gN,toNetwork:()=>hN}),yN=it({base:()=>bN,baseSepolia:()=>xN,celo:()=>SN,celoSepolia:()=>CN});const bN=8453,xN=84532,SN=42220,CN=11142220;lS();function wN(e){let t=[cS(e.accepted),cS(e.resource),cS(e.extensions)].join(`|`);return j.sha256(A.fromString(t),{as:`Hex`})}HT(),Uw();async function TN(e){let t=e.context?.account??e.config.account;if(!t?.signTypedData)throw Error(`x402 exact requires a typed-data signer.`);let n=e.challenge.request,r=yw(n);if(kN(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?jN(n.extensions):n.extensions,a=r.extra?.assetTransferMethod??`eip3009`;if(a!==`eip3009`)throw Error(`x402 exact ${String(a)} signing is not implemented yet.`);let o=r.extra?.name,s=r.extra?.version;if(typeof o!=`string`||typeof s!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let c=Math.floor(Date.now()/1e3),l={from:I(t.address),nonce:i?.mppx?wN({accepted:r,extensions:i,resource:n.resource}):NN(),to:I(r.payTo),validAfter:(c-600).toString(),validBefore:(c+r.maxTimeoutSeconds).toString(),value:r.amount},u=await t.signTypedData({domain:{chainId:ON(r.network),name:o,verifyingContract:I(r.asset),version:s},message:{...l,value:BigInt(l.value),validAfter:BigInt(l.validAfter),validBefore:BigInt(l.validBefore)},primaryType:`TransferWithAuthorization`,types:DN});return zT({accepted:r,...i?{extensions:i}:{},payload:{authorization:l,signature:u},...n.resource?{resource:n.resource}:{},x402Version:2})}function EN(e){let t=e.challenge.request,n;try{n=yw(t),kN(e.config,n)}catch{return!1}if(!t.resource||(n.extra?.assetTransferMethod??`eip3009`)!==`eip3009`)return!1;let r=n.extra?.name,i=n.extra?.version;return typeof r==`string`&&typeof i==`string`}const DN={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function ON(e){return Number(e.slice(Sw.length))}function kN(e,t){let n=ON(t.network);if(e.networks&&!e.networks.includes(n))throw Error(`x402 exact chain ID is not allowed: ${n}.`);let r=e.currencies??e.assets;if(r?.some(e=>fN(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=I(t.asset);if(!r.some(n=>mN(n,e,t.network)))throw Error(`x402 exact currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`x402 exact amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=AN(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>me(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function AN(e,t){let n=e.currencies??e.assets,r=I(t.asset),i=n?.find(e=>mN(e,r,t.network)),a=i?pN(i,t.network):void 0;return a?.decimals===void 0?e.decimals===void 0?lN(r,t.network)?.decimals:e.decimals:a.decimals}function jN(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:MN()}}}:e}function MN(){return PN().slice(2)}function NN(){return PN()}function PN(){let e=globalThis.crypto;if(!e?.getRandomValues)throw Error(`x402 exact requires crypto randomness.`);let t=e.getRandomValues(new Uint8Array(32));return`0x${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}xS();const FN=[`authorization`],IN=Y.string().check(Y.regex(/^\d+$/,`Invalid atomic amount`));Y.object({name:Y.string().check(Y.minLength(1)),version:Y.string().check(Y.minLength(1))});const LN=Y.object({chainId:Y.number(),credentialTypes:Y.optional(Y.array(Y.enum(FN)).check(Y.minLength(1))),decimals:Y.optional(Y.number()),permit2Address:Y.optional(gS()),splits:Y.optional(Y.array(Y.object({amount:IN,recipient:gS()})))});Y.object({amount:IN,currency:gS(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),methodDetails:LN,recipient:gS()});const RN=Y.object({amount:dS(),chainId:Y.number(),currency:gS(),credentialTypes:Y.optional(Y.array(Y.enum(FN)).check(Y.minLength(1))),decimals:Y.number(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),permit2Address:Y.optional(gS()),recipient:gS(),splits:Y.optional(Y.array(Y.object({amount:IN,recipient:gS()})))}),zN=Y.object({from:gS(),nonce:_S(),signature:yS(),to:gS(),type:Y.literal(`authorization`),validAfter:IN,validBefore:IN,value:IN}),BN={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function VN(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function HN(e){return j.keccak256(A.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function UN(e){return`eip155:${e}`}function WN(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}xk(),xS();const GN=yk({name:`evm`,intent:`charge`,schema:{credential:{payload:zN},request:Y.pipe(RN,Y.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:s,...c})=>({...c,amount:me(e,i).toString(),currency:I(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:I(a)}:{},...s?{splits:s}:{}},recipient:I(o)})))}});PE(),vC(),ZC(),xk(),xS();function KN(e){return TE(bk(GN,{canHandleChallenge({challenge:t}){return!qN(t)||EN({challenge:t,config:e})},context:Y.object({account:Y.optional(Y.custom())}),async createCredential({challenge:t,context:n}){if(qN(t))return TN({challenge:t,config:e,context:n});let r=n?.account??e.account;if(!r?.signTypedData)throw Error(`EVM authorization requires a typed-data signer.`);let i=t.request;JN(e,i);let a=XN(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return pC(fC({challenge:t,payload:{from:I(r.address),nonce:HN(t),signature:await r.signTypedData({domain:VN({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:I(r.address),nonce:HN(t),to:I(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:BN}),to:I(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:WN({address:I(r.address),chainId:i.methodDetails.chainId})}))}}),{assert(t){qN(t)||JN(e,t.request)}})}function qN(e){return YC(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function JN(e,t){if(YN(e,t),!t.methodDetails.credentialTypes?.includes(`authorization`))throw Error(`EVM authorization is not accepted by this challenge.`);if(t.methodDetails.splits?.length)throw Error(`EVM authorization does not support payment splits.`)}function YN(e,t){let n=t.methodDetails.chainId,r=UN(n);if(e.networks&&!e.networks.includes(n))throw Error(`EVM chain ID is not allowed: ${n}.`);let i=e.currencies??e.assets;if(i?.some(e=>fN(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=I(t.currency);if(!i.some(t=>mN(t,e,r)))throw Error(`EVM currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`EVM charge amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=ZN(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>me(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function XN(e,t){let n=e.currencies??e.assets,r=I(t.currency),i=UN(t.methodDetails.chainId),a=n?.find(e=>mN(e,r,i)),o=a?pN(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;let s=lN(r,i)?.transfer;if(s?.type===`eip3009`)return{name:s.name,version:s.version};throw Error(`EVM authorization requires token name and version.`)}function ZN(e,t){let n=e.currencies??e.assets,r=I(t.currency),i=UN(t.methodDetails.chainId),a=n?.find(e=>mN(e,r,i)),o=a?pN(a,i):void 0;return o?.decimals===void 0?e.decimals===void 0?lN(r,i)?.decimals:e.decimals:o.decimals}function QN(e){return[QN.charge(e)]}(function(e){e.charge=KN,e.assets=vN,e.chains=yN})(QN||={});function $N(e){return e}var eP=z((()=>{}));ZC(),eP();function tP(){return $N({method:`evm`,supports:e=>e.method===`evm`&&!YC(e),async setup({challenge:e,options:t}){let n=e.request,r=n.methodDetails,i=r?.chainId,a=i?nP(i):void 0,o=n.currency,s=await GM(t.account),c=[...Object.values(iN),...Object.values(aN),...Object.values(oN),...Object.values(sN)],l=o??``;if(a&&o)try{let e=N({chain:a,transport:L()}),t=await je(e,{address:o,abi:F,functionName:`symbol`});t&&(l=t)}catch{}return{tokenSymbol:l,tokenDecimals:r?.decimals??6,explorerUrl:a?.blockExplorers?.default?.url,methods:[...QN({account:s,currencies:c})]}}})}function nP(e){return Object.values(Qe).find(t=>t.id===e)}function rP(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`Decimals must be a non-negative integer.`);if(!/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))throw TypeError(`Value \`${e}\` is not a valid decimal number.`);let n=e.startsWith(`-`),[r=`0`,i=``]=(n?e.slice(1):e).split(`.`),a=i.slice(0,t).padEnd(t,`0`),o=BigInt(`${r||`0`}${a}`);return i.length>t&&i[t]>=`5`&&(o+=1n),n?-o:o}xS();const iP=Y.object({customer:Y.optional(Y.string().check(Y.minLength(1))),hooks:Y.optional(Y.object({inputs:Y.object({tax:Y.object({calculation:Y.string().check(Y.minLength(1))})})})),metadata:Y.optional(Y.record(Y.string(),Y.string())),receipt_email:Y.optional(Y.string().check(Y.minLength(1)))}),aP=Y.custom(e=>typeof e==`function`),oP=Y.union([iP,aP]);xk(),xS();const sP=yk({name:`stripe`,intent:`charge`,schema:{credential:{payload:Y.object({externalId:Y.optional(Y.string()),spt:Y.string()})},request:Y.pipe(Y.object({amount:dS(),currency:Y.string(),decimals:Y.number(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),metadata:Y.optional(Y.record(Y.string(),Y.string())),networkId:Y.string(),paymentIntentOptions:Y.optional(oP),paymentMethodTypes:Y.array(Y.string()).check(Y.minLength(1)),recipient:Y.optional(Y.string())}),Y.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:rP(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});vC(),xk(),xS();function cP(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return bk(sP,{context:Y.object({paymentMethod:Y.optional(Y.string())}),async createCredential({challenge:e,context:a}){let o=a?.paymentMethod??i;if(!o)throw Error(`paymentMethod is required (pass via context or parameters)`);let s=e.request.amount,c=e.request.currency,l=typeof e.request.externalId==`string`?e.request.externalId:void 0,u=e.request.methodDetails?.networkId;if(!u)throw Error(`networkId is required in challenge.methodDetails`);let d=e.request.methodDetails?.metadata;if(d?.externalId)throw Error(`methodDetails.metadata.externalId is reserved; use credential externalId instead`);let f=e.expires?Math.floor(new Date(e.expires).getTime()/1e3):Math.floor(Date.now()/1e3)+3600,p=await n({amount:s,challenge:e,client:t,currency:c,expiresAt:f,metadata:d,networkId:u,paymentMethod:o}),m=l??r;return pC({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function lP(e){return[cP(e)]}(function(e){e.charge=cP})(lP||={}),Rx(),PM(),eP();function uP(){return $N({method:`stripe`,supports(e){return e.method===`stripe`&&e.intent===`charge`},async setup({challenge:e,methodOpts:t}){let n=e.request,r=n.currency,i=fP(p.object({paymentMethod:p.string(),secretKey:p.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new B({code:`MISSING_ENV`,message:`MPPX_STRIPE_SECRET_KEY environment variable is required for Stripe payments.`,exitCode:2});return{tokenSymbol:r?.toUpperCase()??``,tokenDecimals:n.decimals??2,methods:[lP.charge({paymentMethod:i.paymentMethod,createToken:async({paymentMethod:e,amount:t,currency:n,networkId:r,expiresAt:i,metadata:o})=>{let s=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()}),c=dP(a),l=process.env.MPPX_STRIPE_SPT_URL?process.env.MPPX_STRIPE_SPT_URL:c?`https://api.stripe.com/v1/test_helpers/shared_payment/granted_tokens`:`https://api.stripe.com/v1/shared_payment/issued_tokens`;if(r){let e=c?`seller_details[network_id]`:`seller_details[network_business_profile]`;s.set(e,r)}if(o)for(let[e,t]of Object.entries(o))s.set(`metadata[${e}]`,t);let u={Authorization:`Basic ${btoa(`${a}:`)}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":fk},d=await globalThis.fetch(l,{method:`POST`,headers:u,body:s});if(!d.ok){let a=await d.json();if(c&&(o||r)&&a.error.message.includes(`Received unknown parameter`)){let r=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()});if(d=await globalThis.fetch(l,{method:`POST`,headers:u,body:r}),!d.ok){let e=await d.json();throw new B({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${e.error.message}`,exitCode:77})}}else throw new B({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${a.error.message}`,exitCode:77})}let{id:f}=await d.json();return f}})]}},formatReceiptField(e,t){if(e===`reference`&&typeof t==`string`&&t.startsWith(`pi_`)){let e=process.env.MPPX_STRIPE_SECRET_KEY,n=`https://dashboard.stripe.com${e!==void 0&&dP(e)?`/test`:``}/payments/${t}`;return X.link(n,t,!0)}}})}function dP(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function fP(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function pP(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 _e(r)}}var mP=z((()=>{}));function hP(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}var gP=z((()=>{}));function _P(e,t={}){return L(e.url,{fetchFn:e.fetch,fetchOptions:{headers:hP(e)},...t})}function vP(e){let{chain:t,getClient:n,remoteFeePayer:r,rpcUrl:i}=e;return n?!t?.serializers&&!r&&!e.requireChain?n:async i=>{let a=await n(i);if(e.requireChain&&(a.chain?.id===void 0||a.chain.id!==i.chainId))throw Error(`Subscription chain mismatch: expected ${i.chainId}, got ${a.chain?.id??`unknown`}.`);let o=a;if(r&&a.transport.key!==`feePayer`){let e=a.request.bind(a),t=We(re({request:t=>e(t)},{retryCount:0}),_P(r,{retryCount:a.transport.retryCount}))({account:a.account,chain:a.chain,pollingInterval:a.pollingInterval,retryCount:0}),n=P({...t.config,retryCount:0},t.value);o=Object.assign({},a,{request:n.request,transport:{...n.config,...n.value}})}return!t?.serializers||o.chain?.serializers?.transaction?o:Object.assign({},o,{chain:{...t,...i.chainId===void 0?{}:{id:i.chainId},...o.chain,formatters:o.chain?.formatters??t.formatters,prepareTransactionRequest:o.chain?.prepareTransactionRequest??t.prepareTransactionRequest,serializers:o.chain?.serializers?.transaction?o.chain.serializers:t.serializers}})}:({chainId:e})=>{if(!i)throw Error("No `rpcUrl` provided.");let n=e||Number(Object.keys(i)[0]),a=i[n];if(!a)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let o=r?We(L(a),_P(r)):L(a);return N({chain:xP[n]??{...t,id:n},transport:o})}}function yP(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 bP(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}var xP,SP=z((()=>{gP(),xP={[ve.id]:ve,[ye.id]:ye}}));function CP(e){let t=j.keccak256(A.fromString(e),{as:`Hex`});return M.toBytes(M.slice(t,0,10))}function wP(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(M.toBytes(EP),0),i[4]=DP,i.set(CP(t),5),n&&i.set(CP(n),15),i.set(TP(r),25),M.fromBytes(i)}function TP(e){let t=j.keccak256(A.fromString(e),{as:`Hex`});return M.toBytes(M.slice(t,0,7))}var EP,DP,OP=z((()=>{EP=M.slice(j.keccak256(A.fromString(`mpp`),{as:`Hex`}),0,4),DP=1}));async function kP(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:QM(e,{chainId:s})?.address;!t||Sk(t,i)||c.some(e=>Sk(e,t))||c.push(t)}let l=await Promise.allSettled([je(e,{...Be.token.getBalance.call(e,{account:n,token:i}),account:null}),...c.map(t=>je(e,{...Be.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/jP;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 Be.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:f});if(t<=0n||t>m)continue;let n=t+t*p/jP,o=n<m?n:m;if(r>=o)return[Be.token.approve.call(e,{amount:o,spender:Ve.stablecoinDex,token:a}),Be.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:f,maxAmountIn:o})]}catch{}}throw new NP({currency:i})}function AP(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`&&Sk(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var jP,MP,NP,PP=z((()=>{eN(),Ck(),aM(),jP=10000n,MP=[eM.pathUsd,eM.usdc,eM.ousd],NP=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}}}));function FP(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}))]}var IP=z((()=>{}));function LP(e,t,n){t&&(n&&!n.some(e=>Sk(e,t))||e.some(e=>Sk(e,t))||e.push(t))}async function RP(e,t,n){try{return(await Be.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function zP(e){let t=e.chain?.feeToken;if(t)return He.toAddress(t);let n=e.chain?.id;return n?tM[n]:void 0}function BP(e){let t=[];return LP(t,eM.pathUsd),LP(t,tM[e]),t}async function VP(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])LP(o,e,n);if(LP(o,await Be.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),LP(o,zP(i),n),!a)for(let e of r??[])LP(o,e,n);for(let e of o)if(await RP(i,t,e))return e;return o[0]}var HP=z((()=>{Ck(),aM()}));function UP(e){if(e!==void 0)return nM[e]}function WP(e){let t=UP(e.chainId);return!!t&&le(e.currency,{strict:!1})&&ue(e.currency,t.token)}function GP(e){let t=UP(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let r=BigInt(n.amount),i=n.memo;return{calls:[{data:ae({abi:Re.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:ae({abi:ZP,functionName:`swapTo`,args:[t.token,r,e.currency,n.recipient,i]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:r,memo:i,recipient:n.recipient}]}}async function KP(e,t){let n=GP(t);if(n)try{return await je(e,Be.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await De(e,{account:t.account,calls:n.calls}),n)}catch{return}}function qP(e={}){let{address:t,amount:n,chainId:r=$j.mainnet}=e;if(r!==$j.mainnet)return;let i=new URL(rM);if(t&&le(t,{strict:!1})&&i.searchParams.set(`address`,I(t)),n!==void 0&&n>0n){let e=(n+QP-1n)/QP,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 JP(e,t){let n=UP(t.chainId);if(!n)return;let r=await je(e,Be.token.getBalance.call(e,{account:t.account,token:n.token})).catch(()=>void 0);return typeof r==`bigint`?r:void 0}async function YP(e,t){let{account:n,amount:r,chainId:i}=t,a=await JP(e,{account:n,chainId:i});if(a===void 0||a>=r)return;let o=e=>`${oe(e,6)} MACH`,s=r-a;return{fundingUrl:qP({address:n,amount:s,chainId:i}),reason:`requested ${o(r)}, available ${o(a)}`,shortfall:s}}async function XP(e,t){let n=await YP(e,t);if(n)return new iS({fundingUrl:n.fundingUrl,reason:n.reason})}var ZP,QP,$P=z((()=>{aS(),aM(),ZP=fe([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]),QP=10n**BigInt(4)}));function eF(e){return{name:`MPP`,version:`3`,chainId:e}}function tF(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function nF(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:eF(n),types:aF,primaryType:iF,message:tF({account:t,challengeId:r,realm:i})}}function rF(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}var iF,aF,oF=z((()=>{iF=`Proof`,aF={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]}}));function sF(e){let t=new Set,n=e;for(;typeof n==`object`&&n&&!t.has(n);){t.add(n);let e=n.data;if(uF(e))return e;let r=e?.data;if(uF(r))return r;n=n.cause}}function cF(e,t){let n=sF(e);if(!n)return;let r=(()=>{try{return ie({abi:dF,data:n})}catch{return}})();if(r?.errorName===`SpendingLimitExceeded`){let n=t.account.accessKeyAddress;return new tS({accessKey:typeof n==`string`?n:void 0,account:t.account.address,cause:e})}if(r?.errorName===`InsufficientBalance`){let[n,i,a]=r.args;return new iS({cause:e,reason:`${t.account.address} holds ${n} of token ${a}, but the payment requires ${i}`})}}async function lF(e,t){try{return await t()}catch(t){throw cF(t,e)??t}}function uF(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{8}/.test(e)}var dF,fF=z((()=>{aS(),dF=[...Re.accountKeychain.filter(e=>e.type===`error`),...Re.tip20.filter(e=>e.type===`error`)]}));function pF(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??[])AF(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=vP({chain:ve,getClient:e.getClient,rpcUrl:iM}),i=pP({account:e.account});SF(e.zone);let a=new Map,o=bk(Zk,{canHandleChallenge({challenge:t}){try{return jF(e,n,t.request),!0}catch{return!1}},context:MF,async createCredential(o){let{challenge:s,context:c}=o,l=OE(o),u=()=>Error(`The Zone withdrawal this challenge resumes is no longer outstanding. Retry the request to pay it.`);jF(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});yP(p,f);let m=f??p.chain?.id;if(bP(e.allowedChainIds,m),m===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");d===void 0&&jF(e,n,s.request,m);let{request:h}=s,{amount:g,methodDetails:_}=h,v=_?.supportedModes??[`pull`,`push`],y=e.zone?.client.chain,b=e.zone?e.zone.zoneId??Dk(y?.id??0):void 0,x=y?.sourceId??(y?Ok(y.id):void 0),S=c?.mode??e.mode;if(BigInt(g)>0n&&e.zone&&b!==void 0&&x===m&&v.includes(`push`)&&(S===void 0||S===`push`)&&Tk(_?.zones,b)&&!_?.splits){let r={assertFee:t=>jF(e,n,h,m,t),challenge:s,clientId:t,client:p,origin:xF(cE(o)),pending:a,zone:e.zone,zoneId:b},i=_F(r);if(i)return yF(r,i);if(l?.resume)throw u();if(s.expires&&yC(s.expires,s.id),CF(s.expires,e.zone.settlementTimeoutMs))return gF(r)}if(l?.resume)throw u();let C=i(p,c),w=async t=>await e.resolveAccount?.({account:C,chainId:m,operation:t})??C;if(BigInt(g)===0n){let e=await w({kind:`signPaymentProof`});return pC({challenge:s,payload:{signature:await Ie(p,{account:e,...nF({account:e.address,chainId:m,challengeId:s.id,realm:s.realm})}),type:`proof`},source:rF({address:e.address,chainId:m})})}let T=h.currency,E=WP({chainId:m,currency:T}),ee=_?.memo??wP({challengeId:s.id,clientId:t,serverId:s.realm}),D=FP({amount:g,methodDetails:{..._,memo:ee},recipient:h.recipient}),O=D.map(e=>Be.token.transfer.call(p,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:T})),k=AP(c?.autoSwap??e.autoSwap,MP),te=_?.machineTokenEnabled===!0&&!l?GP({chainId:m,currency:T,transfers:D}):void 0,A=C,j,M=!1;if(te){let e=await(async()=>{try{return await w({calls:te.calls,kind:`executeCalls`})}catch{return}})();e&&(j=await KP(p,{account:e.address,chainId:m,currency:T,transfers:D}),j?A=e:M=!0)}let ne;if(!j){if(A=await w({kind:`executeCalls`,...k?{}:{calls:O}}),ne=k?await kP(p,{account:A.address,amountOut:BigInt(g),tokenOut:T,tokenIn:k.tokenIn,slippage:k.slippage,maxAmountIn:k.maxAmountIn}):void 0,l&&ne)throw new rS({limit:l.limit,reason:`asset`});if(M&&!k){let e=await mF(p,{account:A.address,amount:BigInt(g),chainId:m,currency:T});if(e)throw e}}let N=j?.calls??[...ne??[],...O],P=BP(m),re=(c?.feeToken??e.feeToken)||(j||E?await VP({account:A.address,allowedTokens:P,candidateTokens:P,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=A.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)})(),F=()=>{l&&s.expires&&yC(s.expires,s.id)};if(ie===`push`){F();let{receipts:e}=A.type===`local`?{receipts:[await lF({account:A},()=>Pe(p,{account:A,calls:N,...re?{feeToken:re}:{},nonceKey:`expiring`,validBefore:ae}))]}:await Me(p,{account:A,...re?{capabilities:{feeToken:re}}:{},calls:N,experimental_fallback:N.length===1,forceAtomic:N.length>1}),t=e?.[0]?.transactionHash;if(!t)throw xE(Error(`No transaction receipt returned.`));return pC({challenge:s,payload:{hash:t,type:`hash`},source:rF({address:A.address,chainId:m})})}let oe=()=>{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.`)};oe();let se=await lF({account:A},()=>Ae(p,{account:A,calls:N,...re?{feeToken:re}:{},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 oe(),F(),pC({challenge:s,payload:{signature:await Fe(p,se),type:`transaction`},source:rF({address:A.address,chainId:m})})}}),s=new Map,c=async t=>{jF(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,a=OE(t),c=s.get(i);if(a&&kE(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 TE(aE({...o,createCredential:c},hF),{assert:t=>jF(e,n,t.request),resumes:t=>vF(a,t,e.zone&&(e.zone.zoneId??Dk(e.zone.client.chain?.id??0)))})}async function mF(e,t){let{account:n,amount:r,chainId:i,currency:a}=t,o=await je(e,Be.token.getBalance.call(e,{account:n,token:a})).catch(()=>void 0);if(!(typeof o!=`bigint`||o>=r))return XP(e,{account:n,amount:r,chainId:i})}function hF(e){let t=Zk.schema.credential.payload.safeParse(cC(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(Xe.serializedType))return;let i=Xe.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&Xe.serialize(i)===r)return de(r)}function gF(e){let{challenge:t,origin:n,pending:r,zoneId:i}=e,a={sent:!1},o={challenge:t,origin:n,terms:EF(t,i),waiters:0,withdrawal:kF(e,a)},s=TF(t);return r.set(s,o),o.withdrawal.catch(()=>{!a.sent&&r.get(s)===o&&r.delete(s)}),yF(e,o)}function _F(e){let{challenge:t,pending:n,zoneId:r}=e,i=n.get(TF(t));if(i)return i;let a=EF(t,r);if(a!==void 0){for(let[e,t]of n)if(t.terms===a){if(!OF(t.challenge.expires)){n.delete(e);continue}if(t.redeemedLate)throw new nS({challengeId:t.challenge.id,senderTags:t.senderTags,zoneId:r});if(!(t.waiters>0))return t}}}function vF(e,t,n){if(n===void 0||e.size===0)return!1;if(e.has(TF(t)))return!0;let r=EF(t,n);if(r===void 0)return!1;for(let t of e.values())if(t.terms===r&&OF(t.challenge.expires)&&(t.redeemedLate||t.waiters===0))return!0;return!1}async function yF(e,t){t.waiters++;try{return await bF(e,t)}finally{t.waiters--}}async function bF(e,t){let{client:n,origin:r,pending:i,zone:a,zoneId:o}=e,{challenge:s}=t,c=s.request.recipient,l=TF(s);if((l===TF(e.challenge)?r!==void 0&&t.origin!==void 0&&r!==t.origin:!r||r!==t.origin)||!OF(s.expires))throw new nS({challengeId:s.id,zoneId:o});let u=await t.withdrawal,d=u.senderTags??await Ak(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}),xE(t)}),f;try{f=await jk(n,{portal:Ek(o),senderTags:d,timeoutMs:wF(s.expires,a.settlementTimeoutMs),to:c})}catch(e){throw new nS({cause:e,challengeId:s.id,senderTags:d,zoneId:o})}i.get(l)===t&&(DF(s.expires)?(t.redeemedLate=!0,t.senderTags=[f.senderTag]):i.delete(l));let{hash:p,senderTag:m}=f;return pC({challenge:s,payload:{hash:p,senderTag:m,type:`zone`,zoneId:o}})}function xF(e){if(e)try{let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`?void 0:t.origin}catch{return}}function SF(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||Ok(n)===void 0)return;let r=Dk(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function CF(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+NF}function wF(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function TF(e){return JSON.stringify(e)}function EF(e,t){let n;try{n=e.opaque===void 0?e.meta:oS(e.opaque)}catch{return}let{digest:r,intent:i,method:a,realm:o,request:s}=e;return cS({digest:r,intent:i,meta:pk(n),method:a,realm:o,request:s,zoneId:t})}function DF(e){if(!e)return!1;let t=new Date(e).getTime();return!Number.isNaN(t)&&Date.now()>=t}function OF(e){if(!e)return!0;let t=new Date(e).getTime();return Number.isNaN(t)||Date.now()<t+3e5}async function kF(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=wP({challengeId:r.id,clientId:i,serverId:r.realm}),f=await Be.zone.getWithdrawalFee(a.client);n(f);let[,p]=Be.zone.requestWithdrawal.calls({amount:c,fallbackRecipient:s.address,memo:d,to:u,token:l}),m=await Ae(a.client,{account:s,calls:[Be.token.approve.call({amount:c+f,spender:Ve.zoneOutbox,token:l}),p]}),h=await Fe(a.client,m);t.sent=!0;let g=de(h),_=await Ne(a.client,{serializedTransaction:h}).catch(e=>Le(a.client,{hash:g,timeout:PF}).catch(()=>{let t=new Zx({cause:e,transactionHash:g});throw t.message=`Zone withdrawal outcome is unknown: transaction ${g} may have been sent. Retrying this challenge does not withdraw again.`,t}));if(_.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${_.transactionHash} reverted.`);let[v]=pe({abi:Re.zoneOutbox,eventName:`WithdrawalRequested`,logs:_.logs});return{blockNumber:_.blockNumber,sender:s.address,senderTags:v?[kk({fallbackNonce:v.args.fallbackNonce,sender:v.args.sender,transactionHash:_.transactionHash})]:void 0,transactionHash:_.transactionHash}}function AF(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 me(e,t)}}function jF(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)&&bP(e.allowedChainIds,s);let c=e.currencies?$M(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>AF(t.maxAmount,c?.decimals))throw Error(`Tempo charge ${u} maxAmount.`)}var MF,NF,PF,FF=z((()=>{wE(),pE(),PE(),vC(),eN(),aS(),bC(),vk(),xk(),lS(),mP(),SP(),xS(),OP(),PP(),IP(),aM(),HP(),$P(),oF(),fF(),Rk(),eA(),MF=Y.object({account:Y.optional(Y.custom()),autoSwap:Y.optional(Y.custom()),feeToken:Y.optional(Y.custom()),mode:Y.optional(Y.enum(Vk))}),NF=15e3,PF=15e3}));function IF(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function LF(e){let t=k.encode(k.from([`address payer`,`address payee`,`address operator`,`address token`,`bytes32 salt`,`address authorizedSigner`,`bytes32 expiringNonceHash`,`address escrow`,`uint256 chainId`]),[e.payer,e.payee,e.operator,e.token,e.salt,e.authorizedSigner,e.expiringNonceHash,e.escrow??`0x4d50500000000000000000000000000000000000`,BigInt(e.chainId)]);return j.keccak256(t)}function RF(e){return Xe.encodeForSigning(e)}function zF(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function BF(e,t){return j.keccak256(M.concat(RF(e),t.sender))}var VF=z((()=>{CA()})),HF,UF,WF,GF,KF=z((()=>{HF=[{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`}],UF=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],WF={name:`descriptor`,type:`tuple`,components:HF},GF=[{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:[WF,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[WF,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[WF,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[WF],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[WF],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[WF],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:HF},{name:`state`,type:`tuple`,components:UF}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:UF}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:UF}]},{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:[WF,{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 qF(e){return e.type===`secp256k1`?e.signature.s<=ZF:e.type===`p256`||e.type===`webAuthn`?e.signature.s<=QF:!0}function JF(e){if(e.type===`configurable`)return{...e,signatures:e.signatures.map(e=>JF(e))};if(qF(e))return e;if(e.type===`secp256k1`){let{r:t,s:n,yParity:r}=e.signature;return{...e,signature:{r:t,s:YF-n,yParity:+(r===0)}}}return e.type===`p256`||e.type===`webAuthn`?{...e,signature:{...e.signature,s:XF-e.signature.s}}:e}var YF,XF,ZF,QF,$F=z((()=>{YF=115792089237316195423570985008687907852837564279074904382605163141518161494337n,XF=115792089210356248762697446949407573529996955224135760342422259061068512044369n,ZF=57896044618658097711785492504343953926418782139537452191302581570759080747168n,QF=57896044605178124381348723474703786764998477612067880171211129530534256022184n}));function eI(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function tI(e){return e===void 0||BigInt(e)===0n}function nI(e,t){let{account:n,config:r,signatures:i}=e,a=Ge.getSignPayload({account:n,config:r,payload:t}),o=Number(r.threshold),s,c=0,l;for(let[e,t]of i.entries()){if(!eI(t.type)||!qF(t)||e>0&&c>=o)return!1;let n=Je.extractAddress({payload:a,signature:t});if(!Je.verify(t,{address:n,payload:a}))return!1;let i=r.owners.find(e=>Sk(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 rI(e,t){let{account:n,commitment:r,payload:i}=t;if(!Sk(e.account,n)||BigInt(e.config.version??0n)===0n&&e.config.owners.some(({owner:t})=>Sk(t,e.account)))return!1;if(tI(r)){if(BigInt(e.config.version??0n)!==0n||!Sk(Ge.getAddress(e.config),n))return!1}else if(Ge.getCommitment(e.config).toLowerCase()!==r.toLowerCase())return!1;return nI(e,i)}var iI=z((()=>{Ck(),$F()}));function aI(e,t){return{name:vI,version:yI,chainId:t,verifyingContract:e}}function oI(e,t,n){return ce({domain:aI(e,t),types:xI,primaryType:`CloseAuthorization`,message:n})}function sI(e,t){return Ke.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function cI(e,t,n){return e.toLowerCase()===Ke.address.toLowerCase()?sI(t,n):ce({domain:aI(e,t),types:bI,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function lI(e,t,n,r){let i=uI(e);return i?dI(i,t,n,r):!1}function uI(e){let t=Je.from(e);if(Je.serialize(t).toLowerCase()===e.toLowerCase())return t}function dI(e,t,n,r){if(e.type===`configurable`)return r.configurable?rI(e,{account:n,commitment:r.openingCommitment,payload:t}):!1;if(!eI(e.type)||!qF(e)||!tI(r.openingCommitment))return!1;let i=Je.extractAddress({payload:t,signature:e});return Je.verify(e,{address:i,payload:t})&&Sk(i,n)}function fI(e){return e.source===`configurable`}function pI(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function mI(e,t){return ze.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function hI(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===Ke.address.toLowerCase())try{return await mI(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return Ie(e,{account:t,domain:aI(r,i),types:bI,primaryType:`Voucher`,message:n})})(),o=Je.from(a);if(!eI(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 Je.serialize(JF(o))}async function gI(e,t,n,r,i){let a=pI(t)?await t.sign({hash:oI(r,i,n),raw:!0}):await Ie(e,{account:t,domain:aI(r,i),types:xI,primaryType:`CloseAuthorization`,message:n}),o=Je.from(a);if(!eI(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 Je.serialize(JF(o))}function _I(e,t,n,r,i={}){try{let a=cI(e,t,n);return lI(n.signature,a,r,i)}catch{return!1}}var vI,yI,bI,xI,SI=z((()=>{Ck(),iI(),$F(),vI=`TIP20 Channel Reserve`,yI=`1`,bI={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},xI={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]}}));function CI(e){return typeof e==`object`&&!!e}function wI(e){return typeof e==`string`&&le(e,{strict:!1})?e:void 0}function TI(e){return wI(e.accessKeyAddress)}function EI(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(M.random(8))%e)}function DI(e){return TI(e)??e.address}function OI(e){return kI(e)!==void 0}function kI(e){let t=TI(e);if(t===void 0)return fI(e)?e:void 0;let n=e.delegate;if(n&&fI(n)&&n.address.toLowerCase()===t.toLowerCase())return n}async function AI(e,t){let n=kI(t);if(!n)return M.random(32);let{config:r}=n,i=await Be.accounts.getConfigCommitment(e,{account:n.address}),a=r?Ge.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 jI(e,t){let n=sF(e);if(n)try{let r=ie({abi:GF,data:n});if(r.errorName!==`SignerConfigChanged`&&r.errorName!==`RootKeyRetired`)return;let[i]=r.args;return i.toLowerCase()===t.signer.toLowerCase()?new eS({cause:e,channelId:t.channelId,reason:r.errorName,signer:i}):void 0}catch{return}}async function MI(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return lF({account:n},()=>Ae(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}}))}async function NI(e,t){return await Fe(e,t)}function PI(e,t,n=!1){let r=e.request.methodDetails,i=CI(r)?wI(r.escrowContract)??wI(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!II(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!II(i,a)?i:a}function FI(e,t,n,r){return pC({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${t.descriptor?.payer??r.address}`})}function II(e,t){return e.toLowerCase()===t.toLowerCase()}function LI(e,t){let n=kI(e);if(!n?.config)return;let{config:r}=n;if(Ge.getCommitment(r).toLowerCase()!==t.salt.toLowerCase()&&(BigInt(r.version??0n)!==0n||Ge.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 RI(e,t,n,r,i,a=SA){let o=LF({...n,chainId:i,escrow:a}),s=rA(r);LI(t,n);let c=await hI(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function zI(e,t,n,r,i,a=SA){let o=await RI(e,t,n,r,i,a),s=await gI(e,t,{channelId:o.channelId,cumulativeAmount:rA(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function BI(e,t,n){let r=DI(t),i=n.escrow??`0x4d50500000000000000000000000000000000000`,a=n.operator??`0x0000000000000000000000000000000000000000`,o=n.salt??await AI(e,t),s=rA(n.deposit),c=rA(n.initialAmount),l=ae({abi:GF,functionName:`open`,args:[n.payee,a,n.token,s,o,r]}),u=await NI(e,await MI(e,{account:t,calls:[...n.prefixCalls??[],{to:i,data:l}],feePayer:n.feePayer,feeToken:n.feeToken??n.token,validAfter:EI()})),d=Ue.deserialize(u),f={authorizedSigner:r,expiringNonceHash:BF(zF({...n.feePayer?{feePayer:!0}:{},transaction:d}),{sender:t.address}),operator:a,payee:n.payee,payer:t.address,salt:o,token:n.token},p=LF({...f,chainId:n.chainId,escrow:i});return{action:`open`,type:`transaction`,channelId:p,transaction:u,signature:await hI(e,t,{channelId:p,cumulativeAmount:c},i,n.chainId),descriptor:f,cumulativeAmount:c.toString(),authorizedSigner:f.authorizedSigner}}async function VI(e,t,n,r,i,a,o=SA,s=[],c=n.token){let l=LF({...n,chainId:i,escrow:o}),u=rA(r);return{action:`topUp`,type:`transaction`,channelId:l,transaction:await NI(e,await MI(e,{account:t,calls:[...s,{to:o,data:ae({abi:GF,functionName:`topUp`,args:[n,u]})}],feePayer:a,feeToken:c,validAfter:EI()}).catch(e=>{throw jI(e,{channelId:l,signer:IF(n)})??e})),descriptor:n,additionalDeposit:u.toString()}}var HI=z((()=>{vC(),aS(),fF(),VF(),KF(),CA(),SI()}));function UI(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function WI(e){return UI({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function GI(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(WI(t),t)},delete(t){e.delete(t)}}}function KI(e){return{...e,cumulativeAmount:e.cumulativeAmount.toString(),deposit:e.deposit.toString()}}function qI(e){return{...e,cumulativeAmount:BigInt(e.cumulativeAmount),deposit:BigInt(e.deposit)}}function JI(e,t){eL.set(e,eL.get(t)??t)}async function YI(e,t,n){let r=$I.get(e);r||(r=new Map,$I.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 XI(e,t,n){return YI(eL.get(e)??e,`funding:${t}`,n)}async function ZI(e,t){await YI(e,`write:${WI(t)}`,async()=>{let n=await e.get(WI(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 QI(e,t){await YI(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}var $I,eL,tL=z((()=>{$I=new WeakMap,eL=new WeakMap}));function nL(e){if(e<0n||e>sL)throw new J({reason:`amount exceeds uint96 range`})}async function rL(e,t,n=SA){let{cumulativeAmount:r,descriptor:i,signature:a}=t;return je(e,{address:n,abi:GF,functionName:`verifyVoucher`,args:[oL(i),r,a]})}async function iL(e,t,n=SA,r){return aL(await je(e,{address:n,abi:GF,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function aL(e){return nL(e.settled),nL(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}function oL(e){return{payer:e.payer,payee:e.payee,operator:e.operator,token:e.token,salt:e.salt,authorizedSigner:e.authorizedSigner,expiringNonceHash:e.expiringNonceHash}}var sL,cL=z((()=>{aS(),KF(),CA(),sL=2n**96n-1n}));function lL(e){return`cumulativeAmount`in e}function uL(e){if(lL(e))return BigInt(e.cumulativeAmount)}async function dL(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await ZI(e.store,t):await QI(e.store,WI(t)),e.notifyUpdate(t)}async function fL(e,t,n){let r=uL(n);if(r===void 0)return;let i=await e.store.get(t);i&&i.channelId.toLowerCase()===n.channelId.toLowerCase()&&(i.cumulativeAmount=i.cumulativeAmount>r?i.cumulativeAmount:r,n.action===`close`&&(i.opened=!1),await dL(e,i))}function pL(e){return e?.action!==void 0}function mL(e){return pL(e)&&e.descriptor!==void 0}function hL(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 me(i,t)}function gL(e,t,n,r){let i=hL(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function _L(e){return typeof e==`object`&&!!e}function vL(e){return typeof e==`string`&&le(e,{strict:!1})?e:void 0}function yL(e){let t=e.request.methodDetails;return _L(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:vL(t.escrowContract),escrow:vL(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:vL(t.feeToken),operator:vL(t.operator),configurableVouchers:typeof t.configurableVouchers==`boolean`?t.configurableVouchers:void 0,sessionSnapshot:zx(t,Ux.sessionSnapshot)}:{}}function bL(e,t){if(typeof e==`string`&&le(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function xL(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function SL(e){return typeof e==`string`?e:void 0}async function CL(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=yL(n);(o.chainId!==void 0||i?.length===0)&&bP(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});yP(c,s);let l=s??c.chain?.id;if(bP(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=PI(n,r,t),d=bL(n.request.recipient,`recipient`),f=bL(n.request.currency,`currency`);return{amount:xL(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:UI({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:SL(n.request.suggestedDeposit),token:f}}async function wL(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=iL}=e,o=LF({...r,chainId:i.chainId,escrow:i.escrow});TL({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 TL(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(!II(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!II(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!II(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!II(IF(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function EL(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function DL(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=hL(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function OL(e){let{account:t,client:n,readChannelState:r,snapshot:i,verifyVoucherOnChain:a=rL}=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=IF(i.descriptor),h=OI(t);if(!(_I(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 wL({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:DI(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 kL(e,t){return II(e.address,t.payer)?II(DI(e),IF(t)):!1}function AL(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(pL(r)){if(!mL(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=EL({context:r,snapshot:o.snapshot});return!n&&s&&kL(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&kL(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 jL(e,t,n=!1){switch(e.type){case`open`:return PL(e,t,n);case`recover`:return FL(e,t);case`voucher`:return IL(e,t);case`manual`:return LL(e,t,n)}}async function ML(e,t){if(e)return await kP(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function NL(e,t){let{account:n,amount:r,chainId:i,client:a,token:o}=t;if(e||!WP({chainId:i,currency:o}))return;let s=await XP(a,{account:n,amount:r,chainId:i});if(s)throw s}async function PL(e,t,n){let{account:r,resolved:i}=e;if(OI(r)&&i.configurableVouchers!==!0)throw new $x({signer:r.address});let a=WA({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw});await NL(n,{account:r.address,amount:a,chainId:i.chainId,client:i.client,token:i.token});let o=await BI(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 ML(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await dL(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function FL(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await wL({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:DI(n),token:o.token}}),l=DL({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`);KA(l,a);let u=await RI(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await dL(t,{...d?.channelId===c.channelId&&d.uncertainTopUp?{uncertainTopUp:!0}:{},channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function IL(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;KA(a,e.maxDeposit);let o=await RI(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await dL(t,r),o}async function LL(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=LF({...s,chainId:o.chainId,escrow:o.escrow});TL({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:DI(r),token:o.token});let l=await RL({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await fL(t,o.key,l),l}async function RL(e,t){switch(e.context.action){case`open`:return zL(e);case`topUp`:return BL(e,t);case`voucher`:return VL(e);case`close`:return HL(e)}}async function zL(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=gL(r,i,`cumulativeAmount`,`open`),c=await RI(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 BL(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=gL(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:(await NL(t,{account:n.address,amount:c,chainId:s.chainId,client:s.client,token:s.token}),VI(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await ML(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken))}function VL(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return RI(a.client,t,i,gL(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function HL(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return zI(a.client,t,i,gL(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}var UL,WL,GL,KL=z((()=>{Gx(),aS(),SP(),xS(),PP(),$P(),cL(),VF(),SI(),HI(),tL(),sj(),UL=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),WL=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),GL=Y.object({account:Y.optional(Y.custom()),autoSwap:Y.optional(Y.custom()),action:Y.optional(Y.enum([`open`,`topUp`,`voucher`,`close`])),channelId:Y.optional(WL),cumulativeAmount:Y.optional(dS()),cumulativeAmountRaw:Y.optional(Y.string()),transaction:Y.optional(UL),descriptor:Y.optional(Y.custom()),additionalDeposit:Y.optional(dS()),additionalDepositRaw:Y.optional(Y.string()),depositRaw:Y.optional(Y.string())})}));async function qL(e,t){let n=rR.get(e)??new Map;rR.set(e,n);let r=n.get(t),i,a=new Promise(e=>{i=e});return n.set(t,a),await r,()=>{i(),n.get(t)===a&&n.delete(t)}}function JL(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function YL(e,t,n){try{let r=e.response?.headers.get(q.paymentReceipt);if(r){let e=fA(r);if(e.challengeId===t.id&&JL(n,e))return!0}}catch{}return e.challenges?.some(e=>mj(e)?JL(n,hj(e)):!1)??!1}function XL(e){let{allowedChainIds:t,currencies:n,decimals:r,expectedRecipients:i,maxAmount:a,maxAtomicAmount:o}=e;if((a!==void 0||o!==void 0)&&n===void 0)throw Error(`Tempo session maxAmount and maxAtomicAmount require currencies.`);for(let e of n??[])ZL(a,typeof e==`string`?r:e.decimals);return{chainId:t?.length===1?t[0]:void 0,currencies:n,decimals:r,expectedRecipients:i?new Set(i.map(e=>e.toLowerCase())):void 0,maxAmount:a,maxAtomicAmount:o===void 0?void 0:BigInt(o)}}function ZL(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo session maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo session maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return me(e,t)}}function QL(e,t,n){let r=e.currencies?$M(e.currencies,t.currency,{chainId:t.methodDetails?.chainId??n??e.chainId,decimals:e.decimals}):void 0;if(e.currencies&&!r)throw Error(`Tempo session currency is not allowed: ${t.currency}.`);if(e.expectedRecipients&&(!t.recipient||!e.expectedRecipients.has(t.recipient.toLowerCase())))throw Error(`Unexpected session recipient: ${t.recipient}`);let i=BigInt(t.amount);if(e.maxAtomicAmount!==void 0&&i>e.maxAtomicAmount)throw Error(`Tempo session amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0&&i>ZL(e.maxAmount,r?.decimals))throw Error(`Tempo session amount exceeds maxAmount.`)}function $L(e,t){try{return QL(e,t),!0}catch{return!1}}function eR(e){return typeof e==`object`&&!!e&&e.action===`close`}function tR(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:f}=e,p=XL(e),m=vP({chain:$e,getClient:c,rpcUrl:iM}),h=pP({account:t}),g=(e,t)=>{let n=(p.currencies?$M(p.currencies,e.currency,{chainId:e.methodDetails?.chainId??t??p.chainId,decimals:a}):void 0)?.decimals??a??6;return{decimals:n,maxDeposit:l===void 0?void 0:me(l,n),topUpAmount:u===void 0?void 0:me(u,n)}};l!==void 0&&me(l,6),u!==void 0&&me(u,6);let _=e.origin===void 0?void 0:new URL(e.origin);if(_&&![`http:`,`https:`].includes(_.protocol))throw Error(`Session origins require HTTP or HTTPS`);let v=i??GI(),y={store:v,notifyUpdate:e=>d?.(e)},b=async(e,t,n)=>{let r=h(e.client,t),i=t?.action?t.descriptor:n?.descriptor??EL({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:IF(i)}:{}}})??r},x=async(e,t,n)=>{let{decimals:r,maxDeposit:i}=g(e.challenge.request,e.chainId);return AL({account:await b(e,t,n),entry:n,context:t,decimals:r,maxDeposit:i,resolved:e})},S=bk(Qk,{canHandleChallenge:({challenge:e,context:t})=>mj(e)&&(eR(t)||t===_w||$L(p,e.request)),context:GL,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&QL(p,t.request);let a=await CL({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m});i?.action!==`close`&&t.request.methodDetails?.chainId===void 0&&QL(p,t.request,a.chainId);let c=rE(e),l=cE(e)??_?.origin;if(l!==void 0&&(l===`null`||![`http:`,`https:`].includes(new URL(l).protocol)))throw Error(`Session payments require an HTTP or HTTPS origin`);if(_&&l!==_.origin)throw Error(`Session channel origin mismatch`);let u={...y,origin:l},d=()=>{};try{let e=!pL(i)&&i?.descriptor===void 0;e&&(d=await qL(v,a.key),c&&(await v.get(a.key))?.opened&&await c.prepare());let n=await v.get(a.key);if(n&&n.origin!==l)throw Error(`Session channel origin mismatch`);if(l&&!n&&a.snapshot&&!i?.descriptor&&!_)throw Error(`Session snapshot recovery requires an explicitly configured origin or descriptor`);let o=await x(a,i,n);if(!e&&c&&o.type===`open`){d=await qL(v,a.key);let e=await v.get(a.key);if(e&&e.origin!==l)throw Error(`Session channel origin mismatch`);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await v.get(a.key)),o=await x(a,i,n))}let s,f=c&&o.type===`open`?{store:{get:e=>v.get(e),async set(e){s=l?{...e,origin:l}:e},delete:e=>v.delete(e)},notifyUpdate(){}}:u,p=await FI(t,await jL(o,f,AP(i?.autoSwap??r,MP)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||YL(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await v.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await ZI(v,e),y.notifyUpdate(e))}return!0}finally{d()}}}else d();return p}catch(e){throw d(),e}}});function C(e,t,n){let r={challenge:e,context:t};return sE(r,nR(n)),S.createCredential(r)}let w=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>XI(v,WI(n),async()=>{s?.throwIfAborted();let c=await v.get(WI(n));if(c?.channelId===n.channelId&&(n=c),n.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let l=n.deposit>r?n.deposit:r,{maxDeposit:u,topUpAmount:d}=g(t.request,n.chainId),f=GA({deposit:l,maxDeposit:u,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:d});f>0n&&await xj({autoSwap:e,additionalDeposit:f,challenge:t,channel:n,channelId:n.channelId,createSessionCredential:(e,t)=>C(e,t,a),onUncertainFunding:async e=>{let t=await v.get(WI(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await ZI(v,n),y.notifyUpdate(n)},fetch:i,input:a,signal:s});let p=l+f;if(p===n.deposit)return;let m=await v.get(WI(n)),h=m?.channelId.toLowerCase()===n.channelId.toLowerCase()?m:n,_={...h,deposit:h.deposit>p?h.deposit:p};await ZI(v,_),y.notifyUpdate(_)});return JT(S,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!mj(e))return;let c=t===void 0?void 0:GL.parse(t);if(pL(c))return;QL(p,e.request);let l=await CL({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),u=await v.get(l.key);if(!u?.opened)return;let d=nR(i);if(u.origin!==d)throw Error(`Session channel origin mismatch`);let f=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,h=u.cumulativeAmount+lA(e),g=f?BigInt(f.requiredCumulative):h,_=g>h?g:h,y=f?BigInt(f.deposit):u.deposit,x=y>u.deposit?y:u.deposit;_<=x&&x===u.deposit||!kL(await b(l,c,u),u.descriptor)||await w({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:x,fetch:r,input:i,requiredCumulative:_,signal:a})}),eE(S,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!mj(e))return u;if(!pA(u))return cA(cC(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await CL({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,p=await v.get(f),h={assertVoucherWithinLocalLimit:t=>KA(t,g(e.request,p?.chainId).maxDeposit),createSessionCredential:(e,t)=>C(e,t,c),fetch:i,getChannel:()=>p??null,async topUpIfNeeded({deposit:n,requiredCumulative:r,signal:a}){p&&await w({autoSwap:t===void 0?void 0:GL.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return Mj({onNeedVoucher:(t,n)=>Nj({challenge:e,driver:h,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function nR(e){let t=new URL(e instanceof Request?e.url:e,globalThis.location===void 0?void 0:globalThis.location.href);if(![`http:`,`https:`].includes(t.protocol))throw Error(`Session payments require an HTTP or HTTPS origin`);return t.origin}var rR,iR=z((()=>{$T(),pE(),Gx(),vC(),eN(),vw(),xk(),mP(),SP(),PP(),aM(),eA(),VF(),CA(),HI(),tL(),KL(),sj(),rR=new WeakMap}));function aR(e,t){sR.set(e,t)}function oR(e){let t=sR.get(e);if(!t)throw Error(`Session manager internals are unavailable.`);return t}var sR,cR=z((()=>{sR=new WeakMap}));function lR(e){let t=null;return{wait(n=()=>!0){if(t)throw Error(`${e} wait already in progress`);return new Promise((e,r)=>{t={predicate:n,resolve:e,reject:r}})},settle(e){if(!t||!t.predicate(e))return;let n=t;t=null,n.resolve(e)},reject(e){if(!t)return;let n=t;t=null,n.reject(e)}}}function uR(e){let t=lR(`close-ready`),n=lR(`receipt`);return{waitForReceipt(e){return n.wait(e)},waitForCloseReady(){let n=e.getSocketSession()?.closeReadyReceipt;return n?Promise.resolve(n):t.wait()},settleReceipt(e){n.settle(e)},settleCloseReady(n){let r=e.getSocketSession();r&&r.challenge.id===n.challengeId&&r.channelId===n.channelId&&(r.closeReadyReceipt=n),t.settle(n)},rejectReceipt(e){n.reject(e)},rejectCloseReady(e){t.reject(e)}}}var dR=z((()=>{}));function fR(e){return e.method===Vx.tempo&&e.intent===Hx.charge}function pR(e){if(!fR(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function mR(e,t,n){if(!n)return t;let r={...OD(_j(e)?e.headers:void 0),...OD(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===q.paymentSession.toLowerCase())?t:{...t,headers:{...r,[q.paymentSession]:n}}}function hR(e,t){return e===void 0?t:{...GL.parse(e),...t}}function gR(e){let t=e.decimals??6,n=e.webSocket??globalThis.WebSocket;return{decimals:t,fetch:e.fetch??globalThis.fetch.bind(globalThis),maxVoucherCumulative:e.maxDeposit===void 0?null:me(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:me(e.topUpAmount,t),WebSocket:n}}function _R(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&bP(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=gR(e),i;function a(e){let t=new URL(_j(e)?e.url:String(e),typeof location>`u`?void 0:location.href);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`SessionManager: session payments require an HTTP origin`);let n=t.origin;if(i!==void 0&&i!==n)throw Error(`SessionManager: session payment origin mismatch`);return i=n,n}if(ZD(r.fetch))throw TypeError(`SessionManager: the fetch sets spending options (maxPayment, authorize, funders or tokens), which accept only charges. Pass a fetch without them.`);let o=XD(r.fetch),s=QD(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??(_j(e)?e.redirect:void 0))===`manual`?`manual`:`error`});if(r.url&&new URL(r.url).origin!==n)throw Error(`SessionManager: session response origin mismatch`);return r};let c=r.fetch;o&&(r.fetch=IC(c,o));let l=vP({chain:$e,getClient:e.client?()=>e.client:e.getClient,rpcUrl:iM}),u=pP({account:e.account}),d=QA(),f=e.credentialContext===void 0?void 0:hR(e.credentialContext,{}),p=uR({getSocketSession:()=>d.socketSession}),m=e.channelStore??GI(),h=new Set,g;async function _(e){let t=await m.get(e);if(t?.opened&&!h.has(t.channelId)){if(t.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return t}}let v=e=>{if(e.origin!==void 0&&e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return e.origin=i,ZI(m,e)},y={async get(e){let t=await _(e);return t&&g&&(g.seenExisting.add(e),!g.committed&&!g.created.has(e)&&(g.resumed??=t)),t},async set(e){let t=WI(e);e.opened&&h.delete(e.channelId),g?.trackCreates&&!g.seenExisting.has(t)&&g.created.set(t,e),await v(e)},delete:e=>QI(m,e)};JI(y,m);async function b(e){let t=WI(e),n=await m.get(t);if(e.uncertainTopUp||n?.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);h.add(e.channelId),g?.seenExisting.delete(t),g?.resumed===e&&(g.resumed=void 0),await Promise.resolve(QI(m,t)).catch(()=>void 0)}async function x(){let e=g;if(e?.created.size){for(let[t,n]of e.created){let e=await m.get(t);if(n.uncertainTopUp||e?.channelId===n.channelId&&e.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before discarding the channel.`);h.add(n.channelId),await Promise.resolve(QI(m,t)).catch(()=>void 0)}e.created.clear(),await L(e.committed??e.previous)}}function S(e){let t=zx(e.request.methodDetails,Ux.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=g;if(!n?.created.size||!d.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&d.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=rj({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function C(e){return FA(d,e)}function w(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function T(e){let t=g,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit&&!e.uncertainTopUp||(t.resumed=void 0,t.committed=rj({channel:d.channel,spent:d.spent,state:d.state}))}let E=tR({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:y,onChannelUpdate(e){e.channelId!==d.channel?.channelId&&(d.spent=0n),d.channel=e,d.lastChallenge&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}}),ee=ZT(E);ee&&JT(E,e=>oe(()=>Promise.resolve(ee(e)),e.signal)),tE(E);let D=pF({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),O=ED({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[E],onChallenge:async(e,t)=>{if(!pj(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&mO(e)===mO(d.lastChallenge);n&&n.challengesReceived++,!i&&(S(e)||(n?.created.size?await x():r&&await L(n.committed??n.previous)),d.lastChallenge=e,C({type:`challengeReceived`,challengeId:e.id}))}});function k(e,t){let n={challenge:e,context:hR(f,t)};return i&&sE(n,i),E.createCredential(n)}function te(e){$A({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:d})}function A(e=d.state.status===`active`?d.state.units:0){!d.channel||!d.lastChallenge||d.state.status!==`active`&&d.state.status!==`withdrawable`&&d.state.status!==`closeRequested`&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:d.channel,spent:d.spent.toString(),units:e})}async function j(t){let r=t.headers.get(q.paymentSessionSnapshot);if(!r)return;let i=TA(r);bP(e.allowedChainIds,i.chainId),PI({request:{methodDetails:{escrow:i.escrow}}},e.escrow,n);let a=await l({chainId:i.chainId});yP(a,i.chainId);let o=u(a),{entry:s,spent:c}=await OL({account:await e.resolveAccount?.({account:o,chainId:i.chainId,operation:{authority:IF(i.descriptor),kind:`authorizePaymentChannel`}})??o,client:a,snapshot:i});return ie(s.cumulativeAmount),await Promise.resolve(y.set(s)).catch(()=>void 0),d.channel=s,d.spent=c,s}async function M(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=_j(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=_j(t)?t.url:t,l={...s,method:`HEAD`,headers:{...OD(i),...OD(n?.headers),[q.acceptPayment]:`${Vx.tempo}/${Hx.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await j(t);let n=RS(t).find(fR);if(!n||!pR(n))return;let i=new URL(String(c),typeof location<`u`?location.href:void 0);if(t.url&&new URL(t.url).origin!==i.origin)return;gE(n,i,e.trustedTempoProofRealms);let a=await D.createCredential({challenge:n,context:{}}),o=await r.fetch(c,iT({...l,redirect:`manual`},GS(n),a));return o.ok?await j(o):void 0}catch{return}}function ne(e,t){let n=d.socketSession;return tj({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:d.channel?.channelId===t?d.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:d.spent,tickCost:n?.tickCost})}function N(e,t){let n=hj(t);if(!n)return;if(LF({...n.descriptor,chainId:n.chainId,escrow:n.escrow}).toLowerCase()!==n.channelId.toLowerCase())throw Error(`close snapshot descriptor does not match its channel ID`);if(n.channelId.toLowerCase()!==e.channelId.toLowerCase())throw Error(`close snapshot channel ID does not match local session`);if(n.chainId!==e.chainId||n.escrow.toLowerCase()!==e.escrow.toLowerCase())throw Error(`close snapshot payment scope does not match local session`);let r=BigInt(n.acceptedCumulative),i=BigInt(n.spent);if(r<0n||i<0n)throw Error(`close snapshot amounts must not be negative`);if(i>r)throw Error(`close snapshot spent exceeds accepted cumulative amount`);if(r>e.cumulativeAmount)throw Error(`close snapshot accepted cumulative exceeds local voucher state`);return{acceptedCumulative:r,spent:i}}function P(e,t){let n=N(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(d.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>d.spent&&(d.spent=i),n}function re(e,t=e.challenge,n=!1){let r=(n?P(e,t):N(e.channel,t))?.acceptedCumulative??ne(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return ie(r),r.toString()}function ie(e){BA({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let ae,F;async function oe(e,t){if(F)throw F;for(;;){let e=ae;if(!e)break;if(!t)await e;else{t.throwIfAborted();let n;try{await Promise.race([e,new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0})})])}finally{t.removeEventListener(`abort`,n)}}}if(t?.throwIfAborted(),F)throw F;let n=e();ae=n;try{return await n}catch(e){throw e instanceof Xj&&(F=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{ae===n&&(ae=void 0)}}async function se(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return XI(m,WI(d.channel),async()=>{let{knownDeposit:t,...n}=e,i=d.channel?await y.get(WI(d.channel)):void 0;if(i?.channelId===e.channelId&&i.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let a=await xj({...n,channel:d.channel,createSessionCredential:k,fetch:r.fetch,onUncertainFunding:async e=>{let t=await y.get(WI(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};d.channel?.channelId===e.channelId&&(d.channel=n),await y.set(n),T(n)}});te(a);let o=d.channel,s=dj({additionalDeposit:e.additionalDeposit,channel:d.channel,channelId:e.channelId,challengeId:d.lastChallenge?.id,currentState:d.state,knownDeposit:t,receipt:a,spent:d.spent});if(s?.channel&&d.lastChallenge){let e=s.channel;for(;;){await y.set(e);let t=d.channel;if(t===o)break;if(!t)return a;let n=s.channel;e=t.channelId===n.channelId?{...t,deposit:t.deposit>n.deposit?t.deposit:n.deposit,cumulativeAmount:t.cumulativeAmount>n.cumulativeAmount?t.cumulativeAmount:n.cumulativeAmount}:t,o=t}if(e.channelId!==s.channel.channelId)return a;d.channel=e,C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}return a})}async function I(e){return oe(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=GA({deposit:n,maxDeposit:r.maxVoucherCumulative,requiredCumulative:e.requiredCumulative,suggestedDeposit:e.challenge.request.suggestedDeposit===void 0?void 0:BigInt(e.challenge.request.suggestedDeposit),topUpAmount:r.topUpAmount});i!==0n&&await se({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function ce(e,t){let n=nj({channel:d.channel,channelId:e,challengeId:d.lastChallenge?.id,cumulativeAmount:t,spent:d.spent,state:d.state});n&&d.channel&&(C({type:`activated`,challengeId:n.challengeId,entry:d.channel,spent:n.spent,units:n.units}),await v(d.channel))}async function L(e){let t=ij(e,d.channel);d.channel=t.channel,d.spent=t.spent,d.state=t.state,d.channel?.opened&&await v(d.channel)}function le(e,t=!0){let n=e.headers.get(q.paymentReceipt),r=n?fA(n):null;return t&&te(r),Object.assign(e,{receipt:r,challenge:d.lastChallenge,channelId:d.channel?.channelId??null,cumulative:d.channel?.cumulativeAmount??0n})}async function ue(e,t){if(t?.[bO])return le(await r.fetch(e,CD(t)),!1);if(g)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);a(e),d.lastUrl=e,d.lastHeaders=t?.headers;let n=rj({channel:d.channel,spent:d.spent,state:d.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};g=i;try{await M(e,t),i.trackCreates=!0;let a=mR(e,t,d.channel?.opened?d.channel.channelId:void 0);f&&(a={...a,context:f});let o=!n.channel?.opened;async function s(){let n=i.resumed;return!o||!n?!1:(o=!1,await b(n),a=mR(e,t,void 0),!0)}for(;;){let t;try{t=await O(e,a)}catch(e){if(i.created.size?await x():await L(i.committed??n),await s())continue;throw e}let o=le(t),c=!1;if(o.status===402){let t=await Cj({input:e,init:a,response:o,createSessionCredential:k,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:ce,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:I});t&&(c=!0,o=le(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await x():await L(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function de(e){let t=await Tj({createSessionCredential:k,fetch:r.fetch,getMinimumSpent:()=>d.spent,headers:d.lastHeaders,lastUrl:d.lastUrl,resolveSignedCloseAmount:t=>re(e,t,!0),signedCloseAmount:re(e),setChallenge(e){d.lastChallenge=e},target:e});return t&&(A(),C({type:`closeStarted`}),C({type:`closed`,receipt:t})),t}let fe={createSessionCredential:k,doFetch:ue,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:ie,acceptReceipt(e){te(e)},topUpIfNeeded:I},pe={get channelId(){return d.channel?.channelId},get cumulative(){return d.channel?.cumulativeAmount??0n},get opened(){return d.channel?.opened??!1},get state(){return d.state},fetch:ue,async topUp(e){let t=uj({amount:e,assertVoucherWithinLocalLimit:ie,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return oe(async()=>{if(d.channel?.channelId!==t.channelId||d.lastChallenge!==t.challenge||d.lastUrl!==t.input)throw Error(`Session changed while waiting to top up`);let n=uj({amount:e,assertVoucherWithinLocalLimit:ie,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return se({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){if(t?.[bO])throw Error(`SessionManager.sse requires payment; use fetch for unpaid streams.`);return Ej(e,t,fe)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=yj(e);a(n);let i=t?.signal?{signal:t.signal}:void 0;await M(n,i);let o=d.channel?.opened?d.channel.channelId:void 0,{challenge:s,credential:c,httpUrl:l,wsUrl:u}=await Fj({async createSessionCredential(e,i){return d.lastChallenge=e,await XT(E,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),k(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){d.lastUrl=e.toString()},probeInit:mR(n,i,o),signal:t?.signal});return d.lastChallenge=s,Bj({challenge:s,credential:c,httpUrl:l,WebSocket:r.WebSocket,wsUrl:u,options:t,createSessionCredential:k,getChannel:()=>d.channel,setSocketSession(e){d.socketSession=e},async refreshChallenge(){let e=await Pj({fetch:r.fetch,input:l,probeInit:mR(l,i,d.channel?.opened?d.channel.channelId:void 0),signal:t?.signal});return d.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:ie,acceptReceipt:te,rejectCloseReady:p.rejectCloseReady,rejectReceipt:p.rejectReceipt,settleCloseReady:p.settleCloseReady,settleReceipt:p.settleReceipt,topUpIfNeeded:I,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=qA({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===qj.OPEN){let r=await aj({activeSocket:n,createSessionCredential:k,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return A(),C({type:`closeStarted`}),C({type:`closed`,receipt:r}),r}return de(t)}};return aR(pe,{consumeSseResponse(e,t,n){let r=a(e);if(t.url&&new URL(t.url).origin!==r)throw Error(`SessionManager: session response origin mismatch`);return Dj(e,t,n,fe)},rehydrate({channel:e,challenge:t,input:n,spent:r}){let i=a(n);if(e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!pj(t))throw Error(`Cannot restore session: challenge is not tempo/session.`);if(r<0n)throw Error(`Cannot restore session: spent must not be negative.`);if(r>e.cumulativeAmount)throw Error(`Cannot restore session: spent exceeds local voucher state.`);ie(e.cumulativeAmount);let o=N(e,t),s=o&&o.spent>r?o.spent:r;d.lastUrl=n,d.lastChallenge=t,d.channel=e,d.spent=s,C({type:`challengeReceived`,challengeId:t.id}),C({type:`activated`,challengeId:t.id,entry:e,spent:s.toString(),units:0})}}),pe}var vR=z((()=>{sC(),DO(),$T(),pE(),bE(),lT(),Gx(),qC(),mP(),SP(),FF(),aM(),HI(),tL(),KL(),iR(),VF(),CA(),MA(),cR(),dR(),sj(),Zj(),(function(e){e.serializeSnapshot=wA,e.deserializeSnapshot=TA})(_R||={})}));function yR(e){return e instanceof Date?e:new Date(e)}function bR(e){let t=e.getTime();if(!Number.isFinite(t))throw new J({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new J({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new J({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function xR(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new J({reason:`periodCount is invalid`});let t=BR[e.periodUnit];if(t===void 0)throw new J({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>zR)throw new J({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new J({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function SR(e){let{challengeExpires:t,request:n}=e;xR(n);let r=bR(yR(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new J({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function CR(e){let t=IR(e.currency,`currency`),n=IR(e.recipient,`recipient`);return[{address:t,selector:RR,recipients:[n]}]}function wR(e){try{let t=M.fromBytes(te.toBytes(e));if(M.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new J({reason:`challenge id must encode 32 bytes`})}}async function TR(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=DR({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:qe.getSignPayload(o)}),c=Je.from(s);if(c.type===`keychain`||c.type===`configurable`)throw new J({reason:`keyAuthorization must use a primitive signature`});return qe.from(o,{signature:Je.serialize(JF(c))})}function ER(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new J({reason:`invalid keyAuthorization payload`});let o=OR(i.signature),s=kR(o);if(AR({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==wR(n))throw new J({reason:`keyAuthorization challenge mismatch`});return jR(o,a),NR(MR(o),a),PR(o.scopes,a),{authorization:o,source:{address:FR(o,s),chainId:r}}}function DR(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return qe.from({address:IR(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:bR(yR(i.subscriptionExpires)),limits:[{token:IR(i.currency,`currency`),limit:BigInt(i.amount),period:xR(i)}],scopes:CR(i),type:t.keyType,witness:wR(n)})}function OR(e){try{return qe.deserialize(e)}catch(e){throw e instanceof qe.InvalidSignatureTypeError?new J({reason:`keyAuthorization must use a primitive signature`}):new J({reason:`invalid keyAuthorization payload`})}}function kR(e){let t=e.signature;if(!t)throw new J({reason:`keyAuthorization must use a primitive signature`});return t}function AR(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new J({reason:`keyAuthorization chainId mismatch`});if(t){if(!ue(n.address,IR(t.accessKeyAddress,`accessKeyAddress`)))throw new J({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new J({reason:`keyAuthorization key type mismatch`})}}function jR(e,t){if(SR({request:t}),e.expiry!==bR(yR(t.subscriptionExpires)))throw new J({reason:`keyAuthorization expiry mismatch`})}function MR(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new J({reason:`keyAuthorization must contain exactly one token limit`});return t}function NR(e,t){if(!ue(e.token,IR(t.currency,`currency`)))throw new J({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new J({reason:`keyAuthorization amount mismatch`});if(e.period!==xR(t))throw new J({reason:`keyAuthorization period mismatch`})}function PR(e,t){if(!e||e.length!==1)throw new J({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=IR(t.currency,`currency`),r=IR(t.recipient,`recipient`),i=new Set;for(let t of e){if(!ue(t.address,n))throw new J({reason:`keyAuthorization call target mismatch`});let e=LR(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new J({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new J({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!ue(t.recipients[0],r))throw new J({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new J({reason:`keyAuthorization must allow transferWithMemo`})}function FR(e,t){let n=qe.getSignPayload(e);try{let e=Je.extractAddress({payload:n,signature:t});if(!qF(t)||!Je.verify(t,{address:e,payload:n}))throw new J({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof J?e:new J({reason:`keyAuthorization signature is invalid`})}}function IR(e,t){if(!le(e))throw new J({reason:`${t} must be an address`});return e.toLowerCase()}function LR(e){return typeof e==`string`?e.toLowerCase():``}var RR,zR,BR,VR=z((()=>{aS(),$F(),RR=`0x95777d59`,zR=(1n<<64n)-1n,BR={dev_second:1n,day:86400n,week:604800n}}));function HR(e={}){let t=vP({chain:ve,requireChain:!0,getClient:e.getClient,rpcUrl:iM}),n=pP({account:e.account});return bk($k,{context:GR,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??$j.testnet,o=await t({chainId:a});if(o.chain?.id!==a)throw Error(`Subscription chain mismatch: expected ${a}, got ${o.chain?.id??`unknown`}.`);let s=n(o,i),c=i?.accessKey??e.accessKey??r.request.methodDetails?.accessKey;if(!c)throw Error("No `accessKey` provided. The subscription challenge must include `accessKey`, or the client must pass one to parameters/context.");WR(r.request),await e.validateRequest?.(r.request);let l=await UR(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=ER({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:qe.serialize(l),type:`keyAuthorization`},request:r.request});if(!ue(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return pC({challenge:r,payload:{signature:qe.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function UR(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await TR({accessKey:n,account:r,challengeId:i,chainId:a,request:o});if(s)return s;let c=await e.request({method:`wallet_authorizeAccessKey`,params:[{address:n.accessKeyAddress,expiry:bR(yR(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:M.fromNumber(BigInt(o.amount)),period:xR(o)}],scopes:CR(o),witness:wR(i)}]});return qe.fromRpc(c.keyAuthorization)}function WR(e){xR(e),bR(yR(e.subscriptionExpires))}var GR,KR=z((()=>{vC(),xk(),mP(),SP(),xS(),aM(),eA(),VR(),GR=Y.object({accessKey:Y.optional(Y.custom()),account:Y.optional(Y.custom())})}));function qR(e={}){let t=e.expectedChainId!==void 0&&(e.allowedChainIds===void 0||e.allowedChainIds.includes(e.expectedChainId)),n=e.expectedChainId===void 0?e:{...e,allowedChainIds:t?[e.expectedChainId]:[]};return[pF(e),JR(n)]}var JR,YR=z((()=>{iR(),vR(),FF(),KR(),JR=Object.assign(tR,{manager:_R}),(function(e){e.charge=pF,e.common=qR,e.session=JR,e.subscription=HR})(qR||={})})),XR=z((()=>{FF(),YR(),KR(),tL(),iR(),vR()})),ZR=it({orderTempoChargeChallengesByBalance:()=>$R,readTempoKeystore:()=>yz,resolveTempoAccount:()=>bz,tempo:()=>ez});async function QR(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}async function $R(e,t){let n=[],r=[];for(let[t,i]of e.entries())sz(i)&&(n.push(t),r.push(i));if(r.length<2)return[...e];let i=await cz(t).catch(()=>void 0);if(!i)return[...e];let a=await Promise.all(r.map(async(e,t)=>({challenge:e,index:t,score:await lz(e,i)})));a.sort((e,t)=>Oz.indexOf(e.score)-Oz.indexOf(t.score)||e.index-t.index);let o=[...e];for(let[e,t]of n.entries())o[t]=a[e].challenge;return o}function ez(){let e;return $N({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:t,options:n,methodOpts:r}){let i=VM(n.account),a=t.request,o=a.currency,s=oz(r),c=pz({autoSwap:s.autoSwap??n.autoSwap,payWith:s.payWith??n.payWith,slippage:s.slippage??n.slippage,tokenIn:s.tokenIn}),l=o??``,u=a.decimals??6,d,f,p,m=!1,h=process.env.MPPX_PRIVATE_KEY?.trim()||(gM(i)?void 0:await HM(i).get());if(!h&&gM(i)&&xz()){m=!0;let e=bz(i);if(e){let r=bM(n.rpcUrl,{network:n.network});p=N({chain:await SM({network:n.network,rpcUrl:r}),transport:L(r)}),dz({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let i=o?await EM(p,o,e.wallet_address).catch(()=>void 0):void 0;l=i?.symbol??o??``,u=i?.decimals??a.decimals??6}}else if(h)f=R(h);else{let e=Cz();if(e){let t=await HM(e).get();t&&(f=R(t))}if(!f)throw n.account?new B({code:`ACCOUNT_NOT_FOUND`,message:`Account "${i}" not found.`,exitCode:69}):new B({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!m&&f){let e=bM(n.rpcUrl,{network:n.network});p=N({chain:await SM({network:n.network,rpcUrl:e}),transport:L(e)}),dz({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let r=o?await EM(p,o,f.address).catch(()=>void 0):void 0;l=r?.symbol??o??``,u=r?.decimals??a.decimals??6}if(m)return{tokenSymbol:l,tokenDecimals:u,explorerUrl:d,methods:[],async createCredential(e){let t=e.headers.get(`www-authenticate`);if(!t)throw Error(`No WWW-Authenticate header in 402 response.`);return Sz(t)}};if(!f||!p)throw new B({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let g=qR({account:f,...s.allowCustomEscrow===void 0?{}:{allowCustomEscrow:s.allowCustomEscrow},getClient:()=>p,...c===void 0?{}:{autoSwap:c},maxDeposit:(()=>{if(t.intent!==`session`)return;let e=t.request.suggestedDeposit,n=(s.deposit===void 0?void 0:String(s.deposit))??e??(TM(p.chain)?`10`:void 0);if(!n)throw new B({code:`MISSING_DEPOSIT`,message:`Session payment requires a deposit. Use -M deposit=<amount> or connect to testnet.`,exitCode:2});return n})()}),_=(()=>{if(!s.channel)return;let e=s.channel,t=hz(e);return{channelId:e,...t!==void 0&&{cumulativeAmountRaw:t.toString()}}})();return e={descriptor:void 0,async signVoucher({channelId:n,cumulativeAmount:r,escrowContract:i,chainId:a,action:o=`voucher`}){let s=e?.descriptor;if(!s)throw Error(`session descriptor not available`);let c={channelId:n,cumulativeAmount:r},l=await hI(p,f,c,i,a);return pC({challenge:t,payload:{action:o,channelId:n,...o===`close`?{closeSignature:await gI(p,f,c,i,a)}:{},descriptor:s,cumulativeAmount:r.toString(),signature:l},source:`did:pkh:eip155:${a}:${f.address}`})},source:`did:pkh:eip155:${p.chain.id}:${f.address}`},{tokenSymbol:l,tokenDecimals:u,explorerUrl:d,methods:[...g],credentialContext:_}},prepareCredentialRequest({challenge:e,headers:t}){e.intent===`session`&&(t.Accept=`text/event-stream`)},async handleResponse(t){if(t.challenge.intent!==`session`||!e)return!1;let{challenge:n,credential:r,response:i,fetchUrl:a,fetchInit:o,verbose:s}=t,{silent:c,confirmEnabled:l,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,shownKeys:p}=t,m=c?e=>{}:e=>process.stderr.write(e),h=cC(r),g=n.request,_=g.methodDetails,v=h.payload.channelId,y=_?.escrowContract??_?.escrow??`0x4d50500000000000000000000000000000000000`,b=_?.chainId??0,x=BigInt(g.amount),S=`cumulativeAmount`in h.payload&&h.payload.cumulativeAmount?BigInt(h.payload.cumulativeAmount):0n;if(`descriptor`in h.payload&&(e.descriptor=h.payload.descriptor),s>=1){if(h.payload.action===`open`){let e=g.suggestedDeposit,t=e?` ${X.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
237
+ `)}function lM(e,t,n){if(OM.has(e)&&typeof t==`string`)return`${t} ${X.dim(`(${yM(BigInt(t),n.tokenSymbol,n.tokenDecimals)})`)}`;if(e===`chainId`&&typeof t==`number`){let e=CM({id:t,name:``});return e?`${t} ${X.dim(`(${e})`)}`:String(t)}return typeof t==`string`&&/^0x[0-9a-fA-F]{40}$/.test(t)?n.explorerUrl?pM(`${n.explorerUrl}/address/${t}`,t):t:typeof t==`string`&&/^https?:\/\//.test(t)?X.link(t,t):String(t)}function uM(e){try{let t=e.replace(/^0x0*/,``);if(!t)return;let n=Uint8Array.from(t.match(/.{1,2}/g).map(e=>Number.parseInt(e,16))),r=new TextDecoder().decode(n);return/^[\x20-\x7e]+$/.test(r)?r:void 0}catch{return}}function dM(e,t){if(e===`realm`&&typeof t==`string`)try{let e=new URL(t.includes(`://`)?t:`https://${t}`);return X.link(e.href,t)}catch{}return String(t)}function fM(e){return typeof e==`object`&&e?JSON.stringify(e):String(e)}function pM(e,t){return X.link(e,t)}function mM(e){if(!e)return{};let t=Array.isArray(e)?e:[e],n={};for(let e of t){let t=e.indexOf(`=`);if(t===-1)throw Error(`Invalid method option format: ${e} (expected key=value)`);n[e.slice(0,t)]=e.slice(t+1)}return n}function hM(e=process.env){if(e.CLAUDECODE)return!0;for(let[t,n]of Object.entries(e))if(n&&(t===`CODEX`||t.startsWith(`CODEX_`)))return!0;return!1}function gM(e){return e.startsWith(`tempo:`)}function _M(e){let t=Ze.createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.on(`close`,()=>n(void 0)),t.question(`${X.bold(`▸ ${e}:`)} `,e=>{t.close(),n(e.trim()||void 0)})})}function vM(e,t=!1){let n=Ze.createInterface({input:process.stdin,output:process.stderr});return new Promise(r=>{let i=t?`(Y/n)`:`(y/N)`;n.question(`${X.bold(`▸ ${e}`)} ${X.dim(i)} `,e=>{n.close();let i=e.trim().toLowerCase();r(i===``?t:i===`y`)})})}function yM(e,t,n=6,r){let[i,a]=(Number(e)/10**n).toString().split(`.`),o=i.replace(/\B(?=(\d{3})+(?!\d))/g,`_`),s=r?.explorerUrl&&r.token?X.dim(X.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):X.dim(t);return`${a?`${o}.${a}`:o} ${s}`}function bM(e,t={}){return e??(t.network?kM[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}function xM(e={}){if(e.network)return e.network;if(!e.rpcUrl&&!(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()))return`testnet`}async function SM(e={}){let t=bM(e.rpcUrl,{network:e.network});if(!t)return ve;let{getChainId:n}=await import(`viem/actions`),r=await n(N({transport:L(t)})),i=Object.values(await import(`viem/tempo/chains`)).filter(e=>typeof e==`object`&&!!e&&`id`in e&&e.id===r),a=i.find(e=>`serializers`in e&&e.serializers)??i[0];if(!a)throw Error(`Unknown chain ID ${r} from RPC ${t}`);return a}function CM(e){return{[ve.id]:`mainnet`,[ye.id]:`testnet`}[e.id]??e.name}function wM(e){return typeof e==`bigint`?e:e.amount}function TM(e){return e.id!==ve.id}async function EM(e,t,n,r={}){let{Actions:i}=await import(`viem/tempo`),[a,o]=await Promise.all([i.token.getBalance(e,{account:n,token:t}).then(wM).catch(()=>0n),i.token.getMetadata(e,{token:t}).catch(e=>{if(r.requireDecimals)throw e;return{symbol:t}})]),s={"0x20c0000000000000000000000000000000000000":`PathUSD`,"0x20C000000000000000000000b9537d11c60E8b50":`USDC`}[t]??o.symbol,c=`decimals`in o&&typeof o.decimals==`number`?o.decimals:6;if(r.requireDecimals&&!(`decimals`in o&&typeof o.decimals==`number`))throw Error(`Token decimals are unavailable.`);return{balance:a,symbol:s,decimals:c,token:t}}async function DM(e,t){if(t?.chain){let n=N({chain:t.chain,transport:L(t.rpcUrl)}),r=t.chain.blockExplorers?.default?.url,i=X.dim(`(${CM(t.chain)})`);return TM(t.chain)?(await Promise.all(NM.map(t=>EM(n,t,e)))).filter(e=>e.balance>0n).map(e=>`${yM(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`):(await Promise.all(MM.map(t=>EM(n,t,e)))).map(e=>`${yM(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`)}let n=N({chain:ve,transport:L(bM())}),r=ve.blockExplorers?.default?.url,i=(await Promise.all(MM.map(t=>EM(n,t,e)))).map(e=>yM(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token}));if(t?.includeTestnet!==!1){let t=N({chain:ye,transport:L()}),n=ye.blockExplorers?.default?.url,r=await Promise.all(NM.map(n=>EM(t,n,e)));for(let e of r)e.balance>0n&&i.push(`${yM(e.balance,e.symbol,e.decimals,{explorerUrl:n,token:e.token})} ${X.dim(`(testnet)`)}`)}return i}var OM,kM,AM,jM,MM,NM,PM=z((()=>{Qj(),aM(),OM=new Set([`amount`,`suggestedDeposit`,`minVoucherDelta`]),kM={mainnet:iM[$j.mainnet],testnet:iM[$j.testnet]},AM=`0x20c0000000000000000000000000000000000000`,jM=`0x20C000000000000000000000b9537d11c60E8b50`,MM=[AM,jM],NM=[`0x20c0000000000000000000000000000000000000`,`0x20c0000000000000000000000000000000000001`,`0x20c0000000000000000000000000000000000002`,`0x20c0000000000000000000000000000000000003`]}));function FM(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:JM}function IM(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function LM(e){return new B({code:`KEYCHAIN_UNAVAILABLE`,message:`Linux keyring requires secret-tool. Install libsecret-tools.`,hint:`On Debian/Ubuntu, run: sudo apt install libsecret-tools gnome-keyring dbus-x11`,exitCode:69,cause:e})}function RM(e){if(e&&IM(e,`secret-tool`))throw LM(e)}function zM(e){return e.map(e=>{if(/[\r\n]/.test(e))throw Error(`Keychain values cannot contain line breaks.`);return`"${e.replace(/["\\]/g,`\\$&`)}"`}).join(` `)}function BM(e,t,n){return new Promise(r=>{let i=m.execFile(e,t,{timeout:FM()},(e,t,n)=>{r({stdout:t.trim(),stderr:n.trim(),error:e})});n!==void 0&&i.stdin?.end(n)})}function VM(){let e=c.join(process.env.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`mppx`,`default`);return{get(){try{return t.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(n){t.mkdirSync(c.dirname(e),{recursive:!0}),t.writeFileSync(e,n,`utf-8`)},clear(){try{t.unlinkSync(e)}catch{}}}}function HM(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:VM().get())}function UM(e=`main`){let t=qM;return{async list(){let e=x.platform();if(e===`darwin`){let{stdout:e,error:n}=await BM(`security`,[`dump-keychain`]);if(n)return[];let r=[],i=e.split(`keychain:`);for(let e of i){let n=e.match(/"svce"<blob>="([^"]*)"/),i=e.match(/"acct"<blob>="([^"]*)"/);n?.[1]===t&&i?.[1]&&r.push(i[1])}return r}if(e===`linux`){let{stdout:e,stderr:n,error:r}=await BM(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(RM(r),r)return[];let i=`${e}\n${n}`,a=[],o=i.matchAll(/\baccount = (.+)/g);for(let e of o)e[1]&&a.push(e[1]);return a}throw Error(`Unsupported platform: ${e}`)},async get(){let n=x.platform();if(n===`darwin`){let{stdout:n,error:r}=await BM(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await BM(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return RM(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=x.platform();if(r===`darwin`){let r=`${zM([`add-generic-password`,`-s`,t,`-a`,e,`-w`,n])}\n`;await BM(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:i}=await BM(`security`,[`-i`],r);if(i)throw i;return}if(r===`linux`){let r=m.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),FM());return r.stdin?.write(n),r.stdin?.end(),new Promise((e,t)=>{r.on(`close`,n=>{clearTimeout(i),n===0?e():t(Error(`secret-tool exited with code ${n}`))}),r.on(`error`,e=>{clearTimeout(i),t(IM(e,`secret-tool`)?LM(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=x.platform();if(n===`darwin`){await BM(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await BM(`secret-tool`,[`clear`,`service`,t,`account`,e]);RM(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function WM(e){let{privateKeyToAccount:t}=await import(`viem/accounts`),n=process.env.MPPX_PRIVATE_KEY?.trim();if(n)return{account:t(n),source:`environment`};let r=HM(e),i=await UM(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function GM(e){let t=HM(e);if(!process.env.MPPX_PRIVATE_KEY?.trim()&&gM(t))throw new B({code:`UNSUPPORTED_ACCOUNT`,message:`Persistent sessions require an mppx account or MPPX_PRIVATE_KEY.`,exitCode:2});return WM(e).catch(e=>{throw new B({code:`ACCOUNT_NOT_FOUND`,message:e instanceof Error?e.message:`No account found.`,exitCode:69,...e instanceof Error&&{cause:e}})})}async function KM(e){return(await WM(e)).account}var qM,JM,YM=z((()=>{PM(),qM=`mppx`,JM=1e4}));Zj(),YM();const XM=[[`ANTIGRAVITY_CLI_ALIAS`,`antigravity`],[`CLAUDECODE`,`claude_code`],[`CLINE_ACTIVE`,`cline`],[`CODEX_SANDBOX`,`codex_cli`],[`CODEX_THREAD_ID`,`codex_cli`],[`CODEX_SANDBOX_NETWORK_DISABLED`,`codex_cli`],[`CODEX_CI`,`codex_cli`],[`CURSOR_AGENT`,`cursor`],[`GEMINI_CLI`,`gemini_cli`],[`OPENCODE`,`open_code`],[`OPENCLAW_SHELL`,`openclaw`],[`CLAUDE_CODE_ENTRYPOINT`,`claude_code`],[`CODEX_INTERNAL_ORIGINATOR_OVERRIDE`,`codex_cli`]];function ZM(e=process.env){return XM.find(([t])=>e[t])?.[1]}function QM(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function $M(e,t){let{chainId:n,decimals:r}=t;if(typeof e==`string`)return{address:e,chainId:n,decimals:r};if(QM(e))return e.addresses[n]?e(n):void 0;if(e.chainId===n)return e}function eN(e,t,n={}){let{chainId:r,decimals:i}=n,a=e=>e.toLowerCase()===t.toLowerCase();for(let t of e){if(typeof t==`string`){if(a(t))return{currency:t,decimals:i};continue}if((r===void 0?QM(t)?Object.keys(t.addresses).map(e=>$M(t,{chainId:Number(e)})):[t]:[$M(t,{chainId:r})]).some(e=>e&&a(e.address)))return{currency:t,decimals:t.decimals}}}var tN=z((()=>{}));tN();const nN=Symbol(`mppx.x402.asset`);function rN(e){return{[nN]:!0,address:e.address,chainId:_N(e.network),decimals:e.decimals,network:e.network,transfer:e.transfer}}function iN(e,t){let n=e(t.chainId);return rN({address:n.address,decimals:n.decimals,network:gN(t.chainId),transfer:vN(t.transfer,n)})}const aN={USDC:rN({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},oN={USDC:rN({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},sN={USDC:rN({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:rN({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},cN={USDC:rN({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},lN=[aN,oN,sN,cN].flatMap(e=>Object.values(e));function uN(e,t){let n=e.toLowerCase();return lN.find(e=>e.network===t&&e.address.toLowerCase()===n)}function dN(e){return typeof e!=`object`||!e?!1:e[nN]===!0}const fN=QM;function pN(e){return typeof e==`string`}function mN(e,t){if(dN(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(typeof e==`string`)return{address:e};let n=$M(e,{chainId:_N(t)});if(n)return{address:n.address,decimals:n.decimals,name:n.name}}function hN(e,t,n){let r=mN(e,n);return r?I(r.address)===I(t):!1}function gN(e){return`eip155:${e}`}function _N(e){return Number(e.slice(7))}function vN(e,t){if(e.type!==`eip3009`)return e;if(e.name)return{...e,name:e.name};if(!t.name)throw Error(`EIP-3009 token assets require a token name.`);return{...e,name:t.name}}var yN=it({base:()=>aN,baseSepolia:()=>oN,celo:()=>sN,celoSepolia:()=>cN,define:()=>rN,fromToken:()=>iN,isAsset:()=>dN,isRawAddress:()=>pN,isToken:()=>fN,lookup:()=>uN,matches:()=>hN,resolve:()=>mN,toChainId:()=>_N,toNetwork:()=>gN}),bN=it({base:()=>xN,baseSepolia:()=>SN,celo:()=>CN,celoSepolia:()=>wN});const xN=8453,SN=84532,CN=42220,wN=11142220;lS();function TN(e){let t=[cS(e.accepted),cS(e.resource),cS(e.extensions)].join(`|`);return j.sha256(A.fromString(t),{as:`Hex`})}HT(),Uw();async function EN(e){let t=e.context?.account??e.config.account;if(!t?.signTypedData)throw Error(`x402 exact requires a typed-data signer.`);let n=e.challenge.request,r=yw(n);if(AN(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?MN(n.extensions):n.extensions,a=r.extra?.assetTransferMethod??`eip3009`;if(a!==`eip3009`)throw Error(`x402 exact ${String(a)} signing is not implemented yet.`);let o=r.extra?.name,s=r.extra?.version;if(typeof o!=`string`||typeof s!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let c=Math.floor(Date.now()/1e3),l={from:I(t.address),nonce:i?.mppx?TN({accepted:r,extensions:i,resource:n.resource}):PN(),to:I(r.payTo),validAfter:(c-600).toString(),validBefore:(c+r.maxTimeoutSeconds).toString(),value:r.amount},u=await t.signTypedData({domain:{chainId:kN(r.network),name:o,verifyingContract:I(r.asset),version:s},message:{...l,value:BigInt(l.value),validAfter:BigInt(l.validAfter),validBefore:BigInt(l.validBefore)},primaryType:`TransferWithAuthorization`,types:ON});return zT({accepted:r,...i?{extensions:i}:{},payload:{authorization:l,signature:u},...n.resource?{resource:n.resource}:{},x402Version:2})}function DN(e){let t=e.challenge.request,n;try{n=yw(t),AN(e.config,n)}catch{return!1}if(!t.resource||(n.extra?.assetTransferMethod??`eip3009`)!==`eip3009`)return!1;let r=n.extra?.name,i=n.extra?.version;return typeof r==`string`&&typeof i==`string`}const ON={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function kN(e){return Number(e.slice(Sw.length))}function AN(e,t){let n=kN(t.network);if(e.networks&&!e.networks.includes(n))throw Error(`x402 exact chain ID is not allowed: ${n}.`);let r=e.currencies??e.assets;if(r?.some(e=>pN(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=I(t.asset);if(!r.some(n=>hN(n,e,t.network)))throw Error(`x402 exact currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`x402 exact amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=jN(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>me(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function jN(e,t){let n=e.currencies??e.assets,r=I(t.asset),i=n?.find(e=>hN(e,r,t.network)),a=i?mN(i,t.network):void 0;return a?.decimals===void 0?e.decimals===void 0?uN(r,t.network)?.decimals:e.decimals:a.decimals}function MN(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:NN()}}}:e}function NN(){return FN().slice(2)}function PN(){return FN()}function FN(){let e=globalThis.crypto;if(!e?.getRandomValues)throw Error(`x402 exact requires crypto randomness.`);let t=e.getRandomValues(new Uint8Array(32));return`0x${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}xS();const IN=[`authorization`],LN=Y.string().check(Y.regex(/^\d+$/,`Invalid atomic amount`));Y.object({name:Y.string().check(Y.minLength(1)),version:Y.string().check(Y.minLength(1))});const RN=Y.object({chainId:Y.number(),credentialTypes:Y.optional(Y.array(Y.enum(IN)).check(Y.minLength(1))),decimals:Y.optional(Y.number()),permit2Address:Y.optional(gS()),splits:Y.optional(Y.array(Y.object({amount:LN,recipient:gS()})))});Y.object({amount:LN,currency:gS(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),methodDetails:RN,recipient:gS()});const zN=Y.object({amount:dS(),chainId:Y.number(),currency:gS(),credentialTypes:Y.optional(Y.array(Y.enum(IN)).check(Y.minLength(1))),decimals:Y.number(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),permit2Address:Y.optional(gS()),recipient:gS(),splits:Y.optional(Y.array(Y.object({amount:LN,recipient:gS()})))}),BN=Y.object({from:gS(),nonce:_S(),signature:yS(),to:gS(),type:Y.literal(`authorization`),validAfter:LN,validBefore:LN,value:LN}),VN={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function HN(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function UN(e){return j.keccak256(A.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function WN(e){return`eip155:${e}`}function GN(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}xk(),xS();const KN=yk({name:`evm`,intent:`charge`,schema:{credential:{payload:BN},request:Y.pipe(zN,Y.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:s,...c})=>({...c,amount:me(e,i).toString(),currency:I(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:I(a)}:{},...s?{splits:s}:{}},recipient:I(o)})))}});PE(),vC(),ZC(),xk(),xS();function qN(e){return TE(bk(KN,{canHandleChallenge({challenge:t}){return!JN(t)||DN({challenge:t,config:e})},context:Y.object({account:Y.optional(Y.custom())}),async createCredential({challenge:t,context:n}){if(JN(t))return EN({challenge:t,config:e,context:n});let r=n?.account??e.account;if(!r?.signTypedData)throw Error(`EVM authorization requires a typed-data signer.`);let i=t.request;YN(e,i);let a=ZN(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return pC(fC({challenge:t,payload:{from:I(r.address),nonce:UN(t),signature:await r.signTypedData({domain:HN({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:I(r.address),nonce:UN(t),to:I(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:VN}),to:I(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:GN({address:I(r.address),chainId:i.methodDetails.chainId})}))}}),{assert(t){JN(t)||YN(e,t.request)}})}function JN(e){return YC(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function YN(e,t){if(XN(e,t),!t.methodDetails.credentialTypes?.includes(`authorization`))throw Error(`EVM authorization is not accepted by this challenge.`);if(t.methodDetails.splits?.length)throw Error(`EVM authorization does not support payment splits.`)}function XN(e,t){let n=t.methodDetails.chainId,r=WN(n);if(e.networks&&!e.networks.includes(n))throw Error(`EVM chain ID is not allowed: ${n}.`);let i=e.currencies??e.assets;if(i?.some(e=>pN(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=I(t.currency);if(!i.some(t=>hN(t,e,r)))throw Error(`EVM currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`EVM charge amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=QN(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>me(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function ZN(e,t){let n=e.currencies??e.assets,r=I(t.currency),i=WN(t.methodDetails.chainId),a=n?.find(e=>hN(e,r,i)),o=a?mN(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;let s=uN(r,i)?.transfer;if(s?.type===`eip3009`)return{name:s.name,version:s.version};throw Error(`EVM authorization requires token name and version.`)}function QN(e,t){let n=e.currencies??e.assets,r=I(t.currency),i=WN(t.methodDetails.chainId),a=n?.find(e=>hN(e,r,i)),o=a?mN(a,i):void 0;return o?.decimals===void 0?e.decimals===void 0?uN(r,i)?.decimals:e.decimals:o.decimals}function $N(e){return[$N.charge(e)]}(function(e){e.charge=qN,e.assets=yN,e.chains=bN})($N||={});function eP(e){return e}var tP=z((()=>{}));ZC(),tP();function nP(){return eP({method:`evm`,supports:e=>e.method===`evm`&&!YC(e),async setup({challenge:e,options:t}){let n=e.request,r=n.methodDetails,i=r?.chainId,a=i?rP(i):void 0,o=n.currency,s=await KM(t.account),c=[...Object.values(aN),...Object.values(oN),...Object.values(sN),...Object.values(cN)],l=o??``;if(a&&o)try{let e=N({chain:a,transport:L()}),t=await je(e,{address:o,abi:F,functionName:`symbol`});t&&(l=t)}catch{}return{tokenSymbol:l,tokenDecimals:r?.decimals??6,explorerUrl:a?.blockExplorers?.default?.url,methods:[...$N({account:s,currencies:c})]}}})}function rP(e){return Object.values(Qe).find(t=>t.id===e)}function iP(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`Decimals must be a non-negative integer.`);if(!/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))throw TypeError(`Value \`${e}\` is not a valid decimal number.`);let n=e.startsWith(`-`),[r=`0`,i=``]=(n?e.slice(1):e).split(`.`),a=i.slice(0,t).padEnd(t,`0`),o=BigInt(`${r||`0`}${a}`);return i.length>t&&i[t]>=`5`&&(o+=1n),n?-o:o}xS();const aP=Y.object({customer:Y.optional(Y.string().check(Y.minLength(1))),hooks:Y.optional(Y.object({inputs:Y.object({tax:Y.object({calculation:Y.string().check(Y.minLength(1))})})})),metadata:Y.optional(Y.record(Y.string(),Y.string())),receipt_email:Y.optional(Y.string().check(Y.minLength(1)))}),oP=Y.custom(e=>typeof e==`function`),sP=Y.union([aP,oP]);xk(),xS();const cP=yk({name:`stripe`,intent:`charge`,schema:{credential:{payload:Y.object({externalId:Y.optional(Y.string()),spt:Y.string()})},request:Y.pipe(Y.object({amount:dS(),currency:Y.string(),decimals:Y.number(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),metadata:Y.optional(Y.record(Y.string(),Y.string())),networkId:Y.string(),paymentIntentOptions:Y.optional(sP),paymentMethodTypes:Y.array(Y.string()).check(Y.minLength(1)),recipient:Y.optional(Y.string())}),Y.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:iP(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});vC(),xk(),xS();function lP(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return bk(cP,{context:Y.object({paymentMethod:Y.optional(Y.string())}),async createCredential({challenge:e,context:a}){let o=a?.paymentMethod??i;if(!o)throw Error(`paymentMethod is required (pass via context or parameters)`);let s=e.request.amount,c=e.request.currency,l=typeof e.request.externalId==`string`?e.request.externalId:void 0,u=e.request.methodDetails?.networkId;if(!u)throw Error(`networkId is required in challenge.methodDetails`);let d=e.request.methodDetails?.metadata;if(d?.externalId)throw Error(`methodDetails.metadata.externalId is reserved; use credential externalId instead`);let f=e.expires?Math.floor(new Date(e.expires).getTime()/1e3):Math.floor(Date.now()/1e3)+3600,p=await n({amount:s,challenge:e,client:t,currency:c,expiresAt:f,metadata:d,networkId:u,paymentMethod:o}),m=l??r;return pC({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function uP(e){return[lP(e)]}(function(e){e.charge=lP})(uP||={}),Rx(),PM(),tP();function dP(){return eP({method:`stripe`,supports(e){return e.method===`stripe`&&e.intent===`charge`},async setup({challenge:e,methodOpts:t}){let n=e.request,r=n.currency,i=pP(p.object({paymentMethod:p.string(),secretKey:p.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new B({code:`MISSING_ENV`,message:`MPPX_STRIPE_SECRET_KEY environment variable is required for Stripe payments.`,exitCode:2});return{tokenSymbol:r?.toUpperCase()??``,tokenDecimals:n.decimals??2,methods:[uP.charge({paymentMethod:i.paymentMethod,createToken:async({paymentMethod:e,amount:t,currency:n,networkId:r,expiresAt:i,metadata:o})=>{let s=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()}),c=fP(a),l=process.env.MPPX_STRIPE_SPT_URL?process.env.MPPX_STRIPE_SPT_URL:c?`https://api.stripe.com/v1/test_helpers/shared_payment/granted_tokens`:`https://api.stripe.com/v1/shared_payment/issued_tokens`;if(r){let e=c?`seller_details[network_id]`:`seller_details[network_business_profile]`;s.set(e,r)}if(o)for(let[e,t]of Object.entries(o))s.set(`metadata[${e}]`,t);let u={Authorization:`Basic ${btoa(`${a}:`)}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":fk},d=await globalThis.fetch(l,{method:`POST`,headers:u,body:s});if(!d.ok){let a=await d.json();if(c&&(o||r)&&a.error.message.includes(`Received unknown parameter`)){let r=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()});if(d=await globalThis.fetch(l,{method:`POST`,headers:u,body:r}),!d.ok){let e=await d.json();throw new B({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${e.error.message}`,exitCode:77})}}else throw new B({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${a.error.message}`,exitCode:77})}let{id:f}=await d.json();return f}})]}},formatReceiptField(e,t){if(e===`reference`&&typeof t==`string`&&t.startsWith(`pi_`)){let e=process.env.MPPX_STRIPE_SECRET_KEY,n=`https://dashboard.stripe.com${e!==void 0&&fP(e)?`/test`:``}/payments/${t}`;return X.link(n,t,!0)}}})}function fP(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function pP(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function mP(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 _e(r)}}var hP=z((()=>{}));function gP(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}var _P=z((()=>{}));function vP(e,t={}){return L(e.url,{fetchFn:e.fetch,fetchOptions:{headers:gP(e)},...t})}function yP(e){let{chain:t,getClient:n,remoteFeePayer:r,rpcUrl:i}=e;return n?!t?.serializers&&!r&&!e.requireChain?n:async i=>{let a=await n(i);if(e.requireChain&&(a.chain?.id===void 0||a.chain.id!==i.chainId))throw Error(`Subscription chain mismatch: expected ${i.chainId}, got ${a.chain?.id??`unknown`}.`);let o=a;if(r&&a.transport.key!==`feePayer`){let e=a.request.bind(a),t=We(re({request:t=>e(t)},{retryCount:0}),vP(r,{retryCount:a.transport.retryCount}))({account:a.account,chain:a.chain,pollingInterval:a.pollingInterval,retryCount:0}),n=P({...t.config,retryCount:0},t.value);o=Object.assign({},a,{request:n.request,transport:{...n.config,...n.value}})}return!t?.serializers||o.chain?.serializers?.transaction?o:Object.assign({},o,{chain:{...t,...i.chainId===void 0?{}:{id:i.chainId},...o.chain,formatters:o.chain?.formatters??t.formatters,prepareTransactionRequest:o.chain?.prepareTransactionRequest??t.prepareTransactionRequest,serializers:o.chain?.serializers?.transaction?o.chain.serializers:t.serializers}})}:({chainId:e})=>{if(!i)throw Error("No `rpcUrl` provided.");let n=e||Number(Object.keys(i)[0]),a=i[n];if(!a)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let o=r?We(L(a),vP(r)):L(a);return N({chain:SP[n]??{...t,id:n},transport:o})}}function bP(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 xP(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}var SP,CP=z((()=>{_P(),SP={[ve.id]:ve,[ye.id]:ye}}));function wP(e){let t=j.keccak256(A.fromString(e),{as:`Hex`});return M.toBytes(M.slice(t,0,10))}function TP(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(M.toBytes(DP),0),i[4]=OP,i.set(wP(t),5),n&&i.set(wP(n),15),i.set(EP(r),25),M.fromBytes(i)}function EP(e){let t=j.keccak256(A.fromString(e),{as:`Hex`});return M.toBytes(M.slice(t,0,7))}var DP,OP,kP=z((()=>{DP=M.slice(j.keccak256(A.fromString(`mpp`),{as:`Hex`}),0,4),OP=1}));async function AP(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:$M(e,{chainId:s})?.address;!t||Sk(t,i)||c.some(e=>Sk(e,t))||c.push(t)}let l=await Promise.allSettled([je(e,{...Be.token.getBalance.call(e,{account:n,token:i}),account:null}),...c.map(t=>je(e,{...Be.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/MP;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 Be.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:f});if(t<=0n||t>m)continue;let n=t+t*p/MP,o=n<m?n:m;if(r>=o)return[Be.token.approve.call(e,{amount:o,spender:Ve.stablecoinDex,token:a}),Be.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:f,maxAmountIn:o})]}catch{}}throw new PP({currency:i})}function jP(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`&&Sk(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var MP,NP,PP,FP=z((()=>{tN(),Ck(),aM(),MP=10000n,NP=[eM.pathUsd,eM.usdc,eM.ousd],PP=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}}}));function IP(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}))]}var LP=z((()=>{}));function RP(e,t,n){t&&(n&&!n.some(e=>Sk(e,t))||e.some(e=>Sk(e,t))||e.push(t))}async function zP(e,t,n){try{return(await Be.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function BP(e){let t=e.chain?.feeToken;if(t)return He.toAddress(t);let n=e.chain?.id;return n?tM[n]:void 0}function VP(e){let t=[];return RP(t,eM.pathUsd),RP(t,tM[e]),t}async function HP(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])RP(o,e,n);if(RP(o,await Be.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),RP(o,BP(i),n),!a)for(let e of r??[])RP(o,e,n);for(let e of o)if(await zP(i,t,e))return e;return o[0]}var UP=z((()=>{Ck(),aM()}));function WP(e){if(e!==void 0)return nM[e]}function GP(e){let t=WP(e.chainId);return!!t&&le(e.currency,{strict:!1})&&ue(e.currency,t.token)}function KP(e){let t=WP(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let r=BigInt(n.amount),i=n.memo;return{calls:[{data:ae({abi:Re.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:ae({abi:QP,functionName:`swapTo`,args:[t.token,r,e.currency,n.recipient,i]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:r,memo:i,recipient:n.recipient}]}}async function qP(e,t){let n=KP(t);if(n)try{return await je(e,Be.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await De(e,{account:t.account,calls:n.calls}),n)}catch{return}}function JP(e={}){let{address:t,amount:n,chainId:r=$j.mainnet}=e;if(r!==$j.mainnet)return;let i=new URL(rM);if(t&&le(t,{strict:!1})&&i.searchParams.set(`address`,I(t)),n!==void 0&&n>0n){let e=(n+$P-1n)/$P,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 YP(e,t){let n=WP(t.chainId);if(!n)return;let r=await je(e,Be.token.getBalance.call(e,{account:t.account,token:n.token})).catch(()=>void 0);return typeof r==`bigint`?r:void 0}async function XP(e,t){let{account:n,amount:r,chainId:i}=t,a=await YP(e,{account:n,chainId:i});if(a===void 0||a>=r)return;let o=e=>`${oe(e,6)} MACH`,s=r-a;return{fundingUrl:JP({address:n,amount:s,chainId:i}),reason:`requested ${o(r)}, available ${o(a)}`,shortfall:s}}async function ZP(e,t){let n=await XP(e,t);if(n)return new iS({fundingUrl:n.fundingUrl,reason:n.reason})}var QP,$P,eF=z((()=>{aS(),aM(),QP=fe([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]),$P=10n**BigInt(4)}));function tF(e){return{name:`MPP`,version:`3`,chainId:e}}function nF(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function rF(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:tF(n),types:oF,primaryType:aF,message:nF({account:t,challengeId:r,realm:i})}}function iF(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}var aF,oF,sF=z((()=>{aF=`Proof`,oF={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]}}));function cF(e){let t=new Set,n=e;for(;typeof n==`object`&&n&&!t.has(n);){t.add(n);let e=n.data;if(dF(e))return e;let r=e?.data;if(dF(r))return r;n=n.cause}}function lF(e,t){let n=cF(e);if(!n)return;let r=(()=>{try{return ie({abi:fF,data:n})}catch{return}})();if(r?.errorName===`SpendingLimitExceeded`){let n=t.account.accessKeyAddress;return new tS({accessKey:typeof n==`string`?n:void 0,account:t.account.address,cause:e})}if(r?.errorName===`InsufficientBalance`){let[n,i,a]=r.args;return new iS({cause:e,reason:`${t.account.address} holds ${n} of token ${a}, but the payment requires ${i}`})}}async function uF(e,t){try{return await t()}catch(t){throw lF(t,e)??t}}function dF(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{8}/.test(e)}var fF,pF=z((()=>{aS(),fF=[...Re.accountKeychain.filter(e=>e.type===`error`),...Re.tip20.filter(e=>e.type===`error`)]}));function mF(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??[])jF(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=yP({chain:ve,getClient:e.getClient,rpcUrl:iM}),i=mP({account:e.account});CF(e.zone);let a=new Map,o=bk(Zk,{canHandleChallenge({challenge:t}){try{MF(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:NF,async createCredential(o){let{challenge:s,context:c}=o,l=OE(o),u=()=>Error(`The Zone withdrawal this challenge resumes is no longer outstanding. Retry the request to pay it.`);MF(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});bP(p,f);let m=f??p.chain?.id;if(xP(e.allowedChainIds,m),m===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");d===void 0&&MF(e,n,s.request,m);let{request:h}=s,{amount:g,methodDetails:_}=h,v=_?.supportedModes??[`pull`,`push`],y=e.zone?.client.chain,b=e.zone?e.zone.zoneId??Dk(y?.id??0):void 0,x=y?.sourceId??(y?Ok(y.id):void 0),S=c?.mode??e.mode;if(BigInt(g)>0n&&e.zone&&b!==void 0&&x===m&&v.includes(`push`)&&(S===void 0||S===`push`)&&Tk(_?.zones,b)&&!_?.splits){let r={assertFee:t=>MF(e,n,h,m,t),challenge:s,clientId:t,client:p,origin:SF(cE(o)),pending:a,zone:e.zone,zoneId:b},i=vF(r);if(i)return bF(r,i);if(l?.resume)throw u();if(s.expires&&yC(s.expires,s.id),wF(s.expires,e.zone.settlementTimeoutMs))return _F(r)}if(l?.resume)throw u();let C=i(p,c),w=async t=>await e.resolveAccount?.({account:C,chainId:m,operation:t})??C;if(BigInt(g)===0n){let e=await w({kind:`signPaymentProof`});return pC({challenge:s,payload:{signature:await Ie(p,{account:e,...rF({account:e.address,chainId:m,challengeId:s.id,realm:s.realm})}),type:`proof`},source:iF({address:e.address,chainId:m})})}let T=h.currency,E=GP({chainId:m,currency:T}),ee=_?.memo??TP({challengeId:s.id,clientId:t,serverId:s.realm}),D=IP({amount:g,methodDetails:{..._,memo:ee},recipient:h.recipient}),O=D.map(e=>Be.token.transfer.call(p,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:T})),k=jP(c?.autoSwap??e.autoSwap,NP),te=_?.machineTokenEnabled===!0&&!l?KP({chainId:m,currency:T,transfers:D}):void 0,A=C,j,M=!1;if(te){let e=await(async()=>{try{return await w({calls:te.calls,kind:`executeCalls`})}catch{return}})();e&&(j=await qP(p,{account:e.address,chainId:m,currency:T,transfers:D}),j?A=e:M=!0)}let ne;if(!j){if(A=await w({kind:`executeCalls`,...k?{}:{calls:O}}),ne=k?await AP(p,{account:A.address,amountOut:BigInt(g),tokenOut:T,tokenIn:k.tokenIn,slippage:k.slippage,maxAmountIn:k.maxAmountIn}):void 0,l&&ne)throw new rS({limit:l.limit,reason:`asset`});if(M&&!k){let e=await hF(p,{account:A.address,amount:BigInt(g),chainId:m,currency:T});if(e)throw e}}let N=j?.calls??[...ne??[],...O],P=VP(m),re=(c?.feeToken??e.feeToken)||(j||E?await HP({account:A.address,allowedTokens:P,candidateTokens:P,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=A.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)})(),F=()=>{l&&s.expires&&yC(s.expires,s.id)};if(ie===`push`){F();let{receipts:e}=A.type===`local`?{receipts:[await uF({account:A},()=>Pe(p,{account:A,calls:N,...re?{feeToken:re}:{},nonceKey:`expiring`,validBefore:ae}))]}:await Me(p,{account:A,...re?{capabilities:{feeToken:re}}:{},calls:N,experimental_fallback:N.length===1,forceAtomic:N.length>1}),t=e?.[0]?.transactionHash;if(!t)throw xE(Error(`No transaction receipt returned.`));return pC({challenge:s,payload:{hash:t,type:`hash`},source:iF({address:A.address,chainId:m})})}let oe=()=>{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.`)};oe();let se=await uF({account:A},()=>Ae(p,{account:A,calls:N,...re?{feeToken:re}:{},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 oe(),F(),pC({challenge:s,payload:{signature:await Fe(p,se),type:`transaction`},source:iF({address:A.address,chainId:m})})}}),s=new Map,c=async t=>{MF(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,a=OE(t),c=s.get(i);if(a&&kE(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 TE(aE({...o,createCredential:c},gF),{assert:t=>MF(e,n,t.request),resumes:t=>yF(a,t,e.zone&&(e.zone.zoneId??Dk(e.zone.client.chain?.id??0)))})}async function hF(e,t){let{account:n,amount:r,chainId:i,currency:a}=t,o=await je(e,Be.token.getBalance.call(e,{account:n,token:a})).catch(()=>void 0);if(!(typeof o!=`bigint`||o>=r))return ZP(e,{account:n,amount:r,chainId:i})}function gF(e){let t=Zk.schema.credential.payload.safeParse(cC(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(Xe.serializedType))return;let i=Xe.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&Xe.serialize(i)===r)return de(r)}function _F(e){let{challenge:t,origin:n,pending:r,zoneId:i}=e,a={sent:!1},o={challenge:t,origin:n,terms:DF(t,i),waiters:0,withdrawal:AF(e,a)},s=EF(t);return r.set(s,o),o.withdrawal.catch(()=>{!a.sent&&r.get(s)===o&&r.delete(s)}),bF(e,o)}function vF(e){let{challenge:t,pending:n,zoneId:r}=e,i=n.get(EF(t));if(i)return i;let a=DF(t,r);if(a!==void 0){for(let[e,t]of n)if(t.terms===a){if(!kF(t.challenge.expires)){n.delete(e);continue}if(t.redeemedLate)throw new nS({challengeId:t.challenge.id,senderTags:t.senderTags,zoneId:r});if(!(t.waiters>0))return t}}}function yF(e,t,n){if(n===void 0||e.size===0)return!1;if(e.has(EF(t)))return!0;let r=DF(t,n);if(r===void 0)return!1;for(let t of e.values())if(t.terms===r&&kF(t.challenge.expires)&&(t.redeemedLate||t.waiters===0))return!0;return!1}async function bF(e,t){t.waiters++;try{return await xF(e,t)}finally{t.waiters--}}async function xF(e,t){let{client:n,origin:r,pending:i,zone:a,zoneId:o}=e,{challenge:s}=t,c=s.request.recipient,l=EF(s);if((l===EF(e.challenge)?r!==void 0&&t.origin!==void 0&&r!==t.origin:!r||r!==t.origin)||!kF(s.expires))throw new nS({challengeId:s.id,zoneId:o});let u=await t.withdrawal,d=u.senderTags??await Ak(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}),xE(t)}),f;try{f=await jk(n,{portal:Ek(o),senderTags:d,timeoutMs:TF(s.expires,a.settlementTimeoutMs),to:c})}catch(e){throw new nS({cause:e,challengeId:s.id,senderTags:d,zoneId:o})}i.get(l)===t&&(OF(s.expires)?(t.redeemedLate=!0,t.senderTags=[f.senderTag]):i.delete(l));let{hash:p,senderTag:m}=f;return pC({challenge:s,payload:{hash:p,senderTag:m,type:`zone`,zoneId:o}})}function SF(e){if(e)try{let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`?void 0:t.origin}catch{return}}function CF(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||Ok(n)===void 0)return;let r=Dk(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function wF(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+PF}function TF(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function EF(e){return JSON.stringify(e)}function DF(e,t){let n;try{n=e.opaque===void 0?e.meta:oS(e.opaque)}catch{return}let{digest:r,intent:i,method:a,realm:o,request:s}=e;return cS({digest:r,intent:i,meta:pk(n),method:a,realm:o,request:s,zoneId:t})}function OF(e){if(!e)return!1;let t=new Date(e).getTime();return!Number.isNaN(t)&&Date.now()>=t}function kF(e){if(!e)return!0;let t=new Date(e).getTime();return Number.isNaN(t)||Date.now()<t+3e5}async function AF(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=TP({challengeId:r.id,clientId:i,serverId:r.realm}),f=await Be.zone.getWithdrawalFee(a.client);n(f);let[,p]=Be.zone.requestWithdrawal.calls({amount:c,fallbackRecipient:s.address,memo:d,to:u,token:l}),m=await Ae(a.client,{account:s,calls:[Be.token.approve.call({amount:c+f,spender:Ve.zoneOutbox,token:l}),p]}),h=await Fe(a.client,m);t.sent=!0;let g=de(h),_=await Ne(a.client,{serializedTransaction:h}).catch(e=>Le(a.client,{hash:g,timeout:FF}).catch(()=>{let t=new Zx({cause:e,transactionHash:g});throw t.message=`Zone withdrawal outcome is unknown: transaction ${g} may have been sent. Retrying this challenge does not withdraw again.`,t}));if(_.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${_.transactionHash} reverted.`);let[v]=pe({abi:Re.zoneOutbox,eventName:`WithdrawalRequested`,logs:_.logs});return{blockNumber:_.blockNumber,sender:s.address,senderTags:v?[kk({fallbackNonce:v.args.fallbackNonce,sender:v.args.sender,transactionHash:_.transactionHash})]:void 0,transactionHash:_.transactionHash}}function jF(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 me(e,t)}}function MF(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)&&xP(e.allowedChainIds,s);let c=e.currencies?eN(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>jF(t.maxAmount,c?.decimals))throw Error(`Tempo charge ${u} maxAmount.`)}var NF,PF,FF,IF=z((()=>{wE(),pE(),PE(),vC(),tN(),aS(),bC(),vk(),xk(),lS(),hP(),CP(),xS(),kP(),FP(),LP(),aM(),UP(),eF(),sF(),pF(),Rk(),eA(),NF=Y.object({account:Y.optional(Y.custom()),autoSwap:Y.optional(Y.custom()),feeToken:Y.optional(Y.custom()),mode:Y.optional(Y.enum(Vk))}),PF=15e3,FF=15e3}));function LF(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function RF(e){let t=k.encode(k.from([`address payer`,`address payee`,`address operator`,`address token`,`bytes32 salt`,`address authorizedSigner`,`bytes32 expiringNonceHash`,`address escrow`,`uint256 chainId`]),[e.payer,e.payee,e.operator,e.token,e.salt,e.authorizedSigner,e.expiringNonceHash,e.escrow??`0x4d50500000000000000000000000000000000000`,BigInt(e.chainId)]);return j.keccak256(t)}function zF(e){return Xe.encodeForSigning(e)}function BF(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function VF(e,t){return j.keccak256(M.concat(zF(e),t.sender))}var HF=z((()=>{CA()})),UF,WF,GF,KF,qF=z((()=>{UF=[{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`}],WF=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],GF={name:`descriptor`,type:`tuple`,components:UF},KF=[{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:[GF,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[GF,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[GF,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[GF],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[GF],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[GF],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:UF},{name:`state`,type:`tuple`,components:WF}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:WF}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:WF}]},{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:[GF,{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 JF(e){return e.type===`secp256k1`?e.signature.s<=QF:e.type===`p256`||e.type===`webAuthn`?e.signature.s<=$F:!0}function YF(e){if(e.type===`configurable`)return{...e,signatures:e.signatures.map(e=>YF(e))};if(JF(e))return e;if(e.type===`secp256k1`){let{r:t,s:n,yParity:r}=e.signature;return{...e,signature:{r:t,s:XF-n,yParity:+(r===0)}}}return e.type===`p256`||e.type===`webAuthn`?{...e,signature:{...e.signature,s:ZF-e.signature.s}}:e}var XF,ZF,QF,$F,eI=z((()=>{XF=115792089237316195423570985008687907852837564279074904382605163141518161494337n,ZF=115792089210356248762697446949407573529996955224135760342422259061068512044369n,QF=57896044618658097711785492504343953926418782139537452191302581570759080747168n,$F=57896044605178124381348723474703786764998477612067880171211129530534256022184n}));function tI(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function nI(e){return e===void 0||BigInt(e)===0n}function rI(e,t){let{account:n,config:r,signatures:i}=e,a=Ge.getSignPayload({account:n,config:r,payload:t}),o=Number(r.threshold),s,c=0,l;for(let[e,t]of i.entries()){if(!tI(t.type)||!JF(t)||e>0&&c>=o)return!1;let n=Je.extractAddress({payload:a,signature:t});if(!Je.verify(t,{address:n,payload:a}))return!1;let i=r.owners.find(e=>Sk(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 iI(e,t){let{account:n,commitment:r,payload:i}=t;if(!Sk(e.account,n)||BigInt(e.config.version??0n)===0n&&e.config.owners.some(({owner:t})=>Sk(t,e.account)))return!1;if(nI(r)){if(BigInt(e.config.version??0n)!==0n||!Sk(Ge.getAddress(e.config),n))return!1}else if(Ge.getCommitment(e.config).toLowerCase()!==r.toLowerCase())return!1;return rI(e,i)}var aI=z((()=>{Ck(),eI()}));function oI(e,t){return{name:yI,version:bI,chainId:t,verifyingContract:e}}function sI(e,t,n){return ce({domain:oI(e,t),types:SI,primaryType:`CloseAuthorization`,message:n})}function cI(e,t){return Ke.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function lI(e,t,n){return e.toLowerCase()===Ke.address.toLowerCase()?cI(t,n):ce({domain:oI(e,t),types:xI,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function uI(e,t,n,r){let i=dI(e);return i?fI(i,t,n,r):!1}function dI(e){let t=Je.from(e);if(Je.serialize(t).toLowerCase()===e.toLowerCase())return t}function fI(e,t,n,r){if(e.type===`configurable`)return r.configurable?iI(e,{account:n,commitment:r.openingCommitment,payload:t}):!1;if(!tI(e.type)||!JF(e)||!nI(r.openingCommitment))return!1;let i=Je.extractAddress({payload:t,signature:e});return Je.verify(e,{address:i,payload:t})&&Sk(i,n)}function pI(e){return e.source===`configurable`}function mI(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function hI(e,t){return ze.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function gI(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===Ke.address.toLowerCase())try{return await hI(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return Ie(e,{account:t,domain:oI(r,i),types:xI,primaryType:`Voucher`,message:n})})(),o=Je.from(a);if(!tI(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 Je.serialize(YF(o))}async function _I(e,t,n,r,i){let a=mI(t)?await t.sign({hash:sI(r,i,n),raw:!0}):await Ie(e,{account:t,domain:oI(r,i),types:SI,primaryType:`CloseAuthorization`,message:n}),o=Je.from(a);if(!tI(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 Je.serialize(YF(o))}function vI(e,t,n,r,i={}){try{let a=lI(e,t,n);return uI(n.signature,a,r,i)}catch{return!1}}var yI,bI,xI,SI,CI=z((()=>{Ck(),aI(),eI(),yI=`TIP20 Channel Reserve`,bI=`1`,xI={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},SI={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]}}));function wI(e){return typeof e==`object`&&!!e}function TI(e){return typeof e==`string`&&le(e,{strict:!1})?e:void 0}function EI(e){return TI(e.accessKeyAddress)}function DI(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(M.random(8))%e)}function OI(e){return EI(e)??e.address}function kI(e){return AI(e)!==void 0}function AI(e){let t=EI(e);if(t===void 0)return pI(e)?e:void 0;let n=e.delegate;if(n&&pI(n)&&n.address.toLowerCase()===t.toLowerCase())return n}async function jI(e,t){let n=AI(t);if(!n)return M.random(32);let{config:r}=n,i=await Be.accounts.getConfigCommitment(e,{account:n.address}),a=r?Ge.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 MI(e,t){let n=cF(e);if(n)try{let r=ie({abi:KF,data:n});if(r.errorName!==`SignerConfigChanged`&&r.errorName!==`RootKeyRetired`)return;let[i]=r.args;return i.toLowerCase()===t.signer.toLowerCase()?new eS({cause:e,channelId:t.channelId,reason:r.errorName,signer:i}):void 0}catch{return}}async function NI(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return uF({account:n},()=>Ae(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}}))}async function PI(e,t){return await Fe(e,t)}function FI(e,t,n=!1){let r=e.request.methodDetails,i=wI(r)?TI(r.escrowContract)??TI(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!LI(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!LI(i,a)?i:a}function II(e,t,n,r){return pC({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${t.descriptor?.payer??r.address}`})}function LI(e,t){return e.toLowerCase()===t.toLowerCase()}function RI(e,t){let n=AI(e);if(!n?.config)return;let{config:r}=n;if(Ge.getCommitment(r).toLowerCase()!==t.salt.toLowerCase()&&(BigInt(r.version??0n)!==0n||Ge.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 zI(e,t,n,r,i,a=SA){let o=RF({...n,chainId:i,escrow:a}),s=rA(r);RI(t,n);let c=await gI(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function BI(e,t,n,r,i,a=SA){let o=await zI(e,t,n,r,i,a),s=await _I(e,t,{channelId:o.channelId,cumulativeAmount:rA(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function VI(e,t,n){let r=OI(t),i=n.escrow??`0x4d50500000000000000000000000000000000000`,a=n.operator??`0x0000000000000000000000000000000000000000`,o=n.salt??await jI(e,t),s=rA(n.deposit),c=rA(n.initialAmount),l=ae({abi:KF,functionName:`open`,args:[n.payee,a,n.token,s,o,r]}),u=await PI(e,await NI(e,{account:t,calls:[...n.prefixCalls??[],{to:i,data:l}],feePayer:n.feePayer,feeToken:n.feeToken??n.token,validAfter:DI()})),d=Ue.deserialize(u),f={authorizedSigner:r,expiringNonceHash:VF(BF({...n.feePayer?{feePayer:!0}:{},transaction:d}),{sender:t.address}),operator:a,payee:n.payee,payer:t.address,salt:o,token:n.token},p=RF({...f,chainId:n.chainId,escrow:i});return{action:`open`,type:`transaction`,channelId:p,transaction:u,signature:await gI(e,t,{channelId:p,cumulativeAmount:c},i,n.chainId),descriptor:f,cumulativeAmount:c.toString(),authorizedSigner:f.authorizedSigner}}async function HI(e,t,n,r,i,a,o=SA,s=[],c=n.token){let l=RF({...n,chainId:i,escrow:o}),u=rA(r);return{action:`topUp`,type:`transaction`,channelId:l,transaction:await PI(e,await NI(e,{account:t,calls:[...s,{to:o,data:ae({abi:KF,functionName:`topUp`,args:[n,u]})}],feePayer:a,feeToken:c,validAfter:DI()}).catch(e=>{throw MI(e,{channelId:l,signer:LF(n)})??e})),descriptor:n,additionalDeposit:u.toString()}}var UI=z((()=>{vC(),aS(),pF(),HF(),qF(),CA(),CI()}));function WI(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function GI(e){return WI({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function KI(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(GI(t),t)},delete(t){e.delete(t)}}}function qI(e){return{...e,cumulativeAmount:e.cumulativeAmount.toString(),deposit:e.deposit.toString()}}function JI(e){return{...e,cumulativeAmount:BigInt(e.cumulativeAmount),deposit:BigInt(e.deposit)}}function YI(e,t){tL.set(e,tL.get(t)??t)}async function XI(e,t,n){let r=eL.get(e);r||(r=new Map,eL.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 ZI(e,t,n){return XI(tL.get(e)??e,`funding:${t}`,n)}async function QI(e,t){await XI(e,`write:${GI(t)}`,async()=>{let n=await e.get(GI(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 $I(e,t){await XI(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}var eL,tL,nL=z((()=>{eL=new WeakMap,tL=new WeakMap}));function rL(e){if(e<0n||e>cL)throw new J({reason:`amount exceeds uint96 range`})}async function iL(e,t,n=SA){let{cumulativeAmount:r,descriptor:i,signature:a}=t;return je(e,{address:n,abi:KF,functionName:`verifyVoucher`,args:[sL(i),r,a]})}async function aL(e,t,n=SA,r){return oL(await je(e,{address:n,abi:KF,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function oL(e){return rL(e.settled),rL(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}function sL(e){return{payer:e.payer,payee:e.payee,operator:e.operator,token:e.token,salt:e.salt,authorizedSigner:e.authorizedSigner,expiringNonceHash:e.expiringNonceHash}}var cL,lL=z((()=>{aS(),qF(),CA(),cL=2n**96n-1n}));function uL(e){return`cumulativeAmount`in e}function dL(e){if(uL(e))return BigInt(e.cumulativeAmount)}async function fL(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await QI(e.store,t):await $I(e.store,GI(t)),e.notifyUpdate(t)}async function pL(e,t,n){let r=dL(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 fL(e,i))}function mL(e){return e?.action!==void 0}function hL(e){return mL(e)&&e.descriptor!==void 0}function gL(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 me(i,t)}function _L(e,t,n,r){let i=gL(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function vL(e){return typeof e==`object`&&!!e}function yL(e){return typeof e==`string`&&le(e,{strict:!1})?e:void 0}function bL(e){let t=e.request.methodDetails;return vL(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:yL(t.escrowContract),escrow:yL(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:yL(t.feeToken),operator:yL(t.operator),configurableVouchers:typeof t.configurableVouchers==`boolean`?t.configurableVouchers:void 0,sessionSnapshot:zx(t,Ux.sessionSnapshot)}:{}}function xL(e,t){if(typeof e==`string`&&le(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function SL(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function CL(e){return typeof e==`string`?e:void 0}async function wL(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=bL(n);(o.chainId!==void 0||i?.length===0)&&xP(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});bP(c,s);let l=s??c.chain?.id;if(xP(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=FI(n,r,t),d=xL(n.request.recipient,`recipient`),f=xL(n.request.currency,`currency`);return{amount:SL(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:WI({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:CL(n.request.suggestedDeposit),token:f}}async function TL(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=aL}=e,o=RF({...r,chainId:i.chainId,escrow:i.escrow});EL({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 EL(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(!LI(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!LI(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!LI(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!LI(LF(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function DL(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function OL(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=gL(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function kL(e){let{account:t,client:n,readChannelState:r,snapshot:i,verifyVoucherOnChain:a=iL}=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=LF(i.descriptor),h=kI(t);if(!(vI(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 TL({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:OI(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 AL(e,t){return LI(e.address,t.payer)?LI(OI(e),LF(t)):!1}function jL(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(mL(r)){if(!hL(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=DL({context:r,snapshot:o.snapshot});return!n&&s&&AL(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&AL(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 ML(e,t,n=!1){switch(e.type){case`open`:return FL(e,t,n);case`recover`:return IL(e,t);case`voucher`:return LL(e,t);case`manual`:return RL(e,t,n)}}async function NL(e,t){if(e)return await AP(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function PL(e,t){let{account:n,amount:r,chainId:i,client:a,token:o}=t;if(e||!GP({chainId:i,currency:o}))return;let s=await ZP(a,{account:n,amount:r,chainId:i});if(s)throw s}async function FL(e,t,n){let{account:r,resolved:i}=e;if(kI(r)&&i.configurableVouchers!==!0)throw new $x({signer:r.address});let a=WA({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw});await PL(n,{account:r.address,amount:a,chainId:i.chainId,client:i.client,token:i.token});let o=await VI(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 NL(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await fL(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function IL(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await TL({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:OI(n),token:o.token}}),l=OL({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`);KA(l,a);let u=await zI(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await fL(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 LL(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;KA(a,e.maxDeposit);let o=await zI(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await fL(t,r),o}async function RL(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=RF({...s,chainId:o.chainId,escrow:o.escrow});EL({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:OI(r),token:o.token});let l=await zL({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await pL(t,o.key,l),l}async function zL(e,t){switch(e.context.action){case`open`:return BL(e);case`topUp`:return VL(e,t);case`voucher`:return HL(e);case`close`:return UL(e)}}async function BL(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=_L(r,i,`cumulativeAmount`,`open`),c=await zI(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 VL(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=_L(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:(await PL(t,{account:n.address,amount:c,chainId:s.chainId,client:s.client,token:s.token}),HI(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await NL(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken))}function HL(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return zI(a.client,t,i,_L(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function UL(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return BI(a.client,t,i,_L(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}var WL,GL,KL,qL=z((()=>{Gx(),aS(),CP(),xS(),FP(),eF(),lL(),HF(),CI(),UI(),nL(),sj(),WL=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),GL=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),KL=Y.object({account:Y.optional(Y.custom()),autoSwap:Y.optional(Y.custom()),action:Y.optional(Y.enum([`open`,`topUp`,`voucher`,`close`])),channelId:Y.optional(GL),cumulativeAmount:Y.optional(dS()),cumulativeAmountRaw:Y.optional(Y.string()),transaction:Y.optional(WL),descriptor:Y.optional(Y.custom()),additionalDeposit:Y.optional(dS()),additionalDepositRaw:Y.optional(Y.string()),depositRaw:Y.optional(Y.string())})}));async function JL(e,t){let n=iR.get(e)??new Map;iR.set(e,n);let r=n.get(t),i,a=new Promise(e=>{i=e});return n.set(t,a),await r,()=>{i(),n.get(t)===a&&n.delete(t)}}function YL(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function XL(e,t,n){try{let r=e.response?.headers.get(q.paymentReceipt);if(r){let e=fA(r);if(e.challengeId===t.id&&YL(n,e))return!0}}catch{}return e.challenges?.some(e=>mj(e)?YL(n,hj(e)):!1)??!1}function ZL(e){let{allowedChainIds:t,currencies:n,decimals:r,expectedRecipients:i,maxAmount:a,maxAtomicAmount:o}=e;if((a!==void 0||o!==void 0)&&n===void 0)throw Error(`Tempo session maxAmount and maxAtomicAmount require currencies.`);for(let e of n??[])QL(a,typeof e==`string`?r:e.decimals);return{chainId:t?.length===1?t[0]:void 0,currencies:n,decimals:r,expectedRecipients:i?new Set(i.map(e=>e.toLowerCase())):void 0,maxAmount:a,maxAtomicAmount:o===void 0?void 0:BigInt(o)}}function QL(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo session maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo session maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return me(e,t)}}function $L(e,t,n){let r=e.currencies?eN(e.currencies,t.currency,{chainId:t.methodDetails?.chainId??n??e.chainId,decimals:e.decimals}):void 0;if(e.currencies&&!r)throw Error(`Tempo session currency is not allowed: ${t.currency}.`);if(e.expectedRecipients&&(!t.recipient||!e.expectedRecipients.has(t.recipient.toLowerCase())))throw Error(`Unexpected session recipient: ${t.recipient}`);let i=BigInt(t.amount);if(e.maxAtomicAmount!==void 0&&i>e.maxAtomicAmount)throw Error(`Tempo session amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0&&i>QL(e.maxAmount,r?.decimals))throw Error(`Tempo session amount exceeds maxAmount.`)}function eR(e,t){try{return $L(e,t),!0}catch{return!1}}function tR(e){return typeof e==`object`&&!!e&&e.action===`close`}function nR(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:f}=e,p=ZL(e),m=yP({chain:$e,getClient:c,rpcUrl:iM}),h=mP({account:t}),g=(e,t)=>{let n=(p.currencies?eN(p.currencies,e.currency,{chainId:e.methodDetails?.chainId??t??p.chainId,decimals:a}):void 0)?.decimals??a??6;return{decimals:n,maxDeposit:l===void 0?void 0:me(l,n),topUpAmount:u===void 0?void 0:me(u,n)}};l!==void 0&&me(l,6),u!==void 0&&me(u,6);let _=e.origin===void 0?void 0:new URL(e.origin);if(_&&![`http:`,`https:`].includes(_.protocol))throw Error(`Session origins require HTTP or HTTPS`);let v=i??KI(),y={store:v,notifyUpdate:e=>d?.(e)},b=async(e,t,n)=>{let r=h(e.client,t),i=t?.action?t.descriptor:n?.descriptor??DL({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:LF(i)}:{}}})??r},x=async(e,t,n)=>{let{decimals:r,maxDeposit:i}=g(e.challenge.request,e.chainId);return jL({account:await b(e,t,n),entry:n,context:t,decimals:r,maxDeposit:i,resolved:e})},S=bk(Qk,{canHandleChallenge:({challenge:e,context:t})=>mj(e)&&(tR(t)||t===_w||eR(p,e.request)),context:KL,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&$L(p,t.request);let a=await wL({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m});i?.action!==`close`&&t.request.methodDetails?.chainId===void 0&&$L(p,t.request,a.chainId);let c=rE(e),l=cE(e)??_?.origin;if(l!==void 0&&(l===`null`||![`http:`,`https:`].includes(new URL(l).protocol)))throw Error(`Session payments require an HTTP or HTTPS origin`);if(_&&l!==_.origin)throw Error(`Session channel origin mismatch`);let u={...y,origin:l},d=()=>{};try{let e=!mL(i)&&i?.descriptor===void 0;e&&(d=await JL(v,a.key),c&&(await v.get(a.key))?.opened&&await c.prepare());let n=await v.get(a.key);if(n&&n.origin!==l)throw Error(`Session channel origin mismatch`);if(l&&!n&&a.snapshot&&!i?.descriptor&&!_)throw Error(`Session snapshot recovery requires an explicitly configured origin or descriptor`);let o=await x(a,i,n);if(!e&&c&&o.type===`open`){d=await JL(v,a.key);let e=await v.get(a.key);if(e&&e.origin!==l)throw Error(`Session channel origin mismatch`);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await v.get(a.key)),o=await x(a,i,n))}let s,f=c&&o.type===`open`?{store:{get:e=>v.get(e),async set(e){s=l?{...e,origin:l}:e},delete:e=>v.delete(e)},notifyUpdate(){}}:u,p=await II(t,await ML(o,f,jP(i?.autoSwap??r,NP)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||XL(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await v.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await QI(v,e),y.notifyUpdate(e))}return!0}finally{d()}}}else d();return p}catch(e){throw d(),e}}});function C(e,t,n){let r={challenge:e,context:t};return sE(r,rR(n)),S.createCredential(r)}let w=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>ZI(v,GI(n),async()=>{s?.throwIfAborted();let c=await v.get(GI(n));if(c?.channelId===n.channelId&&(n=c),n.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let l=n.deposit>r?n.deposit:r,{maxDeposit:u,topUpAmount:d}=g(t.request,n.chainId),f=GA({deposit:l,maxDeposit:u,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:d});f>0n&&await xj({autoSwap:e,additionalDeposit:f,challenge:t,channel:n,channelId:n.channelId,createSessionCredential:(e,t)=>C(e,t,a),onUncertainFunding:async e=>{let t=await v.get(GI(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await QI(v,n),y.notifyUpdate(n)},fetch:i,input:a,signal:s});let p=l+f;if(p===n.deposit)return;let m=await v.get(GI(n)),h=m?.channelId.toLowerCase()===n.channelId.toLowerCase()?m:n,_={...h,deposit:h.deposit>p?h.deposit:p};await QI(v,_),y.notifyUpdate(_)});return JT(S,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!mj(e))return;let c=t===void 0?void 0:KL.parse(t);if(mL(c))return;$L(p,e.request);let l=await wL({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),u=await v.get(l.key);if(!u?.opened)return;let d=rR(i);if(u.origin!==d)throw Error(`Session channel origin mismatch`);let f=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,h=u.cumulativeAmount+lA(e),g=f?BigInt(f.requiredCumulative):h,_=g>h?g:h,y=f?BigInt(f.deposit):u.deposit,x=y>u.deposit?y:u.deposit;_<=x&&x===u.deposit||!AL(await b(l,c,u),u.descriptor)||await w({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:x,fetch:r,input:i,requiredCumulative:_,signal:a})}),eE(S,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!mj(e))return u;if(!pA(u))return cA(cC(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await wL({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,p=await v.get(f),h={assertVoucherWithinLocalLimit:t=>KA(t,g(e.request,p?.chainId).maxDeposit),createSessionCredential:(e,t)=>C(e,t,c),fetch:i,getChannel:()=>p??null,async topUpIfNeeded({deposit:n,requiredCumulative:r,signal:a}){p&&await w({autoSwap:t===void 0?void 0:KL.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return Mj({onNeedVoucher:(t,n)=>Nj({challenge:e,driver:h,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function rR(e){let t=new URL(e instanceof Request?e.url:e,globalThis.location===void 0?void 0:globalThis.location.href);if(![`http:`,`https:`].includes(t.protocol))throw Error(`Session payments require an HTTP or HTTPS origin`);return t.origin}var iR,aR=z((()=>{$T(),pE(),Gx(),vC(),tN(),vw(),xk(),hP(),CP(),FP(),aM(),eA(),HF(),CA(),UI(),nL(),qL(),sj(),iR=new WeakMap}));function oR(e,t){cR.set(e,t)}function sR(e){let t=cR.get(e);if(!t)throw Error(`Session manager internals are unavailable.`);return t}var cR,lR=z((()=>{cR=new WeakMap}));function uR(e){let t=null;return{wait(n=()=>!0){if(t)throw Error(`${e} wait already in progress`);return new Promise((e,r)=>{t={predicate:n,resolve:e,reject:r}})},settle(e){if(!t||!t.predicate(e))return;let n=t;t=null,n.resolve(e)},reject(e){if(!t)return;let n=t;t=null,n.reject(e)}}}function dR(e){let t=uR(`close-ready`),n=uR(`receipt`);return{waitForReceipt(e){return n.wait(e)},waitForCloseReady(){let n=e.getSocketSession()?.closeReadyReceipt;return n?Promise.resolve(n):t.wait()},settleReceipt(e){n.settle(e)},settleCloseReady(n){let r=e.getSocketSession();r&&r.challenge.id===n.challengeId&&r.channelId===n.channelId&&(r.closeReadyReceipt=n),t.settle(n)},rejectReceipt(e){n.reject(e)},rejectCloseReady(e){t.reject(e)}}}var fR=z((()=>{}));function pR(e){return e.method===Vx.tempo&&e.intent===Hx.charge}function mR(e){if(!pR(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function hR(e,t,n){if(!n)return t;let r={...OD(_j(e)?e.headers:void 0),...OD(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===q.paymentSession.toLowerCase())?t:{...t,headers:{...r,[q.paymentSession]:n}}}function gR(e,t){return e===void 0?t:{...KL.parse(e),...t}}function _R(e){let t=e.decimals??6,n=e.webSocket??globalThis.WebSocket;return{decimals:t,fetch:e.fetch??globalThis.fetch.bind(globalThis),maxVoucherCumulative:e.maxDeposit===void 0?null:me(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:me(e.topUpAmount,t),WebSocket:n}}function vR(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&xP(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=_R(e),i;function a(e){let t=new URL(_j(e)?e.url:String(e),typeof location>`u`?void 0:location.href);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`SessionManager: session payments require an HTTP origin`);let n=t.origin;if(i!==void 0&&i!==n)throw Error(`SessionManager: session payment origin mismatch`);return i=n,n}if(ZD(r.fetch))throw TypeError(`SessionManager: the fetch sets spending options (maxPayment, authorize, funders or tokens), which accept only charges. Pass a fetch without them.`);let o=XD(r.fetch),s=QD(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??(_j(e)?e.redirect:void 0))===`manual`?`manual`:`error`});if(r.url&&new URL(r.url).origin!==n)throw Error(`SessionManager: session response origin mismatch`);return r};let c=r.fetch;o&&(r.fetch=IC(c,o));let l=yP({chain:$e,getClient:e.client?()=>e.client:e.getClient,rpcUrl:iM}),u=mP({account:e.account}),d=QA(),f=e.credentialContext===void 0?void 0:gR(e.credentialContext,{}),p=dR({getSocketSession:()=>d.socketSession}),m=e.channelStore??KI(),h=new Set,g;async function _(e){let t=await m.get(e);if(t?.opened&&!h.has(t.channelId)){if(t.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return t}}let v=e=>{if(e.origin!==void 0&&e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return e.origin=i,QI(m,e)},y={async get(e){let t=await _(e);return t&&g&&(g.seenExisting.add(e),!g.committed&&!g.created.has(e)&&(g.resumed??=t)),t},async set(e){let t=GI(e);e.opened&&h.delete(e.channelId),g?.trackCreates&&!g.seenExisting.has(t)&&g.created.set(t,e),await v(e)},delete:e=>$I(m,e)};YI(y,m);async function b(e){let t=GI(e),n=await m.get(t);if(e.uncertainTopUp||n?.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);h.add(e.channelId),g?.seenExisting.delete(t),g?.resumed===e&&(g.resumed=void 0),await Promise.resolve($I(m,t)).catch(()=>void 0)}async function x(){let e=g;if(e?.created.size){for(let[t,n]of e.created){let e=await m.get(t);if(n.uncertainTopUp||e?.channelId===n.channelId&&e.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before discarding the channel.`);h.add(n.channelId),await Promise.resolve($I(m,t)).catch(()=>void 0)}e.created.clear(),await L(e.committed??e.previous)}}function S(e){let t=zx(e.request.methodDetails,Ux.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=g;if(!n?.created.size||!d.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&d.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=rj({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function C(e){return FA(d,e)}function w(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function T(e){let t=g,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit&&!e.uncertainTopUp||(t.resumed=void 0,t.committed=rj({channel:d.channel,spent:d.spent,state:d.state}))}let E=nR({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:y,onChannelUpdate(e){e.channelId!==d.channel?.channelId&&(d.spent=0n),d.channel=e,d.lastChallenge&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}}),ee=ZT(E);ee&&JT(E,e=>oe(()=>Promise.resolve(ee(e)),e.signal)),tE(E);let D=mF({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),O=ED({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[E],onChallenge:async(e,t)=>{if(!pj(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&mO(e)===mO(d.lastChallenge);n&&n.challengesReceived++,!i&&(S(e)||(n?.created.size?await x():r&&await L(n.committed??n.previous)),d.lastChallenge=e,C({type:`challengeReceived`,challengeId:e.id}))}});function k(e,t){let n={challenge:e,context:gR(f,t)};return i&&sE(n,i),E.createCredential(n)}function te(e){$A({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:d})}function A(e=d.state.status===`active`?d.state.units:0){!d.channel||!d.lastChallenge||d.state.status!==`active`&&d.state.status!==`withdrawable`&&d.state.status!==`closeRequested`&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:d.channel,spent:d.spent.toString(),units:e})}async function j(t){let r=t.headers.get(q.paymentSessionSnapshot);if(!r)return;let i=TA(r);xP(e.allowedChainIds,i.chainId),FI({request:{methodDetails:{escrow:i.escrow}}},e.escrow,n);let a=await l({chainId:i.chainId});bP(a,i.chainId);let o=u(a),{entry:s,spent:c}=await kL({account:await e.resolveAccount?.({account:o,chainId:i.chainId,operation:{authority:LF(i.descriptor),kind:`authorizePaymentChannel`}})??o,client:a,snapshot:i});return ie(s.cumulativeAmount),await Promise.resolve(y.set(s)).catch(()=>void 0),d.channel=s,d.spent=c,s}async function M(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=_j(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=_j(t)?t.url:t,l={...s,method:`HEAD`,headers:{...OD(i),...OD(n?.headers),[q.acceptPayment]:`${Vx.tempo}/${Hx.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await j(t);let n=RS(t).find(pR);if(!n||!mR(n))return;let i=new URL(String(c),typeof location<`u`?location.href:void 0);if(t.url&&new URL(t.url).origin!==i.origin)return;gE(n,i,e.trustedTempoProofRealms);let a=await D.createCredential({challenge:n,context:{}}),o=await r.fetch(c,iT({...l,redirect:`manual`},GS(n),a));return o.ok?await j(o):void 0}catch{return}}function ne(e,t){let n=d.socketSession;return tj({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:d.channel?.channelId===t?d.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:d.spent,tickCost:n?.tickCost})}function N(e,t){let n=hj(t);if(!n)return;if(RF({...n.descriptor,chainId:n.chainId,escrow:n.escrow}).toLowerCase()!==n.channelId.toLowerCase())throw Error(`close snapshot descriptor does not match its channel ID`);if(n.channelId.toLowerCase()!==e.channelId.toLowerCase())throw Error(`close snapshot channel ID does not match local session`);if(n.chainId!==e.chainId||n.escrow.toLowerCase()!==e.escrow.toLowerCase())throw Error(`close snapshot payment scope does not match local session`);let r=BigInt(n.acceptedCumulative),i=BigInt(n.spent);if(r<0n||i<0n)throw Error(`close snapshot amounts must not be negative`);if(i>r)throw Error(`close snapshot spent exceeds accepted cumulative amount`);if(r>e.cumulativeAmount)throw Error(`close snapshot accepted cumulative exceeds local voucher state`);return{acceptedCumulative:r,spent:i}}function P(e,t){let n=N(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(d.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>d.spent&&(d.spent=i),n}function re(e,t=e.challenge,n=!1){let r=(n?P(e,t):N(e.channel,t))?.acceptedCumulative??ne(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return ie(r),r.toString()}function ie(e){BA({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let ae,F;async function oe(e,t){if(F)throw F;for(;;){let e=ae;if(!e)break;if(!t)await e;else{t.throwIfAborted();let n;try{await Promise.race([e,new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0})})])}finally{t.removeEventListener(`abort`,n)}}}if(t?.throwIfAborted(),F)throw F;let n=e();ae=n;try{return await n}catch(e){throw e instanceof Xj&&(F=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{ae===n&&(ae=void 0)}}async function se(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return ZI(m,GI(d.channel),async()=>{let{knownDeposit:t,...n}=e,i=d.channel?await y.get(GI(d.channel)):void 0;if(i?.channelId===e.channelId&&i.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let a=await xj({...n,channel:d.channel,createSessionCredential:k,fetch:r.fetch,onUncertainFunding:async e=>{let t=await y.get(GI(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};d.channel?.channelId===e.channelId&&(d.channel=n),await y.set(n),T(n)}});te(a);let o=d.channel,s=dj({additionalDeposit:e.additionalDeposit,channel:d.channel,channelId:e.channelId,challengeId:d.lastChallenge?.id,currentState:d.state,knownDeposit:t,receipt:a,spent:d.spent});if(s?.channel&&d.lastChallenge){let e=s.channel;for(;;){await y.set(e);let t=d.channel;if(t===o)break;if(!t)return a;let n=s.channel;e=t.channelId===n.channelId?{...t,deposit:t.deposit>n.deposit?t.deposit:n.deposit,cumulativeAmount:t.cumulativeAmount>n.cumulativeAmount?t.cumulativeAmount:n.cumulativeAmount}:t,o=t}if(e.channelId!==s.channel.channelId)return a;d.channel=e,C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}return a})}async function I(e){return oe(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=GA({deposit:n,maxDeposit:r.maxVoucherCumulative,requiredCumulative:e.requiredCumulative,suggestedDeposit:e.challenge.request.suggestedDeposit===void 0?void 0:BigInt(e.challenge.request.suggestedDeposit),topUpAmount:r.topUpAmount});i!==0n&&await se({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function ce(e,t){let n=nj({channel:d.channel,channelId:e,challengeId:d.lastChallenge?.id,cumulativeAmount:t,spent:d.spent,state:d.state});n&&d.channel&&(C({type:`activated`,challengeId:n.challengeId,entry:d.channel,spent:n.spent,units:n.units}),await v(d.channel))}async function L(e){let t=ij(e,d.channel);d.channel=t.channel,d.spent=t.spent,d.state=t.state,d.channel?.opened&&await v(d.channel)}function le(e,t=!0){let n=e.headers.get(q.paymentReceipt),r=n?fA(n):null;return t&&te(r),Object.assign(e,{receipt:r,challenge:d.lastChallenge,channelId:d.channel?.channelId??null,cumulative:d.channel?.cumulativeAmount??0n})}async function ue(e,t){if(t?.[bO])return le(await r.fetch(e,CD(t)),!1);if(g)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);a(e),d.lastUrl=e,d.lastHeaders=t?.headers;let n=rj({channel:d.channel,spent:d.spent,state:d.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};g=i;try{await M(e,t),i.trackCreates=!0;let a=hR(e,t,d.channel?.opened?d.channel.channelId:void 0);f&&(a={...a,context:f});let o=!n.channel?.opened;async function s(){let n=i.resumed;return!o||!n?!1:(o=!1,await b(n),a=hR(e,t,void 0),!0)}for(;;){let t;try{t=await O(e,a)}catch(e){if(i.created.size?await x():await L(i.committed??n),await s())continue;throw e}let o=le(t),c=!1;if(o.status===402){let t=await Cj({input:e,init:a,response:o,createSessionCredential:k,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:ce,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:I});t&&(c=!0,o=le(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await x():await L(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function de(e){let t=await Tj({createSessionCredential:k,fetch:r.fetch,getMinimumSpent:()=>d.spent,headers:d.lastHeaders,lastUrl:d.lastUrl,resolveSignedCloseAmount:t=>re(e,t,!0),signedCloseAmount:re(e),setChallenge(e){d.lastChallenge=e},target:e});return t&&(A(),C({type:`closeStarted`}),C({type:`closed`,receipt:t})),t}let fe={createSessionCredential:k,doFetch:ue,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:ie,acceptReceipt(e){te(e)},topUpIfNeeded:I},pe={get channelId(){return d.channel?.channelId},get cumulative(){return d.channel?.cumulativeAmount??0n},get opened(){return d.channel?.opened??!1},get state(){return d.state},fetch:ue,async topUp(e){let t=uj({amount:e,assertVoucherWithinLocalLimit:ie,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return oe(async()=>{if(d.channel?.channelId!==t.channelId||d.lastChallenge!==t.challenge||d.lastUrl!==t.input)throw Error(`Session changed while waiting to top up`);let n=uj({amount:e,assertVoucherWithinLocalLimit:ie,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return se({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){if(t?.[bO])throw Error(`SessionManager.sse requires payment; use fetch for unpaid streams.`);return Ej(e,t,fe)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=yj(e);a(n);let i=t?.signal?{signal:t.signal}:void 0;await M(n,i);let o=d.channel?.opened?d.channel.channelId:void 0,{challenge:s,credential:c,httpUrl:l,wsUrl:u}=await Fj({async createSessionCredential(e,i){return d.lastChallenge=e,await XT(E,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),k(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){d.lastUrl=e.toString()},probeInit:hR(n,i,o),signal:t?.signal});return d.lastChallenge=s,Bj({challenge:s,credential:c,httpUrl:l,WebSocket:r.WebSocket,wsUrl:u,options:t,createSessionCredential:k,getChannel:()=>d.channel,setSocketSession(e){d.socketSession=e},async refreshChallenge(){let e=await Pj({fetch:r.fetch,input:l,probeInit:hR(l,i,d.channel?.opened?d.channel.channelId:void 0),signal:t?.signal});return d.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:ie,acceptReceipt:te,rejectCloseReady:p.rejectCloseReady,rejectReceipt:p.rejectReceipt,settleCloseReady:p.settleCloseReady,settleReceipt:p.settleReceipt,topUpIfNeeded:I,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=qA({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===qj.OPEN){let r=await aj({activeSocket:n,createSessionCredential:k,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return A(),C({type:`closeStarted`}),C({type:`closed`,receipt:r}),r}return de(t)}};return oR(pe,{consumeSseResponse(e,t,n){let r=a(e);if(t.url&&new URL(t.url).origin!==r)throw Error(`SessionManager: session response origin mismatch`);return Dj(e,t,n,fe)},rehydrate({channel:e,challenge:t,input:n,spent:r}){let i=a(n);if(e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!pj(t))throw Error(`Cannot restore session: challenge is not tempo/session.`);if(r<0n)throw Error(`Cannot restore session: spent must not be negative.`);if(r>e.cumulativeAmount)throw Error(`Cannot restore session: spent exceeds local voucher state.`);ie(e.cumulativeAmount);let o=N(e,t),s=o&&o.spent>r?o.spent:r;d.lastUrl=n,d.lastChallenge=t,d.channel=e,d.spent=s,C({type:`challengeReceived`,challengeId:t.id}),C({type:`activated`,challengeId:t.id,entry:e,spent:s.toString(),units:0})}}),pe}var yR=z((()=>{sC(),DO(),$T(),pE(),bE(),lT(),Gx(),qC(),hP(),CP(),IF(),aM(),UI(),nL(),qL(),aR(),HF(),CA(),MA(),lR(),fR(),sj(),Zj(),(function(e){e.serializeSnapshot=wA,e.deserializeSnapshot=TA})(vR||={})}));function bR(e){return e instanceof Date?e:new Date(e)}function xR(e){let t=e.getTime();if(!Number.isFinite(t))throw new J({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new J({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new J({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function SR(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new J({reason:`periodCount is invalid`});let t=VR[e.periodUnit];if(t===void 0)throw new J({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>BR)throw new J({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new J({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function CR(e){let{challengeExpires:t,request:n}=e;SR(n);let r=xR(bR(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new J({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function wR(e){let t=LR(e.currency,`currency`),n=LR(e.recipient,`recipient`);return[{address:t,selector:zR,recipients:[n]}]}function TR(e){try{let t=M.fromBytes(te.toBytes(e));if(M.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new J({reason:`challenge id must encode 32 bytes`})}}async function ER(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=OR({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:qe.getSignPayload(o)}),c=Je.from(s);if(c.type===`keychain`||c.type===`configurable`)throw new J({reason:`keyAuthorization must use a primitive signature`});return qe.from(o,{signature:Je.serialize(YF(c))})}function DR(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new J({reason:`invalid keyAuthorization payload`});let o=kR(i.signature),s=AR(o);if(jR({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==TR(n))throw new J({reason:`keyAuthorization challenge mismatch`});return MR(o,a),PR(NR(o),a),FR(o.scopes,a),{authorization:o,source:{address:IR(o,s),chainId:r}}}function OR(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return qe.from({address:LR(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:xR(bR(i.subscriptionExpires)),limits:[{token:LR(i.currency,`currency`),limit:BigInt(i.amount),period:SR(i)}],scopes:wR(i),type:t.keyType,witness:TR(n)})}function kR(e){try{return qe.deserialize(e)}catch(e){throw e instanceof qe.InvalidSignatureTypeError?new J({reason:`keyAuthorization must use a primitive signature`}):new J({reason:`invalid keyAuthorization payload`})}}function AR(e){let t=e.signature;if(!t)throw new J({reason:`keyAuthorization must use a primitive signature`});return t}function jR(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new J({reason:`keyAuthorization chainId mismatch`});if(t){if(!ue(n.address,LR(t.accessKeyAddress,`accessKeyAddress`)))throw new J({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new J({reason:`keyAuthorization key type mismatch`})}}function MR(e,t){if(CR({request:t}),e.expiry!==xR(bR(t.subscriptionExpires)))throw new J({reason:`keyAuthorization expiry mismatch`})}function NR(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new J({reason:`keyAuthorization must contain exactly one token limit`});return t}function PR(e,t){if(!ue(e.token,LR(t.currency,`currency`)))throw new J({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new J({reason:`keyAuthorization amount mismatch`});if(e.period!==SR(t))throw new J({reason:`keyAuthorization period mismatch`})}function FR(e,t){if(!e||e.length!==1)throw new J({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=LR(t.currency,`currency`),r=LR(t.recipient,`recipient`),i=new Set;for(let t of e){if(!ue(t.address,n))throw new J({reason:`keyAuthorization call target mismatch`});let e=RR(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new J({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new J({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!ue(t.recipients[0],r))throw new J({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new J({reason:`keyAuthorization must allow transferWithMemo`})}function IR(e,t){let n=qe.getSignPayload(e);try{let e=Je.extractAddress({payload:n,signature:t});if(!JF(t)||!Je.verify(t,{address:e,payload:n}))throw new J({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof J?e:new J({reason:`keyAuthorization signature is invalid`})}}function LR(e,t){if(!le(e))throw new J({reason:`${t} must be an address`});return e.toLowerCase()}function RR(e){return typeof e==`string`?e.toLowerCase():``}var zR,BR,VR,HR=z((()=>{aS(),eI(),zR=`0x95777d59`,BR=(1n<<64n)-1n,VR={dev_second:1n,day:86400n,week:604800n}}));function UR(e={}){let t=yP({chain:ve,requireChain:!0,getClient:e.getClient,rpcUrl:iM}),n=mP({account:e.account});return bk($k,{context:KR,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??$j.testnet,o=await t({chainId:a});if(o.chain?.id!==a)throw Error(`Subscription chain mismatch: expected ${a}, got ${o.chain?.id??`unknown`}.`);let s=n(o,i),c=i?.accessKey??e.accessKey??r.request.methodDetails?.accessKey;if(!c)throw Error("No `accessKey` provided. The subscription challenge must include `accessKey`, or the client must pass one to parameters/context.");GR(r.request),await e.validateRequest?.(r.request);let l=await WR(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=DR({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:qe.serialize(l),type:`keyAuthorization`},request:r.request});if(!ue(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return pC({challenge:r,payload:{signature:qe.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function WR(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await ER({accessKey:n,account:r,challengeId:i,chainId:a,request:o});if(s)return s;let c=await e.request({method:`wallet_authorizeAccessKey`,params:[{address:n.accessKeyAddress,expiry:xR(bR(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:M.fromNumber(BigInt(o.amount)),period:SR(o)}],scopes:wR(o),witness:TR(i)}]});return qe.fromRpc(c.keyAuthorization)}function GR(e){SR(e),xR(bR(e.subscriptionExpires))}var KR,qR=z((()=>{vC(),xk(),hP(),CP(),xS(),aM(),eA(),HR(),KR=Y.object({accessKey:Y.optional(Y.custom()),account:Y.optional(Y.custom())})}));function JR(e={}){let t=e.expectedChainId!==void 0&&(e.allowedChainIds===void 0||e.allowedChainIds.includes(e.expectedChainId)),n=e.expectedChainId===void 0?e:{...e,allowedChainIds:t?[e.expectedChainId]:[]};return[mF(e),YR(n)]}var YR,XR=z((()=>{aR(),yR(),IF(),qR(),YR=Object.assign(nR,{manager:vR}),(function(e){e.charge=mF,e.common=JR,e.session=YR,e.subscription=UR})(JR||={})})),ZR=z((()=>{IF(),XR(),qR(),nL(),aR(),yR()})),QR=it({orderTempoChargeChallengesByBalance:()=>ez,readTempoKeystore:()=>bz,resolveTempoAccount:()=>xz,tempo:()=>tz});async function $R(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}async function ez(e,t){let n=[],r=[];for(let[t,i]of e.entries())cz(i)&&(n.push(t),r.push(i));if(r.length<2)return[...e];let i=await lz(t).catch(()=>void 0);if(!i)return[...e];let a=await Promise.all(r.map(async(e,t)=>({challenge:e,index:t,score:await uz(e,i)})));a.sort((e,t)=>kz.indexOf(e.score)-kz.indexOf(t.score)||e.index-t.index);let o=[...e];for(let[e,t]of n.entries())o[t]=a[e].challenge;return o}function tz(){let e;return eP({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:t,options:n,methodOpts:r}){let i=HM(n.account),a=t.request,o=a.currency,s=sz(r),c=mz({autoSwap:s.autoSwap??n.autoSwap,payWith:s.payWith??n.payWith,slippage:s.slippage??n.slippage,tokenIn:s.tokenIn}),l=o??``,u=a.decimals??6,d,f,p,m=!1,h=process.env.MPPX_PRIVATE_KEY?.trim()||(gM(i)?void 0:await UM(i).get());if(!h&&gM(i)&&Sz()){m=!0;let e=xz(i);if(e){let r=bM(n.rpcUrl,{network:n.network});p=N({chain:await SM({network:n.network,rpcUrl:r}),transport:L(r)}),fz({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let i=o?await EM(p,o,e.wallet_address).catch(()=>void 0):void 0;l=i?.symbol??o??``,u=i?.decimals??a.decimals??6}}else if(h)f=R(h);else{let e=wz();if(e){let t=await UM(e).get();t&&(f=R(t))}if(!f)throw n.account?new B({code:`ACCOUNT_NOT_FOUND`,message:`Account "${i}" not found.`,exitCode:69}):new B({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!m&&f){let e=bM(n.rpcUrl,{network:n.network});p=N({chain:await SM({network:n.network,rpcUrl:e}),transport:L(e)}),fz({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let r=o?await EM(p,o,f.address).catch(()=>void 0):void 0;l=r?.symbol??o??``,u=r?.decimals??a.decimals??6}if(m)return{tokenSymbol:l,tokenDecimals:u,explorerUrl:d,methods:[],async createCredential(e){let t=e.headers.get(`www-authenticate`);if(!t)throw Error(`No WWW-Authenticate header in 402 response.`);return Cz(t)}};if(!f||!p)throw new B({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let g=JR({account:f,...s.allowCustomEscrow===void 0?{}:{allowCustomEscrow:s.allowCustomEscrow},getClient:()=>p,...c===void 0?{}:{autoSwap:c},maxDeposit:(()=>{if(t.intent!==`session`)return;let e=t.request.suggestedDeposit,n=(s.deposit===void 0?void 0:String(s.deposit))??e??(TM(p.chain)?`10`:void 0);if(!n)throw new B({code:`MISSING_DEPOSIT`,message:`Session payment requires a deposit. Use -M deposit=<amount> or connect to testnet.`,exitCode:2});return n})()}),_=(()=>{if(!s.channel)return;let e=s.channel,t=gz(e);return{channelId:e,...t!==void 0&&{cumulativeAmountRaw:t.toString()}}})();return e={descriptor:void 0,async signVoucher({channelId:n,cumulativeAmount:r,escrowContract:i,chainId:a,action:o=`voucher`}){let s=e?.descriptor;if(!s)throw Error(`session descriptor not available`);let c={channelId:n,cumulativeAmount:r},l=await gI(p,f,c,i,a);return pC({challenge:t,payload:{action:o,channelId:n,...o===`close`?{closeSignature:await _I(p,f,c,i,a)}:{},descriptor:s,cumulativeAmount:r.toString(),signature:l},source:`did:pkh:eip155:${a}:${f.address}`})},source:`did:pkh:eip155:${p.chain.id}:${f.address}`},{tokenSymbol:l,tokenDecimals:u,explorerUrl:d,methods:[...g],credentialContext:_}},prepareCredentialRequest({challenge:e,headers:t}){e.intent===`session`&&(t.Accept=`text/event-stream`)},async handleResponse(t){if(t.challenge.intent!==`session`||!e)return!1;let{challenge:n,credential:r,response:i,fetchUrl:a,fetchInit:o,verbose:s}=t,{silent:c,confirmEnabled:l,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,shownKeys:p}=t,m=c?e=>{}:e=>process.stderr.write(e),h=cC(r),g=n.request,_=g.methodDetails,v=h.payload.channelId,y=_?.escrowContract??_?.escrow??`0x4d50500000000000000000000000000000000000`,b=_?.chainId??0,x=BigInt(g.amount),S=`cumulativeAmount`in h.payload&&h.payload.cumulativeAmount?BigInt(h.payload.cumulativeAmount):0n;if(`descriptor`in h.payload&&(e.descriptor=h.payload.descriptor),s>=1){if(h.payload.action===`open`){let e=g.suggestedDeposit,t=e?` ${X.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
238
238
  `}${X.dim(`Channel opened ${h.payload.channelId}`)}${t}\n`)}else m(`${l?``:`
239
- `}${X.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let C=i;C.ok&&!C.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let w=C.headers.get(q.paymentReceipt);if(w)try{let e=JSON.parse(te.toString(w));nz(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&gz(v,S),s>=1&&tz(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
240
- `})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await rz(C,{challenge:n,channelId:v,escrowContract:y,chainId:b,cumulativeAmount:S,tickCost:x,fetchUrl:a,fetchInit:o,session:e,info:m,verbose:s,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this}):(await QR(C),v&&y&&b&&(l&&m(`
241
- `),l&&!await t.confirm(`Close channel?`,!0)?s>=1&&m(`${X.dim(`Kept channel open.`)}\n`):await iz({channelId:v,cumulativeAmount:S,escrowContract:y,chainId:b,fetchUrl:a,fetchInit:o,session:e,info:m,verbose:s,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,confirmEnabled:l}))),!0},formatReceiptField(e,t){(e===`reference`||e===`txHash`)&&typeof t==`string`&&t.startsWith(`0x`)}})}function tz(e,t){t.info(`${t.prefix??``}${X.bold(X.green(`Payment Receipt`))}\n`);let n=[],r=e.channelId&&e.reference&&e.channelId===e.reference,i=new Set([`acceptedCumulative`,`spent`]);for(let[a,o]of Object.entries(e)){if(o===void 0||t.shownKeys.has(a)||a===`reference`&&r)continue;let e=t.handler.formatReceiptField?.(a,o);e===void 0?i.has(a)&&typeof o==`string`?n.push([a,`${o} ${X.dim(`(${yM(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,pM(`${t.explorerUrl}/tx/${o}`,o)]):n.push([a,String(o)]):n.push([a,e])}n.sort(([e],[t])=>e.localeCompare(t));let a=Math.max(...n.map(([e])=>e.length));for(let[e,r]of n)t.info(` ${X.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
242
- `)}function nz(e,t){if(typeof e.acceptedCumulative!=`string`)return;let n=BigInt(e.acceptedCumulative),r=typeof e.spent==`string`?BigInt(e.spent):0n;if(r>n)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(n>t)throw Error(`receipt accepted cumulative exceeds locally signed voucher amount`);if(r>t)throw Error(`receipt spent exceeds locally signed voucher amount`)}async function rz(e,t){let n=t.cumulativeAmount,r=e.body?.getReader();if(!r)throw Error(`No response body`);let i=new TextDecoder,a=``,o=``,s=t.verbose?await az():void 0,c=(()=>{if(!s||!X.isColorSupported)return;let e=e=>Math.max(0,Math.min(255,Math.round(e))),t=.299*s.r+.587*s.g+.114*s.b<128?1:-1,n=n=>r=>`\x1b[48;2;${e(s.r+n*t)};${e(s.g+n*t)};${e(s.b+n*t)}m${r}\x1b[49m`;return[n(12),n(24)]})(),l=0,u=e=>{if(c){let t=c[l%c.length];process.stdout.write(e.replace(/[^\n]+/g,e=>t(e))),l++}else process.stdout.write(e)},d=async e=>{for(let r of e){if(r.startsWith(`event: `)){o=r.slice(7).trim();continue}if(!r.startsWith(`data: `)){r===``&&(o=``);continue}let e=r.slice(6);if(e.trim()!==`[DONE]`){if(o===`payment-need-voucher`&&t.channelId&&t.escrowContract&&t.chainId){try{let r=JSON.parse(e);if(r.channelId!==t.channelId)throw Error(`payment-need-voucher channelId does not match current session`);let i=BigInt(r.requiredCumulative);if(i>n+t.tickCost)throw Error(`payment-need-voucher exceeds next locally billable amount`);n=n>i?n:i;let a=await t.session.signVoucher({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId});await globalThis.fetch(t.fetchUrl,{method:`POST`,headers:{[q.authorization]:a}})}catch(e){t.info(X.dim(X.yellow(` [voucher failed: ${e instanceof Error?e.message:e}]`)))}o=``;continue}if(o===`payment-receipt`){if(t.verbose>=1)try{tz(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
239
+ `}${X.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let C=i;C.ok&&!C.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let w=C.headers.get(q.paymentReceipt);if(w)try{let e=JSON.parse(te.toString(w));rz(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&_z(v,S),s>=1&&nz(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
240
+ `})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await iz(C,{challenge:n,channelId:v,escrowContract:y,chainId:b,cumulativeAmount:S,tickCost:x,fetchUrl:a,fetchInit:o,session:e,info:m,verbose:s,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this}):(await $R(C),v&&y&&b&&(l&&m(`
241
+ `),l&&!await t.confirm(`Close channel?`,!0)?s>=1&&m(`${X.dim(`Kept channel open.`)}\n`):await az({channelId:v,cumulativeAmount:S,escrowContract:y,chainId:b,fetchUrl:a,fetchInit:o,session:e,info:m,verbose:s,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,confirmEnabled:l}))),!0},formatReceiptField(e,t){(e===`reference`||e===`txHash`)&&typeof t==`string`&&t.startsWith(`0x`)}})}function nz(e,t){t.info(`${t.prefix??``}${X.bold(X.green(`Payment Receipt`))}\n`);let n=[],r=e.channelId&&e.reference&&e.channelId===e.reference,i=new Set([`acceptedCumulative`,`spent`]);for(let[a,o]of Object.entries(e)){if(o===void 0||t.shownKeys.has(a)||a===`reference`&&r)continue;let e=t.handler.formatReceiptField?.(a,o);e===void 0?i.has(a)&&typeof o==`string`?n.push([a,`${o} ${X.dim(`(${yM(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,pM(`${t.explorerUrl}/tx/${o}`,o)]):n.push([a,String(o)]):n.push([a,e])}n.sort(([e],[t])=>e.localeCompare(t));let a=Math.max(...n.map(([e])=>e.length));for(let[e,r]of n)t.info(` ${X.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
242
+ `)}function rz(e,t){if(typeof e.acceptedCumulative!=`string`)return;let n=BigInt(e.acceptedCumulative),r=typeof e.spent==`string`?BigInt(e.spent):0n;if(r>n)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(n>t)throw Error(`receipt accepted cumulative exceeds locally signed voucher amount`);if(r>t)throw Error(`receipt spent exceeds locally signed voucher amount`)}async function iz(e,t){let n=t.cumulativeAmount,r=e.body?.getReader();if(!r)throw Error(`No response body`);let i=new TextDecoder,a=``,o=``,s=t.verbose?await oz():void 0,c=(()=>{if(!s||!X.isColorSupported)return;let e=e=>Math.max(0,Math.min(255,Math.round(e))),t=.299*s.r+.587*s.g+.114*s.b<128?1:-1,n=n=>r=>`\x1b[48;2;${e(s.r+n*t)};${e(s.g+n*t)};${e(s.b+n*t)}m${r}\x1b[49m`;return[n(12),n(24)]})(),l=0,u=e=>{if(c){let t=c[l%c.length];process.stdout.write(e.replace(/[^\n]+/g,e=>t(e))),l++}else process.stdout.write(e)},d=async e=>{for(let r of e){if(r.startsWith(`event: `)){o=r.slice(7).trim();continue}if(!r.startsWith(`data: `)){r===``&&(o=``);continue}let e=r.slice(6);if(e.trim()!==`[DONE]`){if(o===`payment-need-voucher`&&t.channelId&&t.escrowContract&&t.chainId){try{let r=JSON.parse(e);if(r.channelId!==t.channelId)throw Error(`payment-need-voucher channelId does not match current session`);let i=BigInt(r.requiredCumulative);if(i>n+t.tickCost)throw Error(`payment-need-voucher exceeds next locally billable amount`);n=n>i?n:i;let a=await t.session.signVoucher({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId});await globalThis.fetch(t.fetchUrl,{method:`POST`,headers:{[q.authorization]:a}})}catch(e){t.info(X.dim(X.yellow(` [voucher failed: ${e instanceof Error?e.message:e}]`)))}o=``;continue}if(o===`payment-receipt`){if(t.verbose>=1)try{nz(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
243
243
 
244
244
  `})}catch{}o=``;continue}if(e.length===0)u(`
245
245
  `);else try{let t=JSON.parse(e);u(t.token??t.choices?.[0]?.delta?.content??e)}catch{u(e)}o=``}}};for(;;){let{done:e,value:t}=await r.read();if(e)break;a+=i.decode(t,{stream:!0});let n=a.split(`
246
- `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await iz({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId,fetchUrl:t.fetchUrl,fetchInit:t.fetchInit,session:t.session,info:t.info,verbose:t.verbose,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,confirmEnabled:!1})}async function iz(e){let t=await e.session.signVoucher({channelId:e.channelId,cumulativeAmount:e.cumulativeAmount,escrowContract:e.escrowContract,chainId:e.chainId,action:`close`}),n=await globalThis.fetch(e.fetchUrl,{...e.fetchInit,headers:{...OD(e.fetchInit.headers),Authorization:t}});if(n.ok){if(_z(e.channelId),e.verbose>=1){let t=n.headers.get(q.paymentReceipt),r;if(t)try{let e=JSON.parse(te.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${X.dim(pM(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${X.dim(`Channel closed.`)} ${X.dim(`Spent ${yM(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${X.dim(X.yellow(`Channel close failed`))} ${X.dim(`(${n.status})`)}\n`),e.info(`${X.dim(` channelId: ${e.channelId}`)}\n${X.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${X.dim(` escrowContract: ${e.escrowContract}`)}\n${X.dim(` chainId: ${e.chainId}`)}\n${X.dim(` response: ${t||`(empty)`}`)}\n`)}}function az(e=100){return!process.stdin.isTTY||!process.stdout.isTTY?Promise.resolve(void 0):new Promise(t=>{let n=process.stdin.isRaw,r=``,i=()=>{clearTimeout(a),process.stdin.removeListener(`data`,o),process.stdin.isTTY&&process.stdin.setRawMode(n??!1),process.stdin.pause()},a=setTimeout(()=>{i(),t(void 0)},e),o=e=>{r+=e.toString();let n=r.match(/\x1b\]11;rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!n)return;i();let a=e=>Number.parseInt(e.slice(0,2),16);t({r:a(n[1]),g:a(n[2]),b:a(n[3])})};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on(`data`,o),process.stdout.write(`\x1B]11;?\x07`)})}function oz(e){return uz(Ez,e,Dz)}function sz(e){return e.method===`tempo`&&e.intent===`charge`}async function cz(e){let t=VM(e.options.account),n=process.env.MPPX_PRIVATE_KEY?.trim()||(gM(t)?void 0:await HM(t).get()),r;if(n)r=R(n).address;else if(gM(t)&&xz())r=bz(t)?.wallet_address;else{let e=Cz();if(e){let t=await HM(e).get();t&&(r=R(t).address)}}if(!r)return;let i=bM(e.options.rpcUrl,{network:e.options.network}),a=N({chain:await SM({network:e.options.network,rpcUrl:i}),transport:L(i)});return{account:r,client:a}}async function lz(e,t){let n=e.request,r=n.currency,i=n.amount;if(typeof r!=`string`||typeof i!=`string`)return`unsupported`;let a=n.methodDetails,o=a?.chainId;if(o&&t.client.chain?.id&&o!==t.client.chain.id)return`unsupported`;let s=BigInt(i);if(s===0n)return`payable`;let c=await Be.token.getBalance(t.client,{account:t.account,token:r}).then(e=>e.amount).catch(()=>void 0);if(c===void 0)return`unknownBalance`;if(c>=s)return`payable`;if(a?.machineTokenEnabled===!0&&!a.splits?.length){let e=await JP(t.client,{account:t.account,chainId:o??t.client.chain?.id});if(e!==void 0&&e>=s)return`payable`}return`insufficientBalance`}function uz(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function dz(e){let t=e.challenge.request.methodDetails?.chainId;if(!t||!e.clientChainId||t===e.clientChainId)return;let n=t===4217?` Use --network mainnet or --rpc-url https://rpc.tempo.xyz.`:t===42431?` Use --network testnet or --rpc-url https://rpc.moderato.tempo.xyz.`:``;throw new B({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function fz(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function pz(e){let t=fz(e.tokenIn)??fz(e.payWith);if(!(!e.autoSwap&&!t&&e.slippage===void 0)){if(e.autoSwap===!1&&!t&&e.slippage===void 0)return!1;if(e.slippage!==void 0&&(!Number.isFinite(e.slippage)||e.slippage<0))throw Error(`Invalid CLI options (slippage: expected a non-negative number)`);return{...t?{tokenIn:t}:{},...e.slippage===void 0?{}:{slippage:e.slippage}}}}function mz(){return c.join(process.env.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`mppx`,`channels`)}function hz(e){try{let n=t.readFileSync(c.join(mz(),e),`utf-8`).trim();return n?BigInt(n):void 0}catch{return}}function gz(e,n){let r=mz();t.mkdirSync(r,{recursive:!0}),t.writeFileSync(c.join(r,e),n.toString(),`utf-8`)}function _z(e){try{t.unlinkSync(c.join(mz(),e))}catch{}}function vz(){return x.platform()===`darwin`?c.join(x.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):c.join(process.env.XDG_DATA_HOME||c.join(x.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function yz(){try{let e=t.readFileSync(vz(),`utf-8`),n=[],r;for(let t of e.split(`
247
- `)){let e=t.trim();if(e===`[[keys]]`){r?.wallet_address&&n.push(r),r={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!r)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?r.wallet_type=o:a===`wallet_address`?r.wallet_address=o:a===`chain_id`&&(r.chain_id=Number.parseInt(o,10))}return r?.wallet_address&&n.push(r),n}catch{return[]}}function bz(e){let t=yz();if(t.length===0)return;let n=e.slice(6);if(n==="default"||n===``)return t[0];let r=Number.parseInt(n,10);if(!Number.isNaN(r)&&r>=0&&r<t.length)return t[r]}function xz(){if(kz!==void 0)return kz;try{m.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),kz=!0}catch{kz=!1}return kz}async function Sz(e){return new Promise((t,n)=>{m.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function Cz(){let e=BM();if(gM(e.get())&&!xz()&&x.platform()===`darwin`)try{let t=m.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===wz&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}var wz,Tz,Ez,Dz,Oz,kz,Az=z((()=>{Rx(),DO(),Gx(),vC(),XR(),$P(),CA(),SI(),JM(),PM(),eP(),wz=`mppx`,Tz=p.union([p.boolean(),p.literal(`true`).transform(()=>!0),p.literal(`false`).transform(()=>!1)]),Ez=p.object({allowCustomEscrow:p.optional(Tz),autoSwap:p.optional(Tz),channel:p.optional(p.coerce.string()),deposit:p.optional(p.union([p.string(),p.number()])),payWith:p.optional(p.string()),slippage:p.optional(p.coerce.number()),tokenIn:p.optional(p.string())}),Dz=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`],Oz=[`payable`,`unknownBalance`,`insufficientBalance`,`unsupported`]}));ZC(),JM(),eP();const jz=[...Object.entries(iN),...Object.entries(aN),...Object.entries(oN),...Object.entries(sN)];function Mz(){return $N({method:`evm`,supports:Nz,async setup({challenge:e,options:t}){let n=e.request,r=n.network?Pz(gN(n.network)):void 0,i=n.network&&n.asset?jz.find(([,e])=>mN(e,n.asset,n.network)):void 0,a=n.extra?.name,o=n.extra?.version,s=n.asset&&n.network&&typeof a==`string`&&typeof o==`string`?nN({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await GM(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...QN({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function Nz(e){if(!YC(e))return!1;let t=e.request,n=t.extra,r=n?.assetTransferMethod;return t.scheme===`exact`&&typeof t.asset==`string`&&typeof t.network==`string`&&typeof n?.name==`string`&&typeof n?.version==`string`&&(r===void 0||r===`eip3009`)}function Pz(e){return Object.values(Qe).find(t=>t.id===e)}sC(),vw(),vk(),lS(),Az();const Fz=[ez(),uP(),tP(),Mz()];async function Iz(e,t,n){let r=n;for(let n of t??[]){let t=await n.preparePayment?.({challenge:e,...r===void 0?{}:{credentialContext:r}});t&&`credentialContext`in t&&(r=t.credentialContext)}return r}function Lz(e,t){let n=t?.plugins?.find(t=>Vz(t,e));if(n)return{plugin:n};let r=Bz(t)?.filter(t=>t.name===e.method&&t.intent===e.intent),i=r?.find(t=>t.canHandleChallenge?.({challenge:e})??!0);if(i)return{method:i};if(r?.length)return{};let a=Fz.find(t=>Vz(t,e));return a?{plugin:a}:{}}function Rz(e,t){let n=Bz(t);if(n?.length){let r=nw(e,n,$C(n,t?.paymentPreferences).entries);if(r){let e=t?.plugins?.find(e=>Vz(e,r.challenge));return{challenge:r.challenge,...e?{plugin:e}:{method:r.method}}}return}for(let n of e){let e=Lz(n,t);if(e.plugin||e.method)return{challenge:n,...e}}}function zz(e){let t=Bz(e);if(t?.length)return $C(t,e?.paymentPreferences).header}function Bz(e){return Array.isArray(e?.methods)?e.methods.flat():void 0}function Vz(e,t){return e.supports?e.supports(t):e.method===t.method}async function Hz(e){let t=Uz(e);if(!t)return;let n=await import(t);return{config:n.default??n,path:t}}function Uz(e){if(e){let n=c.resolve(e);return t.existsSync(n)?n:void 0}let n=process.env.MPPX_CONFIG?.trim();if(n){let e=c.resolve(n);return t.existsSync(e)?e:void 0}}function Wz(e,t){function n(t){let n={...t.request};if(t.method===`tempo`&&t.intent===`session`){let e={...n.methodDetails};delete e.sessionSnapshot,Object.keys(e).length?n.methodDetails=e:delete n.methodDetails}let{meta:r,opaque:i,...a}=t;return JSON.stringify([CS({...a,request:n,id:e.id,expires:e.expires}),Gz(t)])}if(n(t)!==n(e))throw Error(`Payment request changed on retry. Run the command again to approve the new payment.`)}function Gz(e){let t=e.opaque??(e.meta?cS(e.meta):void 0);if(t===void 0)return;let n;try{n=oS(t)}catch{return t}if(typeof n!=`object`||!n||Array.isArray(n))return t;let r=pk(n);return r?cS(r):void 0}Az(),sC(),bE(),HI(),cR(),vR(),Zj();function Kz(e){return e??globalThis.fetch.bind(globalThis)}function qz(e,t){let n=e.request.methodDetails?.chainId;if(n!==void 0&&n!==t.chainId)throw Error(`Close challenge changed the session chain.`);if(typeof e.request.recipient!=`string`||e.request.recipient.toLowerCase()!==t.descriptor.payee.toLowerCase())throw Error(`Close challenge changed the session payee.`);if(typeof e.request.currency!=`string`||e.request.currency.toLowerCase()!==t.descriptor.token.toLowerCase())throw Error(`Close challenge changed the session token.`);if(PI(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Error(`Close challenge changed the session escrow.`);let r=hj(e);if(r&&r.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Close challenge changed the session channel.`)}async function Jz(e){qz(e.challenge,e.channel);let t=e.channel;if(t.origin===void 0){let n=new URL(e.input instanceof Request?e.input.url:e.input);if(![`http:`,`https:`].includes(n.protocol))throw Error(`Legacy session close requires an HTTP origin`);gE(e.challenge,n,e.manager.trustedTempoProofRealms),t={...t,origin:n.origin}}let n=Kz(e.fetch),r,i=async(t,i)=>{r&&=(await e.onChallenge?.(r),void 0);let a=await n(t,i);if(a.status!==402)return a;let o=RS(a).find(pj);if(!o)throw Error(`Refreshed close response did not include tempo/session.`);return qz(o,e.channel),r=o,a},a=_R({...e.manager,bootstrap:!1,escrow:e.channel.escrow,fetch:i});oR(a).rehydrate({...e,channel:t}),t!==e.channel&&await e.manager.channelStore?.set(t);let o=await a.close();if(!o)throw Error(`Session close response did not include a payment receipt.`);return{manager:a,receipt:o}}sC(),HI(),tL(),Zj(),VF(),xS();var Yz=class extends Error{name=`SessionStateError`;code=`SESSION_STATE_INVALID`;file;constructor(e,t={}){super(e,t.cause===void 0?void 0:{cause:t.cause}),this.file=t.file}},Xz=class extends Error{name=`SessionBusyError`;code=`SESSION_BUSY`;exitCode=75;scope;owner;constructor(e,t){super(`Session scope is busy in process ${t.pid} on ${t.hostname}.`),this.scope=e,this.owner=t}};const Zz=Y.object({origin:Y.optional(Y.string()),channelId:_S(),cumulativeAmount:Y.string(),deposit:Y.string(),descriptor:Y.object({payer:gS(),payee:gS(),operator:gS(),token:gS(),salt:_S(),authorizedSigner:gS(),expiringNonceHash:_S()}),escrow:gS(),chainId:Y.number(),opened:Y.boolean()}),Qz=Y.object({name:Y.optional(Y.string()),address:gS()}),$z=Y.object({method:Y.literal(`tempo`),intent:Y.literal(`session`),status:Y.literal(`success`),timestamp:Y.string(),reference:Y.string(),challengeId:Y.string(),channelId:_S(),acceptedCumulative:Y.string(),spent:Y.string(),units:Y.optional(Y.number()),txHash:Y.optional(_S())}),eB=Y.object({version:Y.literal(1),method:Y.literal(`tempo`),intent:Y.literal(`session`),status:Y.enum([`opening`,`open`,`closing`,`stale`]),channel:Zz,account:Qz,endpoint:Y.string(),challenge:rC,receipt:Y.optional($z),spent:Y.string(),units:Y.number(),createdAt:Y.string(),updatedAt:Y.string()}),tB=Y.object({version:Y.literal(1),channelId:_S()}),nB=Y.object({version:Y.literal(1),scope:Y.string(),hostname:Y.string(),pid:Y.number(),token:Y.string(),createdAt:Y.string()});function rB(e,t,n,r){let i=e.safeParse(t);if(!i.success)throw Z(n,r,i.error);return i.data}function iB(e){let t=mB(e);return[t.payer,t.payee,t.token,t.escrow,t.chainId].join(`:`)}function aB(e){return{payer:e.descriptor.payer,payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId}}function oB(e={}){let t=e.stateRoot??cB(),n={root:t,channels:c.join(t,`channels`),locks:c.join(t,`locks`),preferred:c.join(t,`preferred`)},r=e.hostname??x.hostname(),i=e.pid??process.pid,a=e.now??(()=>new Date),o=e.isProcessAlive??BB;async function s(){for(let e of[n.root,n.channels,n.locks,n.preferred])await w.mkdir(e,{recursive:!0,mode:448}),await w.chmod(e,448)}async function l(e){let t=fB(e),r=lB(n,t),i=await jB(r);if(i===void 0)return;let a=SB(i,r);if(a.channel.channelId.toLowerCase()!==t)throw Z(r,`Session filename does not match its channel ID.`);return CB(a)}async function u(){let e;try{e=await w.readdir(n.channels,{withFileTypes:!0})}catch(e){if(HB(e,`ENOENT`))return[];throw Z(n.channels,`Unable to list managed sessions.`,e)}let t=[];for(let n of e){if(!n.isFile()||n.name.includes(`.tmp-`)||!n.name.endsWith(`.json`))continue;let e=n.name.slice(0,-5);fB(e);let r=await l(e);r&&t.push(r)}return t.sort((e,t)=>e.createdAt.localeCompare(t.createdAt))}async function d(e){await s();let t=vB(e.channel),r=fB(t.channelId),i=lB(n,r),o=await jB(i),c=o===void 0?void 0:SB(o,i);c&&wB(c,e,i);let l=c?.channel.origin??t.origin;if(c?.channel.origin&&t.origin&&c.channel.origin!==t.origin)throw Z(i,`Session payment origin mismatch.`);if(l!==void 0&&new URL(l).origin!==l)throw Z(i,`Session payment origin must be a normalized origin.`);let u=bB(e.challenge,i);EB(u,t,i);let d=e.receipt?xB(e.receipt,t.channelId,i):void 0,f=c?qI(c.channel):void 0,p=AB(t.cumulativeAmount,f?.cumulativeAmount??0n),m=AB(e.spent??0n,d?BigInt(d.spent):0n,c?BigInt(c.spent):0n);if(m>p)throw Z(i,`Session spend exceeds the locally authorized cumulative amount.`);let h=yB(KI({...t,cumulativeAmount:p,...l!==void 0&&{origin:l}}),i),g=kB(c?.updatedAt,a(),i),_=OB(c?.receipt,d),v=_B(e.account,i),y=SB({version:1,method:`tempo`,intent:`session`,status:e.status,channel:h,account:{...v.name===void 0?c?.account.name===void 0?{}:{name:c.account.name}:{name:v.name},address:v.address},endpoint:gB(e.endpoint,i),challenge:u,..._!==void 0&&{receipt:_},spent:m.toString(),units:Math.max(c?.units??0,e.units??0,d?.units??0),createdAt:c?.createdAt??g,updatedAt:g},i);return await MB(i,y),CB(y)}async function f(e){let t=dB(n,e),r=await jB(t);if(r===void 0)return;let{channelId:i}=rB(tB,r,t,`Preferred session is invalid.`),a=await l(i);if(!a)throw Z(t,`Preferred session ${i} does not exist.`);return DB(a.channel,e,t),i}async function p(e,t){let r=fB(t),i=await l(r),a=dB(n,e);if(!i)throw Z(a,`Session ${r} does not exist.`);DB(i.channel,e,a),await MB(a,{version:1,channelId:r})}async function m(e,t){let r=dB(n,e),i=t===void 0?void 0:fB(t),a=await jB(r);if(a===void 0)return;let o=rB(tB,a,r,`Preferred session is invalid.`).channelId;i&&o.toLowerCase()!==i||await RB(r,`Unable to clear preferred session.`)}async function h(e){let t=fB(e),r=await l(t);r&&(await m(aB(r.channel),t),await RB(lB(n,t),`Unable to remove session.`))}async function g(e){await s();let t=uB(n,e);for(let n=0;n<3;n++){let n={version:1,scope:e,hostname:r,pid:i,token:v(),createdAt:a().toISOString()};try{if(await NB(t,n),await IB(FB(t))){await LB(t,n);continue}return{async release(){await LB(t,n)}}}catch(e){if(!HB(e,`EEXIST`))throw e}let s=await jB(t);if(s===void 0)continue;let c=rB(nB,s,t,`Session lock is invalid.`);if(c.scope!==e)throw Z(t,`Session lock scope is invalid.`);if(c.hostname!==r||o(c.pid))throw new Xz(e,c);await PB(t,c)}let c=await jB(t);throw c===void 0?Z(t,`Unable to acquire session lock.`):new Xz(e,rB(nB,c,t,`Session lock is invalid.`))}async function _(e){return g(iB(e))}return{root:t,get:l,list:u,upsert:d,remove:h,getPreferred:f,setPreferred:p,clearPreferred:m,acquire:_}}function sB(e,t){let n=hB(t.scope),r=t.selection===`auto`||t.selection===`new`?void 0:fB(t.selection);function i(e){if(e.toLowerCase()!==n)throw new Yz(`Session manager requested an unexpected payment scope.`)}async function a(n=!0){if(t.selection===`new`&&!r)return;let i=r??await e.getPreferred(t.scope);if(!i)return;let a=await e.get(i);if(!a)throw new Yz(`Session ${i} does not exist.`);if(DB(a.channel,t.scope),!(n&&(a.status!==`open`||!a.channel.opened)))return r=i,a}return{async get(e){return i(e),(await a())?.channel},async set(n){if(i(WI(n)),DB(n,t.scope),r&&r.toLowerCase()!==n.channelId.toLowerCase())throw new Yz(`Session manager selected ${r}, but attempted to store ${n.channelId}.`);r||t.onNewChannel?.(n);let a=await e.upsert({...t.context(),channel:n});r=a.channel.channelId,await e.setPreferred(t.scope,a.channel.channelId)},async delete(n){i(n);let o=await a(!1);if(!o)return;let s=t.context();await e.upsert({...o,...s,status:s.status===`closing`?`closing`:`stale`,channel:o.channel,spent:s.spent??o.spent,units:s.units??o.units}),s.status!==`closing`&&await e.clearPreferred(t.scope,o.channel.channelId),r=void 0}}}function cB(){let e=process.env.XDG_STATE_HOME||c.join(x.homedir(),`.local`,`state`);return c.join(e,`mppx`,`sessions`,`v1`)}function lB(e,t){return c.join(e.channels,`${t}.json`)}function uB(e,t){let n=_(`sha256`).update(t).digest(`hex`);return c.join(e.locks,`${n}.lock`)}function dB(e,t){let n=_(`sha256`).update(iB(t)).digest(`hex`);return c.join(e.preferred,`${n}.json`)}function fB(e){return rB(_S(),e,void 0,`Invalid session channel ID: ${e}.`).toLowerCase()}function pB(e,t,n){return rB(gS(),e,n,`Invalid ${t}.`).toLowerCase()}function mB(e){if(!Number.isSafeInteger(e.chainId)||e.chainId<0)throw new Yz(`Invalid session chain ID.`);return{payer:pB(e.payer,`session payer`),payee:pB(e.payee,`session payee`),token:pB(e.token,`session token`),escrow:pB(e.escrow,`session escrow`),chainId:e.chainId}}function hB(e){let t=mB(e);return[t.payee,t.token,t.escrow,t.chainId].join(`:`)}function gB(e,t){if(typeof e!=`string`)throw Z(t,`Session endpoint is invalid.`);let n;try{n=new URL(e)}catch(e){throw Z(t,`Session endpoint is invalid.`,e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Z(t,`Session endpoint must use HTTP or HTTPS.`);if(n.username||n.password)throw Z(t,`Session endpoint must not contain credentials.`);let r=e.indexOf(`#`);return r===-1?e:e.slice(0,r)}function _B(e,t){return rB(Qz,e,t,`Session account is invalid.`)}function vB(e){return qI(yB(KI(e)))}function yB(e,t){return rB(Zz,e,t,`Stored session channel is invalid.`)}function bB(e,t){let n=rC.safeParse(e);if(!n.success||!pj(n.data))throw Z(t,`Stored session challenge is invalid.`);return n.data}function xB(e,t,n){let r=rB($z,e,n,`Stored session receipt is invalid.`);if(r.channelId!==t.toLowerCase())throw Z(n,`Stored session receipt has a different channel ID.`);if(r.reference.toLowerCase()!==t.toLowerCase())throw Z(n,`Stored session receipt has a different reference.`);if(BigInt(r.spent)>BigInt(r.acceptedCumulative))throw Z(n,`Stored session receipt spend exceeds its accepted amount.`);return r}function SB(e,t){let n=rB(eB,e,t,`Stored session is invalid.`),{receipt:r,...i}=n,a=n.channel,o=n.account;if(o.address.toLowerCase()!==a.descriptor.payer.toLowerCase())throw Z(t,`Stored session account does not match the channel payer.`);let s=r?xB(r,a.channelId,t):void 0,c=n.spent,l=BigInt(a.cumulativeAmount);if(BigInt(c)>l)throw Z(t,`Stored session spend exceeds its cumulative authorization.`);if(s&&BigInt(s.acceptedCumulative)>l)throw Z(t,`Stored receipt exceeds the cumulative authorization.`);if(Date.parse(n.updatedAt)<Date.parse(n.createdAt))throw Z(t,`Stored session timestamps are not monotonic.`);let u=gB(n.endpoint,t);if(u!==n.endpoint)throw Z(t,`Stored session endpoint contains a fragment.`);let d=bB(n.challenge,t);return EB(d,qI(a),t),{...i,account:o,channel:a,endpoint:u,challenge:d,...s&&{receipt:s}}}function CB(e){return{version:1,status:e.status,channel:qI(e.channel),account:e.account,endpoint:e.endpoint,challenge:e.challenge,...e.receipt&&{receipt:e.receipt},spent:BigInt(e.spent),units:e.units,createdAt:e.createdAt,updatedAt:e.updatedAt}}function wB(e,t,n){let r=vB(t.channel),i=_B(t.account,n),a=qI(e.channel);if(JSON.stringify(TB(r))!==JSON.stringify(TB(a)))throw Z(n,`Session update changed immutable channel identity.`);if(i.address.toLowerCase()!==e.account.address.toLowerCase())throw Z(n,`Session update changed the payer account.`)}function TB(e){return{channelId:e.channelId.toLowerCase(),descriptor:Object.fromEntries(Object.entries(e.descriptor).map(([e,t])=>[e,typeof t==`string`?t.toLowerCase():t])),escrow:e.escrow.toLowerCase(),chainId:e.chainId}}function EB(e,t,n){if(LF({...t.descriptor,chainId:t.chainId,escrow:t.escrow}).toLowerCase()!==t.channelId.toLowerCase())throw Z(n,`Session channel ID does not match its descriptor.`);let r=pB(e.request.recipient,`challenge recipient`,n),i=pB(e.request.currency,`challenge currency`,n);if(r!==t.descriptor.payee.toLowerCase())throw Z(n,`Session challenge payee does not match the channel.`);if(i!==t.descriptor.token.toLowerCase())throw Z(n,`Session challenge token does not match the channel.`);if(PI(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Z(n,`Session challenge escrow does not match the channel.`);if(VB(e.request.methodDetails)){let r=e.request.methodDetails;if(r.chainId!==void 0&&r.chainId!==t.chainId)throw Z(n,`Session challenge chain does not match the channel.`)}}function DB(e,t,n){let r=mB(t);if(e.descriptor.payer.toLowerCase()!==r.payer||e.descriptor.payee.toLowerCase()!==r.payee||e.descriptor.token.toLowerCase()!==r.token||e.escrow.toLowerCase()!==r.escrow||e.chainId!==r.chainId)throw Z(n,`Session channel does not match the selected payment scope.`)}function OB(e,t){return e?t&&Date.parse(t.timestamp)>=Date.parse(e.timestamp)?t:e:t}function kB(e,t,n){if(!Number.isFinite(t.getTime()))throw Z(n,`Session clock is invalid.`);let r=t.toISOString();return!e||Date.parse(r)>=Date.parse(e)?r:e}function AB(...e){return e.reduce((e,t)=>t>e?t:e,0n)}async function jB(e){let t;try{t=await w.readFile(e,`utf8`)}catch(t){if(HB(t,`ENOENT`))return;throw Z(e,`Unable to read session state.`,t)}try{return JSON.parse(t)}catch(t){throw Z(e,`Session state contains invalid JSON.`,t)}}async function MB(e,t){await w.mkdir(c.dirname(e),{recursive:!0,mode:448}),await w.chmod(c.dirname(e),448);let n=`${e}.tmp-${process.pid}-${v()}`,r;try{r=await w.open(n,`wx`,384),await r.writeFile(`${JSON.stringify(t,null,2)}\n`,`utf8`),await r.sync(),await r.close(),r=void 0,await w.rename(n,e),await w.chmod(e,384),await zB(c.dirname(e))}catch(t){throw await r?.close().catch(()=>void 0),await w.unlink(n).catch(()=>void 0),t instanceof Yz?t:Z(e,`Unable to write session state.`,t)}}async function NB(e,t){let n;try{n=await w.open(e,`wx`,384),await n.writeFile(`${JSON.stringify(t)}\n`,`utf8`),await n.sync(),await n.close(),n=void 0,await zB(c.dirname(e))}catch(t){throw await n?.close().catch(()=>void 0),n&&await w.unlink(e).catch(()=>void 0),t}}async function PB(e,t){let n=FB(e);try{await w.link(e,n)}catch(t){if(HB(t,`EEXIST`)||HB(t,`ENOENT`))return;throw Z(e,`Unable to claim dead lock.`,t)}try{let r=await jB(n);if(r===void 0||rB(nB,r,n,`Session lock is invalid.`).token!==t.token)return;await RB(e,`Unable to reclaim dead lock.`)}finally{await RB(n,`Unable to release dead lock claim.`)}}function FB(e){return`${e}.reclaim`}async function IB(e){try{return await w.access(e),!0}catch(t){if(HB(t,`ENOENT`))return!1;throw Z(e,`Unable to inspect session lock.`,t)}}async function LB(e,t){let n=await jB(e);n!==void 0&&rB(nB,n,e,`Session lock is invalid.`).token===t.token&&await RB(e,`Unable to release session lock.`)}async function RB(e,t){try{await w.unlink(e),await zB(c.dirname(e))}catch(n){if(!HB(n,`ENOENT`))throw Z(e,t,n)}}async function zB(e){let t=await w.open(e,`r`);try{await t.sync()}finally{await t.close()}}function BB(e){try{return process.kill(e,0),!0}catch(e){if(HB(e,`ESRCH`))return!1;if(HB(e,`EPERM`))return!0;throw e}}function VB(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function HB(e,t){return e instanceof Error&&`code`in e&&e.code===t}function Z(e,t,n){return new Yz(t,{...n!==void 0&&{cause:n},file:e})}Rx(),sC(),DO(),KL(),cL(),VF(),JM(),PM();const UB=p.object({status:p.enum([`opening`,`open`,`closing`,`stale`]),channelId:p.string(),account:p.string().optional(),payer:p.string(),payee:p.string(),authorizedSigner:p.string(),token:p.string(),escrow:p.string(),chainId:p.number(),cumulativeAmount:p.string(),confirmedSpend:p.string(),deposit:p.string(),units:p.number(),resourceUrl:p.string(),createdAt:p.string(),updatedAt:p.string()}),WB=p.object({channelId:p.string(),status:p.enum([`closed`,`already-closed`]),spent:p.string(),txHash:p.string().optional()}),GB=p.object({closed:p.array(WB),failed:p.array(p.object({channelId:p.string(),message:p.string()}))});function KB(e){return e===`mainnet`?ve.id:ye.id}function qB(e){if(e===ve.id)return`mainnet`;if(e===ye.id)return`testnet`}function JB(e){let t={};for(let n of e??[]){let e=n.indexOf(`:`);if(e===-1)throw new B({code:`INVALID_HEADER`,message:`Invalid header format: ${n}`,exitCode:2});t[n.slice(0,e).trim()]=n.slice(e+1).trim()}return t}function YB(e){return{status:e.status,channelId:e.channel.channelId,...e.account.name&&{account:e.account.name},payer:e.channel.descriptor.payer,payee:e.channel.descriptor.payee,authorizedSigner:e.channel.descriptor.authorizedSigner,token:e.channel.descriptor.token,escrow:e.channel.escrow,chainId:e.channel.chainId,cumulativeAmount:e.channel.cumulativeAmount.toString(),confirmedSpend:e.spent.toString(),deposit:e.channel.deposit.toString(),units:e.units,resourceUrl:e.endpoint,createdAt:e.createdAt,updatedAt:e.updatedAt}}function XB(e,t){throw e instanceof B?e:e instanceof Xz?new B({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e instanceof Yz?new B({code:e.code,message:e.message,exitCode:65,cause:e}):new B({code:t,message:e instanceof Error?e.message:String(e),exitCode:75,...e instanceof Error&&{cause:e}})}async function ZB(e,t){let n=await WM(t??e.account.name);if(!kL(n.account,e.channel.descriptor))throw new B({code:`SESSION_ACCOUNT_MISMATCH`,message:`Account ${n.account.address} cannot sign for session ${e.channel.channelId}.`,exitCode:2});return n}async function QB(e,t){if(t.network&&KB(t.network)!==e)throw new B({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, not ${t.network}.`,exitCode:2});let n=t.network??qB(e),r=bM(t.rpcUrl,{network:n}),i=await SM({network:n,rpcUrl:r});if(i.id!==e)throw new B({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, but RPC is chainId ${i.id}.`,exitCode:2});return N({chain:i,transport:L(r)})}const $B=vb(`sessions`,{description:`Manage persistent payment sessions (list, view, close)`}).command(`list`,{description:`List persistent payment sessions`,options:p.object({account:p.string().optional().describe(`Filter by account name`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Filter by Tempo network`)}),output:p.object({sessions:p.array(UB)}),alias:{account:`a`},async run(e){try{let t=(await oB().list()).filter(t=>!(e.options.account&&t.account.name!==e.options.account||e.options.network&&t.channel.chainId!==KB(e.options.network))).map(YB),n={sessions:t};if(e.format===`json`&&e.formatExplicit)return e.ok(n);t.length===0&&console.log(`No sessions.`);for(let[e,n]of t.entries())e>0&&console.log(``),eV(n);return}catch(e){return XB(e,`SESSION_LIST_FAILED`)}}}).command(`view`,{description:`View a persistent payment session`,args:p.object({channelId:p.string().describe(`Full session channel ID`)}),output:UB,async run(e){try{let t=await oB().get(e.args.channelId);if(!t)throw new B({code:`SESSION_NOT_FOUND`,message:`Session ${e.args.channelId} was not found.`,exitCode:2});let n=YB(t);if(e.format===`json`&&e.formatExplicit)return e.ok(n);eV(n);return}catch(e){return XB(e,`SESSION_VIEW_FAILED`)}}}).command(`close`,{description:`Cooperatively close persistent payment sessions`,usage:[{suffix:`<channel-id> [options]`},{suffix:`--all --yes [options]`}],args:p.object({channelId:p.string().optional().describe(`Full session channel ID`)}),options:p.object({account:p.string().optional().describe(`Account name`),all:p.boolean().optional().default(!1).describe(`Close every matching session`),header:p.array(p.string()).optional().describe(`Add close request header (repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`),url:p.string().optional().describe(`Override the stored resource URL`),yes:p.boolean().optional().default(!1).describe(`Confirm closing every session`)}),output:p.union([WB,GB]),alias:{account:`a`,header:`H`,rpcUrl:`r`},async run(e){if(e.options.all&&e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all, not both.`,exitCode:2});if(!e.options.all&&!e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all.`,exitCode:2});if(e.options.all&&!e.options.yes)return e.error({code:`CONFIRMATION_REQUIRED`,message:`Closing all sessions requires --yes.`,exitCode:2});if(e.options.all&&(e.options.header||e.options.rpcUrl||e.options.url))return e.error({code:`INVALID_SESSION_CLOSE`,message:`--header, --rpc-url, and --url only apply to a single session.`,exitCode:2});let t=oB();async function n(e,n={}){let r=await t.get(e);if(!r)throw new B({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let i=aB(r.channel),a=await t.acquire(i);try{let r=await t.get(e);if(!r)throw new B({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});if(KS(r.challenge))throw new B({code:`SESSION_STATE_INVALID`,message:`Stored session challenge selects a credential header other than Payment-Authorization.`,exitCode:65});let a=await ZB(r,n.account),o=await QB(r.channel.chainId,n);if(LF({...r.channel.descriptor,escrow:r.channel.escrow,chainId:r.channel.chainId}).toLowerCase()!==r.channel.channelId.toLowerCase())throw new B({code:`SESSION_STATE_INVALID`,message:`Stored descriptor does not derive the session channel ID.`,exitCode:65});if((await iL(o,r.channel.channelId,r.channel.escrow)).deposit===0n)return await t.remove(r.channel.channelId),{channelId:r.channel.channelId,status:`already-closed`,spent:r.spent.toString()};let s=gB(n.resourceUrl??r.endpoint),c={...a.source===`keychain`&&{name:a.accountName},address:a.account.address},l=(e=r.challenge)=>({status:`closing`,account:c,endpoint:s,challenge:e,...r.receipt&&{receipt:r.receipt},spent:r.spent,units:r.units}),u=await t.upsert({...l(),channel:r.channel}),d=JB(n.headers),f=u.challenge,p=await Jz({channel:u.channel,challenge:u.challenge,fetch:async(e,t)=>globalThis.fetch(e,{...t,headers:{...d,...OD(t?.headers)}}),input:s,spent:u.spent,async onChallenge(e){f=e,await t.upsert({...l(e),channel:u.channel})},manager:{account:a.account,client:o,channelStore:sB(t,{scope:i,selection:u.channel.channelId,context:()=>l(f)})}});return await t.remove(u.channel.channelId),{channelId:u.channel.channelId,status:`closed`,spent:p.receipt.spent,txHash:p.receipt.txHash}}finally{await a.release()}}try{if(e.options.all){let r=(await t.list()).filter(t=>(!e.options.account||t.account.name===e.options.account)&&(!e.options.network||t.channel.chainId===KB(e.options.network))),i=[],a=[];for(let t of r)try{i.push(await n(t.channel.channelId,{account:e.options.account,network:e.options.network}))}catch(e){a.push({channelId:t.channel.channelId,message:e instanceof Error?e.message:String(e)})}let o={closed:i,failed:a};if(a.length>0){for(let e of a)process.stderr.write(`${e.channelId}: ${e.message}\n`);process.exitCode=1}if(e.format===`json`&&e.formatExplicit)return e.ok(o);for(let e of i)console.log(`${e.channelId} ${e.status} ${e.spent}`);for(let e of a)console.log(`${e.channelId} failed ${e.message}`);return}let r=await n(e.args.channelId,{account:e.options.account,headers:e.options.header,network:e.options.network,resourceUrl:e.options.url,rpcUrl:e.options.rpcUrl});if(e.format===`json`&&e.formatExplicit)return e.ok(r);console.log(`${r.channelId} ${r.status} ${r.spent}`),r.txHash&&console.log(` transaction ${r.txHash}`);return}catch(e){return XB(e,`SESSION_CLOSE_FAILED`)}}});function eV(e){console.log(e.channelId),console.log(` status ${e.status}`),console.log(` cumulative amount ${e.cumulativeAmount}`),console.log(` confirmed spend ${e.confirmedSpend}`),console.log(` deposit ${e.deposit}`),console.log(` chain ${e.chainId}`),console.log(` payer ${e.payer}`),console.log(` payee ${e.payee}`),console.log(` token ${e.token}`),console.log(` resource ${e.resourceUrl}`)}Rx(),KL(),cR(),vR(),CA(),JM(),PM();function tV(e,t){if(t&&e!==`auto`&&t.toLowerCase()!==e.toLowerCase())throw new B({code:`SESSION_SELECTION_CONFLICT`,message:`--session and -M channel= select different sessions.`,exitCode:2});let n=t??e;if(n===`auto`||n===`new`)return n;if(/^0x[0-9a-fA-F]{64}$/.test(n))return n.toLowerCase();throw new B({code:`INVALID_SESSION`,message:`Session must be auto, new, or a 32-byte channel ID.`,exitCode:2})}function nV(e){let t=e.allowCustomEscrow;if(t!==void 0){if(t===`true`)return!0;if(t===`false`)return!1;throw new B({code:`INVALID_ALLOW_CUSTOM_ESCROW`,message:`allowCustomEscrow must be true or false.`,exitCode:2})}}function rV(e,t,n,r){if(t.deposit!==void 0)return t.deposit;let i=e.request.suggestedDeposit;return typeof i==`string`?oe(BigInt(i),r):n?`10`:void 0}function iV(e,t){if(!e)return;if(e.challengeId!==t.challenge.id)throw Error(`Session receipt challenge does not match the paid request.`);if(e.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Session receipt channel does not match the selected channel.`);let n=BigInt(e.acceptedCumulative),r=BigInt(e.spent);if(n>t.cumulative)throw Error(`Session receipt exceeds the local cumulative authorization.`);if(r>n)throw Error(`Session receipt spend exceeds its accepted authorization.`);return e}function aV(e,t){return e.channel.channelId.toLowerCase()===t.toLowerCase()}function oV(e){if(e.trim()!==`[DONE]`){if(e.length===0){process.stdout.write(`
248
- `);return}try{let t=JSON.parse(e);process.stdout.write(t.token??t.choices?.[0]?.delta?.content??e)}catch{process.stdout.write(e)}}}async function sV(e){let{options:t}=e,n=await WM(t.account),r=bM(t.rpcUrl,{network:t.network}),i=await SM({network:t.network,rpcUrl:r}),a=N({chain:i,transport:L(r)}),o=nV(e.methodOptions),s=await CL({allowCustomEscrow:o,challenge:e.challenge,getClient:async()=>a});if(s.chainId!==i.id)throw new B({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${s.chainId}, but RPC is chainId ${i.id}.`,exitCode:2});let{decimals:c}=await EM(a,s.token,n.account.address,{requireDecimals:!0}),l={payer:n.account.address,payee:s.payee,token:s.token,escrow:s.escrow,chainId:s.chainId},u=tV(t.session,e.methodOptions.channel),d=e.registry??oB(),f=await d.acquire(l).catch(e=>{throw e instanceof Xz?new B({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e});try{let r=u===`auto`?await d.getPreferred(l):u===`new`?void 0:u,s=r?await d.get(r):void 0;if(r&&!s)throw new B({code:`SESSION_NOT_FOUND`,message:`Session ${r} was not found.`,exitCode:2});if(s&&u!==`auto`&&(s.status!==`open`||!s.channel.opened||iB(aB(s.channel))!==iB(l)||!kL(n.account,s.channel.descriptor)))throw new B({code:`SESSION_MISMATCH`,message:`Session ${s.channel.channelId} cannot be used for this account and challenge.`,exitCode:2});let f=s?.status===`open`&&s.channel.opened?s:void 0,p=f?`open`:`opening`,m=e.challenge,h=f?.receipt,g=f?.spent??0n,_=f?.units??0,v=gB(e.endpoint),y={...n.source===`keychain`&&{name:n.accountName},address:n.account.address},b=sB(d,{scope:l,selection:u,context:()=>({status:p,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),onNewChannel(){p=`opening`,h=void 0,g=0n,_=0}}),{signal:x,...S}=e.init,C={...S,...x&&{signal:x},onReceipt(e){h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0)}};if(e.challengeResponse.status!==402||e.challengeResponse.bodyUsed)throw Error(`Session manager requires an unconsumed 402 challenge response.`);let w=!0,T=_R({account:n.account,allowCustomEscrow:o,bootstrap:!1,client:a,channelStore:b,credentialContext:e.credentialContext,decimals:c,maxDeposit:rV(e.challenge,e.methodOptions,TM(i),c),fetch:async(t,n)=>w?(w=!1,e.challengeResponse):e.fetch(t,n)});f&&oR(T).rehydrate({channel:f.channel,challenge:e.challenge,input:e.fetchInput,spent:f.spent});let{onReceipt:E,...ee}=C,D=await T.fetch(e.fetchInput,ee);if(t.fail&&D.status>=400)throw new B({code:`HTTP_ERROR`,message:`HTTP error ${D.status}`,exitCode:22});if(D.status===402)throw new B({code:`PAYMENT_REJECTED`,message:`Payment rejected.`,exitCode:75});cM(D,{include:!1,verbose:t.include?Math.max(t.verbose,2):t.verbose,silent:t.silent}),m=D.challenge??e.challenge;let O=T.channelId;if(!O)throw Error(`Session manager did not select a channel.`);if(h=iV(D.receipt,{challenge:m,channelId:O,cumulative:T.cumulative})??h,pA(D)){let t=oR(T).consumeSseResponse(e.fetchInput,D,{onReceipt:E,signal:e.init.signal??void 0});for await(let e of t)oV(e)}else process.stdout.write(Buffer.from(await D.arrayBuffer()));let k=await d.get(O);if(!k||!aV(k,O))throw Error(`Session ${O} was not persisted.`);if(h){let e=iV(h,{challenge:m,channelId:O,cumulative:T.cumulative});if(!e)throw Error(`Session receipt validation failed.`);h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0),p=`open`}await d.upsert({status:p,channel:k.channel,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),t.silent||(e.info(`Session retained ${O}\n`),e.info(`Close with: mppx sessions close ${O}\n`))}finally{await f.release()}}const cV=`StripeCLI`;function lV(e){let t=e.env??process.env,n=e.secretKey?.trim();if(n)return{key:n,source:`flag`};let r=t.STRIPE_SECRET_KEY?.trim();if(r)return{key:r,source:`env`};let i=uV(e);if(i)return{key:i,source:`stripe-cli`}}function uV(e){let t=e.env??process.env,n=c.join(t.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`stripe`),r=e.projectName||t.STRIPE_PROJECT_NAME||`default`,i=mV(c.join(n,`config.toml`),r);if(!e.live)return i.test_mode_api_key||i.secret_key||i.api_key||void 0;let a=i.live_mode_api_key;if(a&&!a.includes(`*`))return a;let o=`${r}.live_mode_api_key`,s=pV(c.join(n,`credentials.json`))?.[o];return typeof s==`string`&&s?s:dV(o,e)}function dV(e,t){let n=t.platform??process.platform,r=t.exec??fV,i=(()=>{if(n===`darwin`)return[`security`,[`find-generic-password`,`-s`,cV,`-a`,e,`-w`]];if(n===`linux`)return[`secret-tool`,[`lookup`,`service`,cV,`username`,e]]})();if(i)try{let e=r(i[0],i[1]).trim();return e.startsWith(`go-keyring-base64:`)?Buffer.from(e.slice(18),`base64`).toString(`utf8`)||void 0:e||void 0}catch{return}}function fV(e,t){return g(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:3e3})}function pV(e){try{return JSON.parse(t.readFileSync(e,`utf8`))}catch{return}}function mV(e,n){let r;try{r=t.readFileSync(e,`utf8`)}catch{return{}}let i=new Set([n,`profiles.${n}`]),a={},o;for(let e of r.split(/\r?\n/)){let t=e.trim();if(!t||t.startsWith(`#`))continue;let n=/^\[\s*([^\]]+?)\s*\]$/.exec(t);if(n){o=n[1].replace(/["']/g,``).replace(/\s*\.\s*/g,`.`);continue}if(!o||!i.has(o))continue;let r=/^([A-Za-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)')/.exec(t);r&&(a[r[1]]=r[2]===void 0?r[3]:r[2].replace(/\\(.)/g,`$1`))}return a}function hV(e,t){return typeof t==`string`?e===`solana`?gV(t)===32:/^0x[0-9a-fA-F]{40}$/.test(t):!1}function gV(e){if(!/^[1-9A-HJ-NP-Za-km-z]{1,64}$/.test(e))return;let t=0n;for(let n of e)t=t*58n+BigInt(`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`.indexOf(n));let n=/^1*/.exec(e)[0].length,r=t===0n?``:t.toString(16);return n+Math.ceil(r.length/2)}function _V(e,n,r){if(/[\r\n]/.test(n)||/[\r\n]/.test(r))throw Error(`env values cannot contain line breaks`);let i=`${n}=${r}`;if(!t.existsSync(e))return t.writeFileSync(e,`${i}\n`,{mode:384});let a=t.readFileSync(e,`utf8`),o=RegExp(`^\\s*(?:export\\s+)?${n}\\s*=`),{lines:s,found:c}=vV(a.split(`
246
+ `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await az({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId,fetchUrl:t.fetchUrl,fetchInit:t.fetchInit,session:t.session,info:t.info,verbose:t.verbose,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,confirmEnabled:!1})}async function az(e){let t=await e.session.signVoucher({channelId:e.channelId,cumulativeAmount:e.cumulativeAmount,escrowContract:e.escrowContract,chainId:e.chainId,action:`close`}),n=await globalThis.fetch(e.fetchUrl,{...e.fetchInit,headers:{...OD(e.fetchInit.headers),Authorization:t}});if(n.ok){if(vz(e.channelId),e.verbose>=1){let t=n.headers.get(q.paymentReceipt),r;if(t)try{let e=JSON.parse(te.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${X.dim(pM(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${X.dim(`Channel closed.`)} ${X.dim(`Spent ${yM(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${X.dim(X.yellow(`Channel close failed`))} ${X.dim(`(${n.status})`)}\n`),e.info(`${X.dim(` channelId: ${e.channelId}`)}\n${X.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${X.dim(` escrowContract: ${e.escrowContract}`)}\n${X.dim(` chainId: ${e.chainId}`)}\n${X.dim(` response: ${t||`(empty)`}`)}\n`)}}function oz(e=100){return!process.stdin.isTTY||!process.stdout.isTTY?Promise.resolve(void 0):new Promise(t=>{let n=process.stdin.isRaw,r=``,i=()=>{clearTimeout(a),process.stdin.removeListener(`data`,o),process.stdin.isTTY&&process.stdin.setRawMode(n??!1),process.stdin.pause()},a=setTimeout(()=>{i(),t(void 0)},e),o=e=>{r+=e.toString();let n=r.match(/\x1b\]11;rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!n)return;i();let a=e=>Number.parseInt(e.slice(0,2),16);t({r:a(n[1]),g:a(n[2]),b:a(n[3])})};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on(`data`,o),process.stdout.write(`\x1B]11;?\x07`)})}function sz(e){return dz(Dz,e,Oz)}function cz(e){return e.method===`tempo`&&e.intent===`charge`}async function lz(e){let t=HM(e.options.account),n=process.env.MPPX_PRIVATE_KEY?.trim()||(gM(t)?void 0:await UM(t).get()),r;if(n)r=R(n).address;else if(gM(t)&&Sz())r=xz(t)?.wallet_address;else{let e=wz();if(e){let t=await UM(e).get();t&&(r=R(t).address)}}if(!r)return;let i=bM(e.options.rpcUrl,{network:e.options.network}),a=N({chain:await SM({network:e.options.network,rpcUrl:i}),transport:L(i)});return{account:r,client:a}}async function uz(e,t){let n=e.request,r=n.currency,i=n.amount;if(typeof r!=`string`||typeof i!=`string`)return`unsupported`;let a=n.methodDetails,o=a?.chainId;if(o&&t.client.chain?.id&&o!==t.client.chain.id)return`unsupported`;let s=BigInt(i);if(s===0n)return`payable`;let c=await Be.token.getBalance(t.client,{account:t.account,token:r}).then(e=>e.amount).catch(()=>void 0);if(c===void 0)return`unknownBalance`;if(c>=s)return`payable`;if(a?.machineTokenEnabled===!0&&!a.splits?.length){let e=await YP(t.client,{account:t.account,chainId:o??t.client.chain?.id});if(e!==void 0&&e>=s)return`payable`}return`insufficientBalance`}function dz(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function fz(e){let t=e.challenge.request.methodDetails?.chainId;if(!t||!e.clientChainId||t===e.clientChainId)return;let n=t===4217?` Use --network mainnet or --rpc-url https://rpc.tempo.xyz.`:t===42431?` Use --network testnet or --rpc-url https://rpc.moderato.tempo.xyz.`:``;throw new B({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function pz(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function mz(e){let t=pz(e.tokenIn)??pz(e.payWith);if(!(!e.autoSwap&&!t&&e.slippage===void 0)){if(e.autoSwap===!1&&!t&&e.slippage===void 0)return!1;if(e.slippage!==void 0&&(!Number.isFinite(e.slippage)||e.slippage<0))throw Error(`Invalid CLI options (slippage: expected a non-negative number)`);return{...t?{tokenIn:t}:{},...e.slippage===void 0?{}:{slippage:e.slippage}}}}function hz(){return c.join(process.env.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`mppx`,`channels`)}function gz(e){try{let n=t.readFileSync(c.join(hz(),e),`utf-8`).trim();return n?BigInt(n):void 0}catch{return}}function _z(e,n){let r=hz();t.mkdirSync(r,{recursive:!0}),t.writeFileSync(c.join(r,e),n.toString(),`utf-8`)}function vz(e){try{t.unlinkSync(c.join(hz(),e))}catch{}}function yz(){return x.platform()===`darwin`?c.join(x.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):c.join(process.env.XDG_DATA_HOME||c.join(x.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function bz(){try{let e=t.readFileSync(yz(),`utf-8`),n=[],r;for(let t of e.split(`
247
+ `)){let e=t.trim();if(e===`[[keys]]`){r?.wallet_address&&n.push(r),r={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!r)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?r.wallet_type=o:a===`wallet_address`?r.wallet_address=o:a===`chain_id`&&(r.chain_id=Number.parseInt(o,10))}return r?.wallet_address&&n.push(r),n}catch{return[]}}function xz(e){let t=bz();if(t.length===0)return;let n=e.slice(6);if(n==="default"||n===``)return t[0];let r=Number.parseInt(n,10);if(!Number.isNaN(r)&&r>=0&&r<t.length)return t[r]}function Sz(){if(Az!==void 0)return Az;try{m.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),Az=!0}catch{Az=!1}return Az}async function Cz(e){return new Promise((t,n)=>{m.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function wz(){let e=VM();if(gM(e.get())&&!Sz()&&x.platform()===`darwin`)try{let t=m.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===Tz&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}var Tz,Ez,Dz,Oz,kz,Az,jz=z((()=>{Rx(),DO(),Gx(),vC(),ZR(),eF(),CA(),CI(),YM(),PM(),tP(),Tz=`mppx`,Ez=p.union([p.boolean(),p.literal(`true`).transform(()=>!0),p.literal(`false`).transform(()=>!1)]),Dz=p.object({allowCustomEscrow:p.optional(Ez),autoSwap:p.optional(Ez),channel:p.optional(p.coerce.string()),deposit:p.optional(p.union([p.string(),p.number()])),payWith:p.optional(p.string()),slippage:p.optional(p.coerce.number()),tokenIn:p.optional(p.string())}),Oz=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`],kz=[`payable`,`unknownBalance`,`insufficientBalance`,`unsupported`]}));ZC(),YM(),tP();const Mz=[...Object.entries(aN),...Object.entries(oN),...Object.entries(sN),...Object.entries(cN)];function Nz(){return eP({method:`evm`,supports:Pz,async setup({challenge:e,options:t}){let n=e.request,r=n.network?Fz(_N(n.network)):void 0,i=n.network&&n.asset?Mz.find(([,e])=>hN(e,n.asset,n.network)):void 0,a=n.extra?.name,o=n.extra?.version,s=n.asset&&n.network&&typeof a==`string`&&typeof o==`string`?rN({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await KM(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...$N({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function Pz(e){if(!YC(e))return!1;let t=e.request,n=t.extra,r=n?.assetTransferMethod;return t.scheme===`exact`&&typeof t.asset==`string`&&typeof t.network==`string`&&typeof n?.name==`string`&&typeof n?.version==`string`&&(r===void 0||r===`eip3009`)}function Fz(e){return Object.values(Qe).find(t=>t.id===e)}sC(),vw(),vk(),lS(),jz();const Iz=[tz(),dP(),nP(),Nz()];async function Lz(e,t,n){let r=n;for(let n of t??[]){let t=await n.preparePayment?.({challenge:e,...r===void 0?{}:{credentialContext:r}});t&&`credentialContext`in t&&(r=t.credentialContext)}return r}function Rz(e,t){let n=t?.plugins?.find(t=>Hz(t,e));if(n)return{plugin:n};let r=Vz(t)?.filter(t=>t.name===e.method&&t.intent===e.intent),i=r?.find(t=>t.canHandleChallenge?.({challenge:e})??!0);if(i)return{method:i};if(r?.length)return{};let a=Iz.find(t=>Hz(t,e));return a?{plugin:a}:{}}function zz(e,t){let n=Vz(t);if(n?.length){let r=nw(e,n,$C(n,t?.paymentPreferences).entries);if(r){let e=t?.plugins?.find(e=>Hz(e,r.challenge));return{challenge:r.challenge,...e?{plugin:e}:{method:r.method}}}return}for(let n of e){let e=Rz(n,t);if(e.plugin||e.method)return{challenge:n,...e}}}function Bz(e){let t=Vz(e);if(t?.length)return $C(t,e?.paymentPreferences).header}function Vz(e){return Array.isArray(e?.methods)?e.methods.flat():void 0}function Hz(e,t){return e.supports?e.supports(t):e.method===t.method}async function Uz(e){let t=Wz(e);if(!t)return;let n=await import(t);return{config:n.default??n,path:t}}function Wz(e){if(e){let n=c.resolve(e);return t.existsSync(n)?n:void 0}let n=process.env.MPPX_CONFIG?.trim();if(n){let e=c.resolve(n);return t.existsSync(e)?e:void 0}}function Gz(e,t){function n(t){let n={...t.request};if(t.method===`tempo`&&t.intent===`session`){let e={...n.methodDetails};delete e.sessionSnapshot,Object.keys(e).length?n.methodDetails=e:delete n.methodDetails}let{meta:r,opaque:i,...a}=t;return JSON.stringify([CS({...a,request:n,id:e.id,expires:e.expires}),Kz(t)])}if(n(t)!==n(e))throw Error(`Payment request changed on retry. Run the command again to approve the new payment.`)}function Kz(e){let t=e.opaque??(e.meta?cS(e.meta):void 0);if(t===void 0)return;let n;try{n=oS(t)}catch{return t}if(typeof n!=`object`||!n||Array.isArray(n))return t;let r=pk(n);return r?cS(r):void 0}jz(),sC(),bE(),UI(),lR(),yR(),Zj();function qz(e){return e??globalThis.fetch.bind(globalThis)}function Jz(e,t){let n=e.request.methodDetails?.chainId;if(n!==void 0&&n!==t.chainId)throw Error(`Close challenge changed the session chain.`);if(typeof e.request.recipient!=`string`||e.request.recipient.toLowerCase()!==t.descriptor.payee.toLowerCase())throw Error(`Close challenge changed the session payee.`);if(typeof e.request.currency!=`string`||e.request.currency.toLowerCase()!==t.descriptor.token.toLowerCase())throw Error(`Close challenge changed the session token.`);if(FI(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Error(`Close challenge changed the session escrow.`);let r=hj(e);if(r&&r.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Close challenge changed the session channel.`)}async function Yz(e){Jz(e.challenge,e.channel);let t=e.channel;if(t.origin===void 0){let n=new URL(e.input instanceof Request?e.input.url:e.input);if(![`http:`,`https:`].includes(n.protocol))throw Error(`Legacy session close requires an HTTP origin`);gE(e.challenge,n,e.manager.trustedTempoProofRealms),t={...t,origin:n.origin}}let n=qz(e.fetch),r,i=async(t,i)=>{r&&=(await e.onChallenge?.(r),void 0);let a=await n(t,i);if(a.status!==402)return a;let o=RS(a).find(pj);if(!o)throw Error(`Refreshed close response did not include tempo/session.`);return Jz(o,e.channel),r=o,a},a=vR({...e.manager,bootstrap:!1,escrow:e.channel.escrow,fetch:i});sR(a).rehydrate({...e,channel:t}),t!==e.channel&&await e.manager.channelStore?.set(t);let o=await a.close();if(!o)throw Error(`Session close response did not include a payment receipt.`);return{manager:a,receipt:o}}sC(),UI(),nL(),Zj(),HF(),xS();var Xz=class extends Error{name=`SessionStateError`;code=`SESSION_STATE_INVALID`;file;constructor(e,t={}){super(e,t.cause===void 0?void 0:{cause:t.cause}),this.file=t.file}},Zz=class extends Error{name=`SessionBusyError`;code=`SESSION_BUSY`;exitCode=75;scope;owner;constructor(e,t){super(`Session scope is busy in process ${t.pid} on ${t.hostname}.`),this.scope=e,this.owner=t}};const Qz=Y.object({origin:Y.optional(Y.string()),channelId:_S(),cumulativeAmount:Y.string(),deposit:Y.string(),descriptor:Y.object({payer:gS(),payee:gS(),operator:gS(),token:gS(),salt:_S(),authorizedSigner:gS(),expiringNonceHash:_S()}),escrow:gS(),chainId:Y.number(),opened:Y.boolean()}),$z=Y.object({name:Y.optional(Y.string()),address:gS()}),eB=Y.object({method:Y.literal(`tempo`),intent:Y.literal(`session`),status:Y.literal(`success`),timestamp:Y.string(),reference:Y.string(),challengeId:Y.string(),channelId:_S(),acceptedCumulative:Y.string(),spent:Y.string(),units:Y.optional(Y.number()),txHash:Y.optional(_S())}),tB=Y.object({version:Y.literal(1),method:Y.literal(`tempo`),intent:Y.literal(`session`),status:Y.enum([`opening`,`open`,`closing`,`stale`]),channel:Qz,account:$z,endpoint:Y.string(),challenge:rC,receipt:Y.optional(eB),spent:Y.string(),units:Y.number(),createdAt:Y.string(),updatedAt:Y.string()}),nB=Y.object({version:Y.literal(1),channelId:_S()}),rB=Y.object({version:Y.literal(1),scope:Y.string(),hostname:Y.string(),pid:Y.number(),token:Y.string(),createdAt:Y.string()});function iB(e,t,n,r){let i=e.safeParse(t);if(!i.success)throw Z(n,r,i.error);return i.data}function aB(e){let t=hB(e);return[t.payer,t.payee,t.token,t.escrow,t.chainId].join(`:`)}function oB(e){return{payer:e.descriptor.payer,payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId}}function sB(e={}){let t=e.stateRoot??lB(),n={root:t,channels:c.join(t,`channels`),locks:c.join(t,`locks`),preferred:c.join(t,`preferred`)},r=e.hostname??x.hostname(),i=e.pid??process.pid,a=e.now??(()=>new Date),o=e.isProcessAlive??VB;async function s(){for(let e of[n.root,n.channels,n.locks,n.preferred])await w.mkdir(e,{recursive:!0,mode:448}),await w.chmod(e,448)}async function l(e){let t=pB(e),r=uB(n,t),i=await MB(r);if(i===void 0)return;let a=CB(i,r);if(a.channel.channelId.toLowerCase()!==t)throw Z(r,`Session filename does not match its channel ID.`);return wB(a)}async function u(){let e;try{e=await w.readdir(n.channels,{withFileTypes:!0})}catch(e){if(UB(e,`ENOENT`))return[];throw Z(n.channels,`Unable to list managed sessions.`,e)}let t=[];for(let n of e){if(!n.isFile()||n.name.includes(`.tmp-`)||!n.name.endsWith(`.json`))continue;let e=n.name.slice(0,-5);pB(e);let r=await l(e);r&&t.push(r)}return t.sort((e,t)=>e.createdAt.localeCompare(t.createdAt))}async function d(e){await s();let t=yB(e.channel),r=pB(t.channelId),i=uB(n,r),o=await MB(i),c=o===void 0?void 0:CB(o,i);c&&TB(c,e,i);let l=c?.channel.origin??t.origin;if(c?.channel.origin&&t.origin&&c.channel.origin!==t.origin)throw Z(i,`Session payment origin mismatch.`);if(l!==void 0&&new URL(l).origin!==l)throw Z(i,`Session payment origin must be a normalized origin.`);let u=xB(e.challenge,i);DB(u,t,i);let d=e.receipt?SB(e.receipt,t.channelId,i):void 0,f=c?JI(c.channel):void 0,p=jB(t.cumulativeAmount,f?.cumulativeAmount??0n),m=jB(e.spent??0n,d?BigInt(d.spent):0n,c?BigInt(c.spent):0n);if(m>p)throw Z(i,`Session spend exceeds the locally authorized cumulative amount.`);let h=bB(qI({...t,cumulativeAmount:p,...l!==void 0&&{origin:l}}),i),g=AB(c?.updatedAt,a(),i),_=kB(c?.receipt,d),v=vB(e.account,i),y=CB({version:1,method:`tempo`,intent:`session`,status:e.status,channel:h,account:{...v.name===void 0?c?.account.name===void 0?{}:{name:c.account.name}:{name:v.name},address:v.address},endpoint:_B(e.endpoint,i),challenge:u,..._!==void 0&&{receipt:_},spent:m.toString(),units:Math.max(c?.units??0,e.units??0,d?.units??0),createdAt:c?.createdAt??g,updatedAt:g},i);return await NB(i,y),wB(y)}async function f(e){let t=fB(n,e),r=await MB(t);if(r===void 0)return;let{channelId:i}=iB(nB,r,t,`Preferred session is invalid.`),a=await l(i);if(!a)throw Z(t,`Preferred session ${i} does not exist.`);return OB(a.channel,e,t),i}async function p(e,t){let r=pB(t),i=await l(r),a=fB(n,e);if(!i)throw Z(a,`Session ${r} does not exist.`);OB(i.channel,e,a),await NB(a,{version:1,channelId:r})}async function m(e,t){let r=fB(n,e),i=t===void 0?void 0:pB(t),a=await MB(r);if(a===void 0)return;let o=iB(nB,a,r,`Preferred session is invalid.`).channelId;i&&o.toLowerCase()!==i||await zB(r,`Unable to clear preferred session.`)}async function h(e){let t=pB(e),r=await l(t);r&&(await m(oB(r.channel),t),await zB(uB(n,t),`Unable to remove session.`))}async function g(e){await s();let t=dB(n,e);for(let n=0;n<3;n++){let n={version:1,scope:e,hostname:r,pid:i,token:v(),createdAt:a().toISOString()};try{if(await PB(t,n),await LB(IB(t))){await RB(t,n);continue}return{async release(){await RB(t,n)}}}catch(e){if(!UB(e,`EEXIST`))throw e}let s=await MB(t);if(s===void 0)continue;let c=iB(rB,s,t,`Session lock is invalid.`);if(c.scope!==e)throw Z(t,`Session lock scope is invalid.`);if(c.hostname!==r||o(c.pid))throw new Zz(e,c);await FB(t,c)}let c=await MB(t);throw c===void 0?Z(t,`Unable to acquire session lock.`):new Zz(e,iB(rB,c,t,`Session lock is invalid.`))}async function _(e){return g(aB(e))}return{root:t,get:l,list:u,upsert:d,remove:h,getPreferred:f,setPreferred:p,clearPreferred:m,acquire:_}}function cB(e,t){let n=gB(t.scope),r=t.selection===`auto`||t.selection===`new`?void 0:pB(t.selection);function i(e){if(e.toLowerCase()!==n)throw new Xz(`Session manager requested an unexpected payment scope.`)}async function a(n=!0){if(t.selection===`new`&&!r)return;let i=r??await e.getPreferred(t.scope);if(!i)return;let a=await e.get(i);if(!a)throw new Xz(`Session ${i} does not exist.`);if(OB(a.channel,t.scope),!(n&&(a.status!==`open`||!a.channel.opened)))return r=i,a}return{async get(e){return i(e),(await a())?.channel},async set(n){if(i(GI(n)),OB(n,t.scope),r&&r.toLowerCase()!==n.channelId.toLowerCase())throw new Xz(`Session manager selected ${r}, but attempted to store ${n.channelId}.`);r||t.onNewChannel?.(n);let a=await e.upsert({...t.context(),channel:n});r=a.channel.channelId,await e.setPreferred(t.scope,a.channel.channelId)},async delete(n){i(n);let o=await a(!1);if(!o)return;let s=t.context();await e.upsert({...o,...s,status:s.status===`closing`?`closing`:`stale`,channel:o.channel,spent:s.spent??o.spent,units:s.units??o.units}),s.status!==`closing`&&await e.clearPreferred(t.scope,o.channel.channelId),r=void 0}}}function lB(){let e=process.env.XDG_STATE_HOME||c.join(x.homedir(),`.local`,`state`);return c.join(e,`mppx`,`sessions`,`v1`)}function uB(e,t){return c.join(e.channels,`${t}.json`)}function dB(e,t){let n=_(`sha256`).update(t).digest(`hex`);return c.join(e.locks,`${n}.lock`)}function fB(e,t){let n=_(`sha256`).update(aB(t)).digest(`hex`);return c.join(e.preferred,`${n}.json`)}function pB(e){return iB(_S(),e,void 0,`Invalid session channel ID: ${e}.`).toLowerCase()}function mB(e,t,n){return iB(gS(),e,n,`Invalid ${t}.`).toLowerCase()}function hB(e){if(!Number.isSafeInteger(e.chainId)||e.chainId<0)throw new Xz(`Invalid session chain ID.`);return{payer:mB(e.payer,`session payer`),payee:mB(e.payee,`session payee`),token:mB(e.token,`session token`),escrow:mB(e.escrow,`session escrow`),chainId:e.chainId}}function gB(e){let t=hB(e);return[t.payee,t.token,t.escrow,t.chainId].join(`:`)}function _B(e,t){if(typeof e!=`string`)throw Z(t,`Session endpoint is invalid.`);let n;try{n=new URL(e)}catch(e){throw Z(t,`Session endpoint is invalid.`,e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Z(t,`Session endpoint must use HTTP or HTTPS.`);if(n.username||n.password)throw Z(t,`Session endpoint must not contain credentials.`);let r=e.indexOf(`#`);return r===-1?e:e.slice(0,r)}function vB(e,t){return iB($z,e,t,`Session account is invalid.`)}function yB(e){return JI(bB(qI(e)))}function bB(e,t){return iB(Qz,e,t,`Stored session channel is invalid.`)}function xB(e,t){let n=rC.safeParse(e);if(!n.success||!pj(n.data))throw Z(t,`Stored session challenge is invalid.`);return n.data}function SB(e,t,n){let r=iB(eB,e,n,`Stored session receipt is invalid.`);if(r.channelId!==t.toLowerCase())throw Z(n,`Stored session receipt has a different channel ID.`);if(r.reference.toLowerCase()!==t.toLowerCase())throw Z(n,`Stored session receipt has a different reference.`);if(BigInt(r.spent)>BigInt(r.acceptedCumulative))throw Z(n,`Stored session receipt spend exceeds its accepted amount.`);return r}function CB(e,t){let n=iB(tB,e,t,`Stored session is invalid.`),{receipt:r,...i}=n,a=n.channel,o=n.account;if(o.address.toLowerCase()!==a.descriptor.payer.toLowerCase())throw Z(t,`Stored session account does not match the channel payer.`);let s=r?SB(r,a.channelId,t):void 0,c=n.spent,l=BigInt(a.cumulativeAmount);if(BigInt(c)>l)throw Z(t,`Stored session spend exceeds its cumulative authorization.`);if(s&&BigInt(s.acceptedCumulative)>l)throw Z(t,`Stored receipt exceeds the cumulative authorization.`);if(Date.parse(n.updatedAt)<Date.parse(n.createdAt))throw Z(t,`Stored session timestamps are not monotonic.`);let u=_B(n.endpoint,t);if(u!==n.endpoint)throw Z(t,`Stored session endpoint contains a fragment.`);let d=xB(n.challenge,t);return DB(d,JI(a),t),{...i,account:o,channel:a,endpoint:u,challenge:d,...s&&{receipt:s}}}function wB(e){return{version:1,status:e.status,channel:JI(e.channel),account:e.account,endpoint:e.endpoint,challenge:e.challenge,...e.receipt&&{receipt:e.receipt},spent:BigInt(e.spent),units:e.units,createdAt:e.createdAt,updatedAt:e.updatedAt}}function TB(e,t,n){let r=yB(t.channel),i=vB(t.account,n),a=JI(e.channel);if(JSON.stringify(EB(r))!==JSON.stringify(EB(a)))throw Z(n,`Session update changed immutable channel identity.`);if(i.address.toLowerCase()!==e.account.address.toLowerCase())throw Z(n,`Session update changed the payer account.`)}function EB(e){return{channelId:e.channelId.toLowerCase(),descriptor:Object.fromEntries(Object.entries(e.descriptor).map(([e,t])=>[e,typeof t==`string`?t.toLowerCase():t])),escrow:e.escrow.toLowerCase(),chainId:e.chainId}}function DB(e,t,n){if(RF({...t.descriptor,chainId:t.chainId,escrow:t.escrow}).toLowerCase()!==t.channelId.toLowerCase())throw Z(n,`Session channel ID does not match its descriptor.`);let r=mB(e.request.recipient,`challenge recipient`,n),i=mB(e.request.currency,`challenge currency`,n);if(r!==t.descriptor.payee.toLowerCase())throw Z(n,`Session challenge payee does not match the channel.`);if(i!==t.descriptor.token.toLowerCase())throw Z(n,`Session challenge token does not match the channel.`);if(FI(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Z(n,`Session challenge escrow does not match the channel.`);if(HB(e.request.methodDetails)){let r=e.request.methodDetails;if(r.chainId!==void 0&&r.chainId!==t.chainId)throw Z(n,`Session challenge chain does not match the channel.`)}}function OB(e,t,n){let r=hB(t);if(e.descriptor.payer.toLowerCase()!==r.payer||e.descriptor.payee.toLowerCase()!==r.payee||e.descriptor.token.toLowerCase()!==r.token||e.escrow.toLowerCase()!==r.escrow||e.chainId!==r.chainId)throw Z(n,`Session channel does not match the selected payment scope.`)}function kB(e,t){return e?t&&Date.parse(t.timestamp)>=Date.parse(e.timestamp)?t:e:t}function AB(e,t,n){if(!Number.isFinite(t.getTime()))throw Z(n,`Session clock is invalid.`);let r=t.toISOString();return!e||Date.parse(r)>=Date.parse(e)?r:e}function jB(...e){return e.reduce((e,t)=>t>e?t:e,0n)}async function MB(e){let t;try{t=await w.readFile(e,`utf8`)}catch(t){if(UB(t,`ENOENT`))return;throw Z(e,`Unable to read session state.`,t)}try{return JSON.parse(t)}catch(t){throw Z(e,`Session state contains invalid JSON.`,t)}}async function NB(e,t){await w.mkdir(c.dirname(e),{recursive:!0,mode:448}),await w.chmod(c.dirname(e),448);let n=`${e}.tmp-${process.pid}-${v()}`,r;try{r=await w.open(n,`wx`,384),await r.writeFile(`${JSON.stringify(t,null,2)}\n`,`utf8`),await r.sync(),await r.close(),r=void 0,await w.rename(n,e),await w.chmod(e,384),await BB(c.dirname(e))}catch(t){throw await r?.close().catch(()=>void 0),await w.unlink(n).catch(()=>void 0),t instanceof Xz?t:Z(e,`Unable to write session state.`,t)}}async function PB(e,t){let n;try{n=await w.open(e,`wx`,384),await n.writeFile(`${JSON.stringify(t)}\n`,`utf8`),await n.sync(),await n.close(),n=void 0,await BB(c.dirname(e))}catch(t){throw await n?.close().catch(()=>void 0),n&&await w.unlink(e).catch(()=>void 0),t}}async function FB(e,t){let n=IB(e);try{await w.link(e,n)}catch(t){if(UB(t,`EEXIST`)||UB(t,`ENOENT`))return;throw Z(e,`Unable to claim dead lock.`,t)}try{let r=await MB(n);if(r===void 0||iB(rB,r,n,`Session lock is invalid.`).token!==t.token)return;await zB(e,`Unable to reclaim dead lock.`)}finally{await zB(n,`Unable to release dead lock claim.`)}}function IB(e){return`${e}.reclaim`}async function LB(e){try{return await w.access(e),!0}catch(t){if(UB(t,`ENOENT`))return!1;throw Z(e,`Unable to inspect session lock.`,t)}}async function RB(e,t){let n=await MB(e);n!==void 0&&iB(rB,n,e,`Session lock is invalid.`).token===t.token&&await zB(e,`Unable to release session lock.`)}async function zB(e,t){try{await w.unlink(e),await BB(c.dirname(e))}catch(n){if(!UB(n,`ENOENT`))throw Z(e,t,n)}}async function BB(e){let t=await w.open(e,`r`);try{await t.sync()}finally{await t.close()}}function VB(e){try{return process.kill(e,0),!0}catch(e){if(UB(e,`ESRCH`))return!1;if(UB(e,`EPERM`))return!0;throw e}}function HB(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function UB(e,t){return e instanceof Error&&`code`in e&&e.code===t}function Z(e,t,n){return new Xz(t,{...n!==void 0&&{cause:n},file:e})}Rx(),sC(),DO(),qL(),lL(),HF(),YM(),PM();const WB=p.object({status:p.enum([`opening`,`open`,`closing`,`stale`]),channelId:p.string(),account:p.string().optional(),payer:p.string(),payee:p.string(),authorizedSigner:p.string(),token:p.string(),escrow:p.string(),chainId:p.number(),cumulativeAmount:p.string(),confirmedSpend:p.string(),deposit:p.string(),units:p.number(),resourceUrl:p.string(),createdAt:p.string(),updatedAt:p.string()}),GB=p.object({channelId:p.string(),status:p.enum([`closed`,`already-closed`]),spent:p.string(),txHash:p.string().optional()}),KB=p.object({closed:p.array(GB),failed:p.array(p.object({channelId:p.string(),message:p.string()}))});function qB(e){return e===`mainnet`?ve.id:ye.id}function JB(e){if(e===ve.id)return`mainnet`;if(e===ye.id)return`testnet`}function YB(e){let t={};for(let n of e??[]){let e=n.indexOf(`:`);if(e===-1)throw new B({code:`INVALID_HEADER`,message:`Invalid header format: ${n}`,exitCode:2});t[n.slice(0,e).trim()]=n.slice(e+1).trim()}return t}function XB(e){return{status:e.status,channelId:e.channel.channelId,...e.account.name&&{account:e.account.name},payer:e.channel.descriptor.payer,payee:e.channel.descriptor.payee,authorizedSigner:e.channel.descriptor.authorizedSigner,token:e.channel.descriptor.token,escrow:e.channel.escrow,chainId:e.channel.chainId,cumulativeAmount:e.channel.cumulativeAmount.toString(),confirmedSpend:e.spent.toString(),deposit:e.channel.deposit.toString(),units:e.units,resourceUrl:e.endpoint,createdAt:e.createdAt,updatedAt:e.updatedAt}}function ZB(e,t){throw e instanceof B?e:e instanceof Zz?new B({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e instanceof Xz?new B({code:e.code,message:e.message,exitCode:65,cause:e}):new B({code:t,message:e instanceof Error?e.message:String(e),exitCode:75,...e instanceof Error&&{cause:e}})}async function QB(e,t){let n=await GM(t??e.account.name);if(!AL(n.account,e.channel.descriptor))throw new B({code:`SESSION_ACCOUNT_MISMATCH`,message:`Account ${n.account.address} cannot sign for session ${e.channel.channelId}.`,exitCode:2});return n}async function $B(e,t){if(t.network&&qB(t.network)!==e)throw new B({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, not ${t.network}.`,exitCode:2});let n=t.network??JB(e),r=bM(t.rpcUrl,{network:n}),i=await SM({network:n,rpcUrl:r});if(i.id!==e)throw new B({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, but RPC is chainId ${i.id}.`,exitCode:2});return N({chain:i,transport:L(r)})}const eV=vb(`sessions`,{description:`Manage persistent payment sessions (list, view, close)`}).command(`list`,{description:`List persistent payment sessions`,options:p.object({account:p.string().optional().describe(`Filter by account name`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Filter by Tempo network`)}),output:p.object({sessions:p.array(WB)}),alias:{account:`a`},async run(e){try{let t=(await sB().list()).filter(t=>!(e.options.account&&t.account.name!==e.options.account||e.options.network&&t.channel.chainId!==qB(e.options.network))).map(XB),n={sessions:t};if(e.format===`json`&&e.formatExplicit)return e.ok(n);t.length===0&&console.log(`No sessions.`);for(let[e,n]of t.entries())e>0&&console.log(``),tV(n);return}catch(e){return ZB(e,`SESSION_LIST_FAILED`)}}}).command(`view`,{description:`View a persistent payment session`,args:p.object({channelId:p.string().describe(`Full session channel ID`)}),output:WB,async run(e){try{let t=await sB().get(e.args.channelId);if(!t)throw new B({code:`SESSION_NOT_FOUND`,message:`Session ${e.args.channelId} was not found.`,exitCode:2});let n=XB(t);if(e.format===`json`&&e.formatExplicit)return e.ok(n);tV(n);return}catch(e){return ZB(e,`SESSION_VIEW_FAILED`)}}}).command(`close`,{description:`Cooperatively close persistent payment sessions`,usage:[{suffix:`<channel-id> [options]`},{suffix:`--all --yes [options]`}],args:p.object({channelId:p.string().optional().describe(`Full session channel ID`)}),options:p.object({account:p.string().optional().describe(`Account name`),all:p.boolean().optional().default(!1).describe(`Close every matching session`),header:p.array(p.string()).optional().describe(`Add close request header (repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`),url:p.string().optional().describe(`Override the stored resource URL`),yes:p.boolean().optional().default(!1).describe(`Confirm closing every session`)}),output:p.union([GB,KB]),alias:{account:`a`,header:`H`,rpcUrl:`r`},async run(e){if(e.options.all&&e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all, not both.`,exitCode:2});if(!e.options.all&&!e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all.`,exitCode:2});if(e.options.all&&!e.options.yes)return e.error({code:`CONFIRMATION_REQUIRED`,message:`Closing all sessions requires --yes.`,exitCode:2});if(e.options.all&&(e.options.header||e.options.rpcUrl||e.options.url))return e.error({code:`INVALID_SESSION_CLOSE`,message:`--header, --rpc-url, and --url only apply to a single session.`,exitCode:2});let t=sB();async function n(e,n={}){let r=await t.get(e);if(!r)throw new B({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let i=oB(r.channel),a=await t.acquire(i);try{let r=await t.get(e);if(!r)throw new B({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});if(KS(r.challenge))throw new B({code:`SESSION_STATE_INVALID`,message:`Stored session challenge selects a credential header other than Payment-Authorization.`,exitCode:65});let a=await QB(r,n.account),o=await $B(r.channel.chainId,n);if(RF({...r.channel.descriptor,escrow:r.channel.escrow,chainId:r.channel.chainId}).toLowerCase()!==r.channel.channelId.toLowerCase())throw new B({code:`SESSION_STATE_INVALID`,message:`Stored descriptor does not derive the session channel ID.`,exitCode:65});if((await aL(o,r.channel.channelId,r.channel.escrow)).deposit===0n)return await t.remove(r.channel.channelId),{channelId:r.channel.channelId,status:`already-closed`,spent:r.spent.toString()};let s=_B(n.resourceUrl??r.endpoint),c={...a.source===`keychain`&&{name:a.accountName},address:a.account.address},l=(e=r.challenge)=>({status:`closing`,account:c,endpoint:s,challenge:e,...r.receipt&&{receipt:r.receipt},spent:r.spent,units:r.units}),u=await t.upsert({...l(),channel:r.channel}),d=YB(n.headers),f=u.challenge,p=await Yz({channel:u.channel,challenge:u.challenge,fetch:async(e,t)=>globalThis.fetch(e,{...t,headers:{...d,...OD(t?.headers)}}),input:s,spent:u.spent,async onChallenge(e){f=e,await t.upsert({...l(e),channel:u.channel})},manager:{account:a.account,client:o,channelStore:cB(t,{scope:i,selection:u.channel.channelId,context:()=>l(f)})}});return await t.remove(u.channel.channelId),{channelId:u.channel.channelId,status:`closed`,spent:p.receipt.spent,txHash:p.receipt.txHash}}finally{await a.release()}}try{if(e.options.all){let r=(await t.list()).filter(t=>(!e.options.account||t.account.name===e.options.account)&&(!e.options.network||t.channel.chainId===qB(e.options.network))),i=[],a=[];for(let t of r)try{i.push(await n(t.channel.channelId,{account:e.options.account,network:e.options.network}))}catch(e){a.push({channelId:t.channel.channelId,message:e instanceof Error?e.message:String(e)})}let o={closed:i,failed:a};if(a.length>0){for(let e of a)process.stderr.write(`${e.channelId}: ${e.message}\n`);process.exitCode=1}if(e.format===`json`&&e.formatExplicit)return e.ok(o);for(let e of i)console.log(`${e.channelId} ${e.status} ${e.spent}`);for(let e of a)console.log(`${e.channelId} failed ${e.message}`);return}let r=await n(e.args.channelId,{account:e.options.account,headers:e.options.header,network:e.options.network,resourceUrl:e.options.url,rpcUrl:e.options.rpcUrl});if(e.format===`json`&&e.formatExplicit)return e.ok(r);console.log(`${r.channelId} ${r.status} ${r.spent}`),r.txHash&&console.log(` transaction ${r.txHash}`);return}catch(e){return ZB(e,`SESSION_CLOSE_FAILED`)}}});function tV(e){console.log(e.channelId),console.log(` status ${e.status}`),console.log(` cumulative amount ${e.cumulativeAmount}`),console.log(` confirmed spend ${e.confirmedSpend}`),console.log(` deposit ${e.deposit}`),console.log(` chain ${e.chainId}`),console.log(` payer ${e.payer}`),console.log(` payee ${e.payee}`),console.log(` token ${e.token}`),console.log(` resource ${e.resourceUrl}`)}Rx(),qL(),lR(),yR(),CA(),YM(),PM();function nV(e,t){if(t&&e!==`auto`&&t.toLowerCase()!==e.toLowerCase())throw new B({code:`SESSION_SELECTION_CONFLICT`,message:`--session and -M channel= select different sessions.`,exitCode:2});let n=t??e;if(n===`auto`||n===`new`)return n;if(/^0x[0-9a-fA-F]{64}$/.test(n))return n.toLowerCase();throw new B({code:`INVALID_SESSION`,message:`Session must be auto, new, or a 32-byte channel ID.`,exitCode:2})}function rV(e){let t=e.allowCustomEscrow;if(t!==void 0){if(t===`true`)return!0;if(t===`false`)return!1;throw new B({code:`INVALID_ALLOW_CUSTOM_ESCROW`,message:`allowCustomEscrow must be true or false.`,exitCode:2})}}function iV(e,t,n,r){if(t.deposit!==void 0)return t.deposit;let i=e.request.suggestedDeposit;return typeof i==`string`?oe(BigInt(i),r):n?`10`:void 0}function aV(e,t){if(!e)return;if(e.challengeId!==t.challenge.id)throw Error(`Session receipt challenge does not match the paid request.`);if(e.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Session receipt channel does not match the selected channel.`);let n=BigInt(e.acceptedCumulative),r=BigInt(e.spent);if(n>t.cumulative)throw Error(`Session receipt exceeds the local cumulative authorization.`);if(r>n)throw Error(`Session receipt spend exceeds its accepted authorization.`);return e}function oV(e,t){return e.channel.channelId.toLowerCase()===t.toLowerCase()}function sV(e){if(e.trim()!==`[DONE]`){if(e.length===0){process.stdout.write(`
248
+ `);return}try{let t=JSON.parse(e);process.stdout.write(t.token??t.choices?.[0]?.delta?.content??e)}catch{process.stdout.write(e)}}}async function cV(e){let{options:t}=e,n=await GM(t.account),r=bM(t.rpcUrl,{network:t.network}),i=await SM({network:t.network,rpcUrl:r}),a=N({chain:i,transport:L(r)}),o=rV(e.methodOptions),s=await wL({allowCustomEscrow:o,challenge:e.challenge,getClient:async()=>a});if(s.chainId!==i.id)throw new B({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${s.chainId}, but RPC is chainId ${i.id}.`,exitCode:2});let{decimals:c}=await EM(a,s.token,n.account.address,{requireDecimals:!0}),l={payer:n.account.address,payee:s.payee,token:s.token,escrow:s.escrow,chainId:s.chainId},u=nV(t.session,e.methodOptions.channel),d=e.registry??sB(),f=await d.acquire(l).catch(e=>{throw e instanceof Zz?new B({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e});try{let r=u===`auto`?await d.getPreferred(l):u===`new`?void 0:u,s=r?await d.get(r):void 0;if(r&&!s)throw new B({code:`SESSION_NOT_FOUND`,message:`Session ${r} was not found.`,exitCode:2});if(s&&u!==`auto`&&(s.status!==`open`||!s.channel.opened||aB(oB(s.channel))!==aB(l)||!AL(n.account,s.channel.descriptor)))throw new B({code:`SESSION_MISMATCH`,message:`Session ${s.channel.channelId} cannot be used for this account and challenge.`,exitCode:2});let f=s?.status===`open`&&s.channel.opened?s:void 0,p=f?`open`:`opening`,m=e.challenge,h=f?.receipt,g=f?.spent??0n,_=f?.units??0,v=_B(e.endpoint),y={...n.source===`keychain`&&{name:n.accountName},address:n.account.address},b=cB(d,{scope:l,selection:u,context:()=>({status:p,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),onNewChannel(){p=`opening`,h=void 0,g=0n,_=0}}),{signal:x,...S}=e.init,C={...S,...x&&{signal:x},onReceipt(e){h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0)}};if(e.challengeResponse.status!==402||e.challengeResponse.bodyUsed)throw Error(`Session manager requires an unconsumed 402 challenge response.`);let w=!0,T=vR({account:n.account,allowCustomEscrow:o,bootstrap:!1,client:a,channelStore:b,credentialContext:e.credentialContext,decimals:c,maxDeposit:iV(e.challenge,e.methodOptions,TM(i),c),fetch:async(t,n)=>w?(w=!1,e.challengeResponse):e.fetch(t,n)});f&&sR(T).rehydrate({channel:f.channel,challenge:e.challenge,input:e.fetchInput,spent:f.spent});let{onReceipt:E,...ee}=C,D=await T.fetch(e.fetchInput,ee);if(t.fail&&D.status>=400)throw new B({code:`HTTP_ERROR`,message:`HTTP error ${D.status}`,exitCode:22});if(D.status===402)throw new B({code:`PAYMENT_REJECTED`,message:`Payment rejected.`,exitCode:75});cM(D,{include:!1,verbose:t.include?Math.max(t.verbose,2):t.verbose,silent:t.silent}),m=D.challenge??e.challenge;let O=T.channelId;if(!O)throw Error(`Session manager did not select a channel.`);if(h=aV(D.receipt,{challenge:m,channelId:O,cumulative:T.cumulative})??h,pA(D)){let t=sR(T).consumeSseResponse(e.fetchInput,D,{onReceipt:E,signal:e.init.signal??void 0});for await(let e of t)sV(e)}else process.stdout.write(Buffer.from(await D.arrayBuffer()));let k=await d.get(O);if(!k||!oV(k,O))throw Error(`Session ${O} was not persisted.`);if(h){let e=aV(h,{challenge:m,channelId:O,cumulative:T.cumulative});if(!e)throw Error(`Session receipt validation failed.`);h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0),p=`open`}await d.upsert({status:p,channel:k.channel,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),t.silent||(e.info(`Session retained ${O}\n`),e.info(`Close with: mppx sessions close ${O}\n`))}finally{await f.release()}}const lV=`StripeCLI`;function uV(e){let t=e.env??process.env,n=e.secretKey?.trim();if(n)return{key:n,source:`flag`};let r=t.STRIPE_SECRET_KEY?.trim();if(r)return{key:r,source:`env`};let i=dV(e);if(i)return{key:i,source:`stripe-cli`}}function dV(e){let t=e.env??process.env,n=c.join(t.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`stripe`),r=e.projectName||t.STRIPE_PROJECT_NAME||`default`,i=hV(c.join(n,`config.toml`),r);if(!e.live)return i.test_mode_api_key||i.secret_key||i.api_key||void 0;let a=i.live_mode_api_key;if(a&&!a.includes(`*`))return a;let o=`${r}.live_mode_api_key`,s=mV(c.join(n,`credentials.json`))?.[o];return typeof s==`string`&&s?s:fV(o,e)}function fV(e,t){let n=t.platform??process.platform,r=t.exec??pV,i=(()=>{if(n===`darwin`)return[`security`,[`find-generic-password`,`-s`,lV,`-a`,e,`-w`]];if(n===`linux`)return[`secret-tool`,[`lookup`,`service`,lV,`username`,e]]})();if(i)try{let e=r(i[0],i[1]).trim();return e.startsWith(`go-keyring-base64:`)?Buffer.from(e.slice(18),`base64`).toString(`utf8`)||void 0:e||void 0}catch{return}}function pV(e,t){return g(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:3e3})}function mV(e){try{return JSON.parse(t.readFileSync(e,`utf8`))}catch{return}}function hV(e,n){let r;try{r=t.readFileSync(e,`utf8`)}catch{return{}}let i=new Set([n,`profiles.${n}`]),a={},o;for(let e of r.split(/\r?\n/)){let t=e.trim();if(!t||t.startsWith(`#`))continue;let n=/^\[\s*([^\]]+?)\s*\]$/.exec(t);if(n){o=n[1].replace(/["']/g,``).replace(/\s*\.\s*/g,`.`);continue}if(!o||!i.has(o))continue;let r=/^([A-Za-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)')/.exec(t);r&&(a[r[1]]=r[2]===void 0?r[3]:r[2].replace(/\\(.)/g,`$1`))}return a}function gV(e,t){return typeof t==`string`?e===`solana`?_V(t)===32:/^0x[0-9a-fA-F]{40}$/.test(t):!1}function _V(e){if(!/^[1-9A-HJ-NP-Za-km-z]{1,64}$/.test(e))return;let t=0n;for(let n of e)t=t*58n+BigInt(`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`.indexOf(n));let n=/^1*/.exec(e)[0].length,r=t===0n?``:t.toString(16);return n+Math.ceil(r.length/2)}function vV(e,n,r){if(/[\r\n]/.test(n)||/[\r\n]/.test(r))throw Error(`env values cannot contain line breaks`);let i=`${n}=${r}`;if(!t.existsSync(e))return t.writeFileSync(e,`${i}\n`,{mode:384});let a=t.readFileSync(e,`utf8`),o=RegExp(`^\\s*(?:export\\s+)?${n}\\s*=`),{lines:s,found:c}=yV(a.split(`
249
249
  `),o,i),l=a===``||a.endsWith(`
250
250
  `)?``:`
251
251
  `,u=c?s.join(`
252
- `):`${a}${l}${i}\n`,d=y.parseEnv;if(d){let t=d(a),i=d(u),o=new Set([...Object.keys(t),...Object.keys(i)]);if(o.delete(n),i[n]!==r||[...o].some(e=>t[e]!==i[e]))throw Error(`could not update ${n} in ${e} safely: edit it by hand`)}t.writeFileSync(e,u)}function vV(e,t,n){let r={};for(let t of[`"`,`'`,"`"]){let n=Array(e.length+1);n[e.length]=-1;for(let r=e.length-1;r>=0;r--)n[r]=yV(e[r],t)?r:n[r+1];r[t]=n}let i=[],a=!1;for(let o=0;o<e.length;o++){let s=o,c=/^[ \t]*[^#=\s][^=]*=[ \t]*(["'`])(.*)$/s.exec(e[o]);if(c&&!yV(c[2],c[1])){let e=r[c[1]][o+1];e!==-1&&(s=e)}let l=t.test(e[o]);if(l&&!a&&i.push(e[o].endsWith(`\r`)?`${n}\r`:n),a||=l,!l)for(let t=o;t<=s;t++)i.push(e[t]);o=s}return{lines:i,found:a}}function yV(e,t){return e.includes(t)}function bV(e){let t=e.findIndex((t,n)=>t===`stripe`&&e[n+1]===`address`);if(t===-1)return[...e];let n=e.slice(0,t+2);for(let r=t+2;r<e.length;r++){let t=e[r];if(n.push(t),t===`--`){n.push(...e.slice(r+1));break}let i=e[r+1];t===`--env`&&(i===void 0||i.startsWith(`-`))&&n.push(`.env`)}return n}DO();function Q(e,t){return t?{label:e,detail:t,severity:`pass`}:{label:e,severity:`pass`}}function $(e,t,n){let r={label:e,severity:`fail`};return t&&(r.detail=t),n&&(r.hint=n),r}function xV(e,t,n){let r={label:e,severity:`warn`};return t&&(r.detail=t),n&&(r.hint=n),r}function SV(e,t,n){let r=t?{label:e,detail:t,severity:`skip`}:{label:e,severity:`skip`};return n&&(r.hint=n),r}async function CV(e,t,n=15e3){let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{let n=globalThis.fetch,i=QD(n),a=XD(n),o={[bO]:!0,...t,redirect:`error`,signal:r.signal};return a?(await a.send((e,t)=>i(e,{...t,[bO]:!0}),new Request(e,o))).response:await i(e,o)}finally{clearTimeout(i)}}function wV(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}const TV=new Set([`get`,`post`,`put`,`patch`,`delete`,`head`,`options`,`trace`]);function EV(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)}function DV(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function OV(e){let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t).toLowerCase();if(!TV.has(n))return null;let r=e.slice(t+1);if(!r)return null;let i=r.startsWith(`/`)?r:`/`+r;return{method:n.toUpperCase(),path:i}}function kV(e,t){if(e){try{let n=JSON.parse(e);if(n&&typeof n==`object`&&!Array.isArray(n)){let e=Object.keys(n);if(e.length>0&&e.every(e=>e.startsWith(`/`))){let e=n[t];return e===void 0?void 0:typeof e==`string`?e:JSON.stringify(e)}}}catch{}return e}}function AV(e){if(!e)return{};let t={};for(let n of e){let e=n.indexOf(`:`);e>0&&(t[n.slice(0,e).trim().toLowerCase()]=n.slice(e+1).trim())}return t}async function jV(e){let t=new URL(`openapi.json`,e.replace(/\/?$/,`/`)).href;try{let e=await CV(t,{});if(!e.ok)return{error:`HTTP ${e.status}`};let n=await e.text();return{doc:JSON.parse(n),raw:n}}catch(e){return e instanceof DOMException&&e.name===`AbortError`?{error:`Request timed out after 15s`}:e instanceof SyntaxError?{error:`Invalid JSON`}:{error:e.message}}}async function MV(e){let t=new URL(`/llms.txt`,e).href,n=`llms.txt found and nonempty`;try{let e=await CV(t,{});if(!e.ok)throw Error(`HTTP ${e.status}`);let r=(await e.text()).trim();if(!r)throw Error(`Empty document`);let i=e.headers.get(`content-type`)?.split(`;`)[0]?.trim().toLowerCase();if(i&&!i.startsWith(`text/`)||i===`text/html`||/^<(?:!doctype html|html|head|body)\b/i.test(r))throw Error(`Expected text documentation, received non-text or HTML content`);return Q(n,t)}catch(e){return{label:n,detail:`${t}: ${e.message}`,severity:`suggested`,hint:`Serve nonempty text documentation at /llms.txt.`}}}function NV(e){let t=[],n=[],r=e.paths;if(!r)return[];for(let[e,i]of Object.entries(r)){let r=IV(i.parameters);for(let[a,o]of Object.entries(i)){if(!TV.has(a)||!o||typeof o!=`object`||Array.isArray(o))continue;let i=o,s=LV(r,IV(i.parameters)),c=s.length>0?s:void 0;if(i[`x-payment-info`]){let n=i[`x-payment-info`];t.push({method:a.toUpperCase(),path:e,amount:n.amount,parameters:c})}else{let t=i.responses;t&&`402`in t&&n.push({method:a.toUpperCase(),path:e,parameters:c})}}}return t.length>0?t:n}function PV(e,t){let n=e.paths;if(!n)return;let r=n[t.path];if(!r)return;let i=r[t.method.toLowerCase()];if(!i?.requestBody)return;let a=i.requestBody.content?.[`application/json`];if(!a)return;if(a.example)return JSON.stringify(a.example);if(a.examples&&typeof a.examples==`object`){let e=Object.values(a.examples)[0];if(e?.value)return JSON.stringify(e.value)}let o=a.schema,s=new Set;if(o=zV(o,e,s),!o||o.type!==`object`)return;let c=BV(o,e,s);if(c&&typeof c==`object`&&Object.keys(c).length>0)return JSON.stringify(c)}function FV(e,t,n){if(!t.path.startsWith(`/`)||t.path.startsWith(`//`)||t.path.includes(`\\`))throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let r=t.path;t.parameters&&(r=RV(r,t.parameters));let i=r.startsWith(`/`)?r.slice(1):r,a=new URL(e.replace(/\/?$/,`/`)),o=new URL(i,a);if(o.origin!==a.origin)throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let s=o.href;if(n){let e=new URL(s);for(let t of n){let[n,...r]=t.split(`=`);n&&e.searchParams.set(n,r.join(`=`))}s=e.href}return s}function IV(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;e.in===`path`&&typeof e.name==`string`&&t.push(e.schema&&typeof e.schema==`object`?{name:e.name,in:`path`,schema:e.schema,example:e.example}:{name:e.name,in:`path`,example:e.example})}return t}function LV(e,t){let n=[...e];for(let e of t){let t=n.findIndex(t=>t.name===e.name);t>=0?n[t]=e:n.push(e)}return n}function RV(e,t){return e.replace(/\{([^}]+)\}/g,(e,n)=>{let r=t.find(e=>e.name===n&&e.in===`path`);if(!r)return e;let i=r.example??r.schema?.example??r.schema?.default;return i===void 0?e:encodeURIComponent(String(i))})}function zV(e,t,n){if(!e||typeof e.$ref!=`string`)return e;if(n?.has(e.$ref))return;let r=e.$ref.replace(/^#\//,``).split(`/`),i=t;for(let e of r)if(i&&typeof i==`object`)i=i[e];else return;return i}function BV(e,t,n){let r=zV(e,t,n)??e;if(r.const!==void 0)return r.const;if(r.example!==void 0)return r.example;if(r.default!==void 0)return r.default;switch(r.type){case`string`:return r.enum&&Array.isArray(r.enum)?r.enum[0]:r.format===`email`?`test@example.com`:r.format===`uuid`?`00000000-0000-0000-0000-000000000000`:r.format===`uri`||r.format===`url`?`https://example.com`:r.format===`date`?`2026-01-01`:r.pattern===`^\\d{5}(?:-\\d{4})?$`?`10001`:r.pattern===`^[A-Z]{2}$`?`US`:`test`;case`number`:case`integer`:return r.minimum??1;case`boolean`:return!0;case`array`:return[];case`object`:{let e=r.properties;if(!e)return{};let i=r.required||[],a={};for(let r of i){let i=e[r];i&&(a[r]=BV(i,t,n))}return a}default:return null}}sC(),Gx(),Qj(),HT();const VV=Object.values(Qe);function HV(e){let t=e.request.methodDetails;return typeof t?.chainId==`number`&&VV.find(e=>e.id===t.chainId)?.testnet===!0}async function UV(e,t,n,r){let i=[],a;try{a=FV(e,t,r?.query)}catch(e){return i.push($(`Request URL valid`,e.message)),{results:i}}let o=AV(r?.extraHeaders),s;r?.body&&!r.bodyIsAutogenerated&&(s=r.body,o[`content-type`]||=`application/json`);let c;try{let e={method:t.method};Object.keys(o).length>0&&(e.headers=o),s&&(e.body=s),c=await CV(a,e)}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}if(!s&&(c.status===400||c.status===422)){let e=r?.body??(r?.discoveryDoc?PV(r.discoveryDoc,t):void 0);if(e){n&&console.log(X.dim(` Retrying with body: ${e}`)),s=e,o[`content-type`]=`application/json`;try{c=await CV(a,{method:t.method,headers:o,body:s})}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}}}if(c.status!==402)return c.status===200?i.push(SV(`Returns 402 without credentials`,`Got 200 (endpoint may not require payment in all cases)`)):c.status===401||c.status===403?i.push(SV(`Returns 402 without credentials`,`Got ${c.status} (endpoint requires auth before payment gate)`)):i.push($(`Returns 402 without credentials`,`Got ${c.status} instead`,c.status===400||c.status===422?`Server requires a valid request body before returning 402. Add a requestBody schema with examples to your OpenAPI doc, or use --body.`:`Endpoints that require payment must return HTTP 402 with a WWW-Authenticate: Payment header when no valid credential is provided.`)),{results:i};i.push(Q(`Returns 402 without credentials`));let l=c.headers.get(q.wwwAuthenticate),u=eH(c);if(!l)return u.length>0?(i.push(SV(`Not an MPP endpoint`,`No WWW-Authenticate header — x402 protocol detected`)),i.push(...u)):i.push(SV(`Not an MPP endpoint`,`No WWW-Authenticate header (may be x402 or other protocol)`)),{results:i};if(u.length>0&&i.push(...u),!l.startsWith(`${Bx.payment} `))return i.push(SV(`Not an MPP endpoint`,`WWW-Authenticate scheme is not Payment`)),{results:i};i.push(Q(`WWW-Authenticate header present`,`Payment scheme`));let d;try{d=RS(c)}catch(e){let t=e.message;i.push($(`Challenge parseable`,t,`The Payment challenge must include a request="<base64url>" parameter containing JSON-encoded payment details.`));let n=l.slice(l.indexOf(` `)+1);return i.push(xV(`Received`,n.length>200?n.slice(0,200)+`...`:n)),{results:i}}if(d.length===0){let e=`No Payment challenges found in header`;try{LS(c)}catch(t){e=t.message}return i.push($(`Challenge parseable`,e)),{results:i}}let f=d.map(e=>`${e.method}/${e.intent}`).join(`, `);i.push(Q(`Challenge parseable`,d.length===1?f:`${d.length} methods: ${f}`));let p=VS(l);p>0&&i.push($(`Challenge credential header`,`${p} of ${d.length+p} challenges select a credential header other than Payment-Authorization`,`A challenge may only set header="Payment-Authorization"; omit header to use Authorization.`));let m=new URL(e).hostname;WV(d,i),GV(d,i),KV(d,i),qV(d,m,i);let h=d.length>1;for(let e of d){let t=e.request;JV(e,t,i,h)}if(n)for(let e of d)console.log(X.dim(` Challenge (${e.method}/${e.intent}): ${JSON.stringify(e,null,2)}`));return{results:i,resolvedBody:s,challenges:d}}function WV(e,t){let n=e.filter(e=>!e.id);n.length===0?t.push(Q(`Challenge has id`)):t.push($(`Challenge has id`,`${n.length} missing`,`Every challenge must include a unique id field.`))}function GV(e,t){let n=e.filter(e=>!e.realm);n.length===0?t.push(Q(`Challenge has realm`)):t.push($(`Challenge has realm`,`${n.length} missing`,`Set realm to your server's hostname.`))}function KV(e,t){let n=new Date;for(let r of e){if(!r.expires){t.push(xV(`Challenge has expiration`,`missing expires field`,`Add an expires field (ISO 8601) to prevent replay attacks.`));return}if(new Date(r.expires)<=n){t.push($(`Challenge expires in the future`,`Expired at ${r.expires}`,`The expires timestamp must be in the future.`));return}}let r=Math.min(...e.map(e=>new Date(e.expires).getTime()-n.getTime()));t.push(Q(`Challenge expires in the future`,`${Math.round(r/6e4)}m from now`))}function qV(e,t,n){let r=e=>e.toLowerCase().replace(/\.$/,``),i=r(t),a=[...new Set(e.map(e=>e.realm??``))].filter(e=>{let t=r(e);return!t||t!==i&&!i.endsWith(`.${t}`)});a.length>0?n.push($(`Realm matches server hostname`,`realm="${a[0]}" vs host="${t}"`,`Set the realm to your production hostname (or base domain) in the challenge.`)):n.push(Q(`Realm matches server hostname`))}function JV(e,t,n,r){let i=r?`[${e.method}] `:``;e.method===Vx.tempo?YV(t,i,n,e):e.method===Vx.stripe?XV(t,i,n):e.method===Vx.evm&&ZV(e,t,i,n)}function YV(e,t,n,r){let i=e.methodDetails,a=Array.isArray(i?.splits)&&i.splits.length>0;if(EV(e.recipient)?n.push(Q(`${t}Valid recipient address`)):e.recipient===void 0&&a?n.push(Q(`${t}Uses splits (no single recipient)`)):e.recipient===void 0?n.push($(`${t}Valid recipient address`,`Missing recipient (and no splits defined)`,`Set request.recipient to a valid 0x address, or use methodDetails.splits for multiple recipients.`)):n.push($(`${t}Valid recipient address`,`Got: ${String(e.recipient)}`,`Set request.recipient to a valid 0x-prefixed 40-hex-char address.`)),EV(e.currency)){let e=HV(r)?`testnet`:`mainnet`;n.push(Q(`${t}Valid currency address`,e))}else n.push($(`${t}Valid currency address`,`Got: ${String(e.currency)}`,`Set request.currency to a valid token address.`));QV(e,t,n,`token's smallest unit (e.g. "10000" = $0.01 for 6-decimal tokens)`)}function XV(e,t,n){QV(e,t,n,`currency's smallest unit (e.g. "100" = $1.00 for USD)`);let r=e.currency;typeof r==`string`&&/^[a-z]{3}$/i.test(r)?n.push(Q(`${t}Valid currency code`,r.toUpperCase())):n.push($(`${t}Valid currency code`,r?`Got: ${r}`:`missing`,`Must be a three-letter ISO currency code (e.g. "usd").`));let i=e.methodDetails,a=i?.networkId;a?n.push(Q(`${t}Has networkId`,a.slice(0,20))):n.push($(`${t}Has networkId`,`Missing methodDetails.networkId`,`Set methodDetails.networkId to your Stripe Business Network profile ID.`));let o=i?.paymentMethodTypes;Array.isArray(o)&&o.length>0?n.push(Q(`${t}Has paymentMethodTypes`,o.join(`, `))):n.push($(`${t}Has paymentMethodTypes`,`Missing or empty`,`Set methodDetails.paymentMethodTypes to an array (e.g. ["card"]).`))}function ZV(e,t,n,r){if(EV(t.recipient)?r.push(Q(`${n}Valid recipient address`)):r.push($(`${n}Valid recipient address`,`Got: ${String(t.recipient)}`,`Set request.recipient to a valid 0x-prefixed Ethereum address.`)),EV(t.currency)){let t=HV(e)?`testnet`:`mainnet`;r.push(Q(`${n}Valid currency address`,t))}else r.push($(`${n}Valid currency address`,`Got: ${String(t.currency)}`,`Set request.currency to a valid ERC-20 token contract address.`));QV(t,n,r,`token's smallest unit`);let i=t.methodDetails?.chainId;typeof i==`number`&&i>0?r.push(Q(`${n}Has chainId`,String(i))):r.push($(`${n}Has chainId`,`Missing methodDetails.chainId`,`Set methodDetails.chainId to the EVM chain ID.`))}function QV(e,t,n,r){DV(e.amount)?n.push(Q(`${t}Amount is valid integer string`)):e.amount===void 0||e.amount===null?n.push($(`${t}Amount is valid integer string`,`Missing amount`,`Set request.amount to a string of digits in the ${r}.`)):n.push($(`${t}Amount is valid integer string`,`Got: ${String(e.amount)}`,`request.amount must be a string of digits (no decimals, no prefix).`))}async function $V(e,t,n){let r=[],i=FV(e,t,n?.query),a=AV(n?.extraHeaders),o=n?.challenge?GS(n.challenge):q.authorization;a[o.toLowerCase()]=`${Bx.payment} dGhpcyBpcyBnYXJiYWdl`;let s;n?.body&&(s=n.body,a[`content-type`]||=`application/json`);try{let e=await CV(i,{method:t.method,headers:a,body:s??null});e.status===402?(r.push(Q(`Malformed credential returns 402`,`not 500`)),e.headers.get(q.wwwAuthenticate)?.startsWith(`${Bx.payment} `)?r.push(Q(`Error response includes fresh challenge`)):r.push(xV(`Error response includes fresh challenge`,`No WWW-Authenticate header`,`When rejecting an invalid credential, respond with 402 and include a fresh WWW-Authenticate: Payment challenge so the client can retry.`))):e.status>=500?r.push($(`Malformed credential returns 402`,`Got ${e.status} (server error)`,`When the ${o} header contains an invalid credential, respond with 402 (not 500). Catch credential validation errors and return a fresh challenge.`)):r.push(xV(`Malformed credential returns 402`,`Got ${e.status}`,`When the ${o} header contains an invalid Payment credential, respond with 402 and a fresh WWW-Authenticate challenge. Returning ${e.status} prevents the client from retrying with a valid payment.`))}catch(e){r.push($(`Error handling test`,e.message))}return r}function eH(e){let t=[],n=e.headers.get(`payment-required`)??e.headers.get(`x-payment-required`);if(!n)return t;let r=e.headers.get(`payment-required`)?`PAYMENT-REQUIRED`:`X-Payment-Required`;try{let e=PT(n);t.push(Q(`x402 payment challenge`,`${r} with valid x402 v${e.x402Version} payload`))}catch{t.push(xV(`x402 payment challenge`,`${r} header present but failed schema validation`,`Ensure the PAYMENT-REQUIRED header contains a valid base64-encoded JSON payload matching the x402 schema.`))}return t}const tH=[`No discovery document found, endpoints could not be automatically found.`,`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,`The MPP SDKs can automatically expose this endpoint. See https://mpp.dev/sdk.`,``,`To test a specific endpoint: mppx validate <url> --endpoint POST:/your/path`].join(`
253
- `);async function*nH(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n=e.verbose??!1,r=await sH(t,e);yield{phase:`discovery`,discovery:r,results:r.checks};for(let i of r.endpoints){yield{phase:`endpoint`,endpoint:i};let a,o=!1;e.endpoint?a=e.body:(a=kV(e.body,i.path),!a&&r.doc&&(a=PV(r.doc,i),o=!!a));let{results:s,resolvedBody:c,challenges:l}=await UV(t,i,n,{body:a,bodyIsAutogenerated:o,query:e.query,extraHeaders:e.headers,discoveryDoc:r.doc??void 0}),u=c??a,d=s.some(e=>e.severity===`pass`&&e.label===`Challenge parseable`),f=!s.some(e=>e.severity===`fail`),p=(l??[]).filter(e=>e.method!==`stripe`).map(e=>e.request.methodDetails?.chainId).filter(e=>typeof e==`number`),m=p.some(oH),h=p.some(e=>!oH(e)),g=!d&&s.some(e=>e.label===`Not an MPP endpoint`),_=s.some(e=>e.severity===`pass`&&e.label===`WWW-Authenticate header present`),v=s.some(e=>e.severity===`fail`&&e.label===`Challenge parseable`);if(yield{phase:`challenge`,endpoint:i,results:s,isMpp:d,isTestnet:m,isMainnet:h,isNonMppPayment:g,isMalformedChallenge:!d&&_&&v,methods:l?.map(e=>e.method)??[]},d&&(yield{phase:`errorHandling`,endpoint:i,results:await $V(t,i,{body:u,challenge:l?.[0],extraHeaders:e.headers,query:e.query})},!e.skipPayment&&f)){let r=e.onPaymentResults;if(!e.payment){let e=[SV(`Payment: not tested`,`no payment validator configured`,"Run `mppx validate` to test payment, or pass `payment` to validate().")];r?.(e),yield{phase:`payment`,endpoint:i,results:e,succeeded:!1};continue}let a=await e.payment(t,i,n,{body:u,query:e.query,extraHeaders:e.headers,yes:e.yes,silent:!r,interactive:e.interactive,...r&&{onResults:r}}),o=Array.isArray(a)?a:a.results,s=Array.isArray(a)?a.some(e=>e.severity===`pass`&&e.label===`Payment: successful`):a.succeeded;if(!Array.isArray(a)&&!s&&!o.some(e=>e.severity===`fail`)){let e=$(`Payment: failed`,`the payment validator reported that the payment did not succeed`);o=[...o,e],r?.([{...e}])}yield{phase:`payment`,endpoint:i,results:o,succeeded:s}}}}async function rH(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n,r=[],i,a=!1,o=!1;for await(let t of nH(e))switch(t.phase){case`discovery`:n=t.discovery;break;case`endpoint`:i={method:t.endpoint.method,path:t.endpoint.path,challenge:[],errorHandling:[],payment:[]},r.push(i);break;case`challenge`:i&&(i.challenge=t.results),t.isMpp&&(t.isTestnet&&(a=!0),t.isMainnet&&(o=!0));break;case`errorHandling`:i&&(i.errorHandling=t.results);break;case`payment`:i&&(i.payment=t.results,e.payment&&(i.paymentSucceeded=t.succeeded))}let s={passed:0,failed:0,warnings:0,suggested:0,skipped:0};if(n)for(let e of n.checks)e.severity===`pass`?s.passed++:e.severity===`fail`?s.failed++:e.severity===`warn`?s.warnings++:e.severity===`suggested`?s.suggested++:e.severity===`skip`&&s.skipped++;for(let e of r)for(let t of[...e.challenge,...e.errorHandling,...e.payment])t.severity===`pass`?s.passed++:t.severity===`fail`?s.failed++:t.severity===`warn`?s.warnings++:t.severity===`suggested`?s.suggested++:t.severity===`skip`&&s.skipped++;if(!n)throw Error(`Discovery phase did not complete`);let c=iH(r,n,{sawTestnet:a,sawMainnet:o,hasPaymentValidator:!!e.payment});return{url:t,discovery:n,endpoints:r,summary:s,suggestions:c}}function iH(e,t,n){let r=[],i=e.flatMap(e=>[...e.challenge,...e.payment]);t.found||r.push(tH);let a=n.sawMainnet,o=n.sawTestnet,s=i.some(e=>e.label.includes(`[stripe]`)&&e.label.includes(`livemode`));return a&&!o?r.push(n.hasPaymentValidator?`Validate your testnet server to test without real funds (Tempo wallets are automatically provisioned).`:"Validate your testnet server to test without real funds. Run `mppx validate` to test payment with an automatically provisioned Tempo wallet."):o&&!a&&r.push(`Validate your mainnet server to confirm real payments work end-to-end.`),s&&r.push(`Validate your testmode Stripe server to test card payments end-to-end (auto-pays with test card).`),r}const aH=Object.values(Qe);function oH(e){return aH.find(t=>t.id===e)?.testnet===!0}async function sH(e,t){let n=[],r=[],i=null,a=!1,o=!1;n.push(await MV(e));let s=new URL(e).origin,c;t.discoveryPath?c=[new URL(t.discoveryPath,e+`/`).href.replace(/\/openapi\.json$/i,``)]:(c=[e,s,`${s}/api`],c=[...new Set(c)]);let l,u=[];for(let e of c)if(l=await jV(e),`error`in l)u.push(`${e}/openapi.json: ${l.error}`);else break;if(!l||`error`in l)n.push({label:`Document found`,detail:u.join(`; `),hint:`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,severity:`fail`});else{a=!0,n.push({label:`Document found and parseable`,severity:`pass`});let e=dk(l.doc),t=e.filter(e=>e.severity===`error`),r=e.filter(e=>e.severity===`warning`);if(t.length>0){n.push({label:`Valid OpenAPI structure`,detail:`${t.length} error(s)`,severity:`fail`});for(let e of t)n.push({label:e.message,detail:e.path,severity:`fail`})}else o=!0,n.push({label:`Valid OpenAPI structure`,severity:`pass`});for(let e of r)n.push({label:e.message,detail:e.path,severity:`warn`});i=l.doc}if(t.endpoint){let e=OV(t.endpoint);e&&r.push(e)}else if(i){r=NV(i);let e=BigInt(`999999999999999999`);r.sort((t,n)=>{let r=DV(t.amount)?BigInt(t.amount):e,i=DV(n.amount)?BigInt(n.amount):e;return r<i?-1:+(r>i)}),r.length>0?n.push({label:`Paid endpoints found`,detail:`${r.length} endpoint(s)`,severity:`pass`}):n.push({label:`Paid endpoints found`,detail:`No endpoints with x-payment-info`,severity:`warn`})}return{found:a,valid:o,endpoints:r,checks:n,doc:i}}sC(),bE(),Gx(),Jw(),XR(),aM(),Zj(),CA(),JM(),PM();async function cH(e,t,n){try{n||console.log(X.dim(` Provisioning testnet wallet and funding via faucet...`));let t=ge(),r=R(t),i=N({chain:ye,transport:L()});if(pj(e)){let{chainId:t,operator:n}=e.request.methodDetails??{};if(t===ye.id&&typeof n==`string`&&le(n)&&n!==he){let e=await Be.faucet.fund(i,{account:n});await Promise.all(e.map(e=>Le(i,{hash:e})))}}let a=await Be.faucet.fund(i,{account:r});await Promise.all(a.map(e=>Le(i,{hash:e}))),n||console.log(X.dim(` Using wallet: ${r.address}`));let o=e.request.currency;if(typeof o==`string`)for(let e=0;e<10;e++){let e=await Be.token.getBalance(i,{account:r.address,token:o}).catch(()=>void 0);if(e&&e.amount>0n)break;await new Promise(e=>setTimeout(e,500))}return{methods:[...qR({account:r})]}}catch(e){t&&console.log(X.dim(` Provisioning failed: ${e.message}`));return}}async function lH(){let e=VM(),{isTempoAccount:t}=await Promise.resolve().then(()=>(PM(),oM)),{resolveTempoAccount:n}=await Promise.resolve().then(()=>(Az(),ZR));if(t(e)){let t=n(e);if(t)return t.wallet_address}try{return(await GM()).address}catch{return}}function uH(e){try{let{execSync:t}=m,n=t(`stripe config --list`,{encoding:`utf8`,timeout:5e3}).match(/test_mode_api_key\s*=\s*'([^']+)'/);if(n?.[1])return e&&console.log(X.dim(` Using Stripe test key from stripe CLI`)),n[1]}catch{}}async function dH(e,t,n){let r=N({chain:e,transport:L()}),[i,a,o]=await Promise.all([n?je(r,{address:t,abi:F,functionName:`balanceOf`,args:[n]}):0n,je(r,{address:t,abi:F,functionName:`decimals`}),je(r,{address:t,abi:F,functionName:`symbol`}).catch(()=>void 0)]);return{balance:i,decimals:a,symbol:o??void 0}}function fH(e){return Object.values(Qe).find(t=>t.id===e)}function pH(e,t){return`$${(Number(e)/10**t).toFixed(2)}`}function mH(e){switch(e.method){case Vx.evm:return`no EVM payment plugin yet`;case`solana`:return`no Solana payment plugin yet`;default:return`no plugin for ${e.method}/${e.intent}`}}async function hH(e,t,n,r){let i=[],a=FV(e,t,r.query),o=AV(r.extraHeaders),s;r.body&&(s=r.body,o[`content-type`]=`application/json`);let c;try{c=await CV(a,{method:t.method,headers:o,body:s??null})}catch(e){return i.push($(`Payment: fetch challenge`,e.message)),i}if(c.status!==402)return i.push(SV(`Payment: skipped`,`Endpoint returned ${c.status}`)),i;let l;try{l=RS(c)}catch(e){return i.push($(`Payment: parse challenge`,e.message)),i}if(l.length===0)return i.push($(`Payment: parse challenge`,`No Payment challenges in response`)),i;let u=[];qV(l,new URL(a).hostname,u);let d=u.filter(e=>e.severity===`fail`);if(d.length>0)return i.push(...d),r.onResults?.(d),i;let f=await Hz().catch(()=>void 0),p=l.find(e=>{if(e.method!==Vx.tempo||Bz(f?.config)?.some(t=>t.name===e.method&&t.intent===e.intent))return!1;let t=e.request.methodDetails;return typeof t?.chainId==`number`&&t.chainId!==$j.mainnet});if(p){let e=await cH(p,n,r.silent);if(e)try{let r=SH((e,t)=>CV(e,t??{},3e4));await bH(i,await jO({methods:e.methods,polyfill:!1,async onChallenge(e,{createCredential:t}){Wz(p,e);let n=await t(await Iz(e,f?.config.extensions));return i.push(Q(`Payment: submitted`,`ephemeral testnet wallet`)),n},fetch:r.fetch}).fetch(a,{method:t.method,headers:o,body:s??null}),n,ye,pj(p),r.receipt)}catch(e){i.push($(`Payment: create credential`,e.message))}else i.push($(`Payment: auto-provision wallet`,`Failed to create and fund testnet wallet`));r.onResults?.(i)}let m=r.interactive,h=process.env.MPPX_STRIPE_SECRET_KEY??uH(n),g=h?.startsWith(`sk_test_`)||h?.startsWith(`rk_test_`),_=new Set([Vx.tempo,Vx.evm,Vx.stripe]);for(let e of l){if(e===p||!_.has(e.method))continue;r.silent||console.log(``);let c=i.length,l=()=>{r.onResults&&i.length>c&&r.onResults(i.slice(c))},u=`Payment [${e.method}]`;try{switch(e.method){case Vx.tempo:case Vx.evm:await gH(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,options:r});break;case Vx.stripe:await _H(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,isStripeTestKey:g??!1,stripeKey:h,options:r})}}finally{l()}}return i}async function gH(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u}=n,d=e.request,f=d.methodDetails,p=DV(d.amount)?BigInt(d.amount):void 0,m=f?.decimals??d.decimals??6,h=d.currency,{plugin:g,method:_}=Lz(e,l?.config);if(!g&&!_){r.push(SV(t,mH(e)));return}let v;if(!_){try{v=await lH()}catch{}if(!v){r.push(SV(t,`no wallet configured. Run "mppx account create" to create one.`));return}}let y;if(e.method===Vx.tempo){let e=f?.chainId??(_?void 0:ve.id);e!==void 0&&(y=e===ye.id?ye:fH(e))}else if(e.method===Vx.evm){let e=f?.chainId;e&&(y=fH(e))}if(p&&h&&!y){r.push(SV(t,`unable to resolve payment chain and verify token decimals`));return}let b;if(p&&h&&y)try{let n;if(e.method===Vx.tempo){let e=await EM(N({chain:y,transport:L()}),h,v??he,{requireDecimals:!0});n=e.balance,m=e.decimals,b=e.symbol}else{let e=await dH(y,h,v);n=e.balance,m=e.decimals,b=e.symbol}if(v&&n<p){let e=pH(p,m),i=pH(n,m),a=b??`tokens`;r.push(SV(t,`insufficient balance (have ${i}, need ${e} ${a} on ${y.name})`,`Fund wallet ${v} with at least ${e} ${a} on ${y.name}.`));return}}catch(e){c&&console.log(X.dim(` Balance check skipped: ${e.message}`)),r.push(SV(t,`unable to verify token balance and decimals from the payment chain`));return}let x=p?pH(p,m):`unknown amount`,S=b??(h?.length===3?h.toUpperCase():``),C=y?.name,w=`${x}${S?` ${S}`:``}${C?` on ${C}`:``}`;if(u.silent||console.log(X.dim(v?` Attempting payment with wallet ${v}`:` Attempting payment with configured method`)),!_&&y?.testnet)u.silent||console.log(X.dim(` Auto-approved: ${w} (testnet)`));else if(!u.yes&&!n.isInteractive){r.push(SV(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${w}`));else if(!await vM(` ${X.yellow(`Pay`)} ${w}. Continue?`,!1)){r.push(SV(t,`declined`));return}let T,E,ee;if(g)try{let t=await g.setup({challenge:e,options:{network:`mainnet`},methodOpts:{}});T=t.methods,E=t.createCredential,ee=t.credentialContext}catch(e){r.push(SV(t,e.message));return}else T=[_];if(_&&pj(e)){let n=!0,u=SH((e,t)=>CV(e,t??{},3e4)),d=jO({methods:[_],polyfill:!1,async onChallenge(n,{createCredential:i}){let a=await Iz(n,l?.config.extensions);Wz(e,n);let o=await i(a);return r.push(Q(`${t}: submitted`)),o},fetch:async(t,r)=>n?(n=!1,new Response(null,{status:402,headers:{[q.wwwAuthenticate]:CS(e)}})):u.fetch(t,r)});try{await bH(r,await d.fetch(i,{method:a.method,headers:o,body:s??null}),c,y,!0,u.receipt)}catch(e){r.push($(t,e.message))}return}let D=await vH(e,T,E,t,r,l?.config.extensions,ee,i);D&&(g?.prepareCredentialRequest?.({challenge:e,credential:D,headers:o}),await yH(r,i,a,D,o,s,c,y,GS(e),pj(e)))}async function _H(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u,stripeKey:d}=n,{plugin:f,method:p}=Lz(e,l?.config);if(!f&&!p){r.push(SV(t,`no Stripe payment method available`));return}let m=!!(f&&!l?.config.plugins?.includes(f)&&n.isStripeTestKey),h=e.request,g=DV(h.amount)?BigInt(h.amount):void 0,_=h.decimals??2,v=h.currency,y=g?pH(g,_):`unknown amount`,b=v?.length===3?v.toUpperCase():``,x=`${y}${b?` ${b}`:``} via Stripe${m?` (testmode)`:``}`;if(m)u.silent||console.log(X.dim(` Attempting: ${x}`));else if(!u.yes&&!n.isInteractive){r.push(SV(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${x}`));else if(!await vM(` ${X.yellow(`Pay`)} ${x}. Continue?`,!1)){r.push(SV(t,`declined`));return}let S,C,w;if(f)try{let t={paymentMethod:`pm_card_visa`};d&&(t.secretKey=d);let n=await f.setup({challenge:e,options:{},methodOpts:t});S=n.methods,C=n.createCredential,w=n.credentialContext}catch(e){r.push(SV(t,e.message));return}else S=[p];let T=await vH(e,S,C,t,r,l?.config.extensions,w,i);if(T){if(f?.prepareCredentialRequest?.({challenge:e,credential:T,headers:o}),m){let n=await CV(i,{method:a.method,headers:{...o,[GS(e)]:T},body:s??null},3e4);n.status>=200&&n.status<300?r.push(Q(`${t}: successful`,`HTTP ${n.status}`)):r.push(SV(`${t}: server is in livemode`,void 0,`Run your server with a Stripe test key to automatically validate Stripe payments in testmode.`));return}await yH(r,i,a,T,o,s,c,void 0,GS(e))}}async function vH(e,t,n,r,i,a,o,s){let c=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:CS(e)}});try{gE(e,new URL(s),void 0);let l=await Iz(e,a,o),u;return u=n?await n(c,l):await jO({methods:t,polyfill:!1}).createCredential(c,l),i.push(Q(`${r}: submitted`)),u}catch(e){let t=e.message;t.toLowerCase().includes(`insufficient`)?i.push(SV(r,`insufficient balance: ${t}`)):i.push($(r,t));return}}async function yH(e,t,n,r,i,a,o,s,c=q.authorization,l=!1){let u;try{u=await CV(t,{method:n.method,headers:{...i,[c]:r},body:a??null},3e4)}catch(t){return e.push($(`Payment: send credential`,t.message)),e}return bH(e,u,o,s,l)}async function bH(e,t,n,r,i=!1,a){if(t.status===402){let n=await t.text().catch(()=>``),r=`Payment rejected`;try{let e=JSON.parse(n);r=e.detail??e.title??r}catch{}return e.push($(`Payment: accepted`,r,`The server rejected a valid credential. Check that your payment verification logic accepts the credential format and that the payment was processed on-chain.`)),e}if(t.status>=400&&t.status<500)e.push(xV(`Payment: post-payment response`,`Got ${t.status}`,`Payment succeeded but the endpoint returned a client error. The endpoint likely requires request body parameters. Use --body to provide them.`));else if(t.status>=500)return e.push($(`Payment: server response`,`Got ${t.status}`,`Payment was accepted but the server errored while generating the response. Check server logs for the underlying error.`)),e;else e.push(Q(`Payment: successful`,`HTTP ${t.status}`));let o=t.headers.get(`content-type`)??``,s=t.headers.get(q.paymentReceipt),c=!s&&i&&pA(t),l=await t.text().catch(()=>``);if(c){let t=a?.(),n=t===void 0?xH(l):t??void 0;n?e.push(Q(`Payment receipt in event stream`,n.reference)):e.push($(`Payment receipt in event stream`,void 0,`SSE session responses without a Payment-Receipt header must end with an "event: payment-receipt" carrying the session receipt.`))}else if(!s)e.push($(`Payment-Receipt header present`,void 0,`After accepting payment, include a Payment-Receipt header with a base64url-encoded JSON object containing: method, reference, status ("success"), and timestamp (ISO 8601).`));else{e.push(Q(`Payment-Receipt header present`));try{let t=Ww(s);if(e.push(Q(`Receipt parseable`)),t.status===`success`?e.push(Q(`Receipt status is "success"`)):e.push($(`Receipt status is "success"`,`Got: ${t.status}`)),t.reference){let n=/^0x[0-9a-fA-F]{64}$/.test(t.reference),r=t.reference.startsWith(`pi_`);n||r?e.push(Q(`Receipt reference valid`,t.reference.slice(0,20)+`...`)):e.push(xV(`Receipt reference format`,t.reference.slice(0,40)))}else e.push(xV(`Receipt has reference`,`No reference field`));if(t.timestamp){let n=new Date(t.timestamp),r=Date.now()-n.getTime();r<6e4?e.push(Q(`Receipt timestamp recent`,`${Math.round(r/1e3)}s ago`)):e.push(xV(`Receipt timestamp recent`,`${Math.round(r/6e4)}m ago`))}n&&console.log(X.dim(` Receipt: ${JSON.stringify(t,null,2)}`))}catch(t){e.push($(`Receipt parseable`,t.message))}}if(l.length>0)e.push(Q(`Response body non-empty`,`${o.split(`;`)[0]}, ${wV(l.length)}`));else{let n=[...t.headers.entries()].filter(([e])=>!e.startsWith(`x-`)&&![`content-type`,`content-length`,`date`,`server`,`connection`,`keep-alive`,`cache-control`,`vary`,`access-control-allow-origin`,`payment-receipt`,`payment-session`,`payment-session-snapshot`].includes(e.toLowerCase()));n.length>0?e.push(xV(`Response body empty -- data may be in headers only`,n.map(([e])=>e).join(`, `))):e.push(xV(`Response body empty`))}if(o?e.push(Q(`Content-Type header set`,o.split(`;`)[0])):e.push(xV(`Content-Type header set`)),s)try{let t=Ww(s);if(t.reference&&/^0x[0-9a-fA-F]{64}$/.test(t.reference)){let n=r?.blockExplorers?.default?.url;if(n){let r=n.includes(`tempo`)?`receipt`:`tx`;e.push(Q(`On-chain transaction`,`${n}/${r}/${t.reference}`))}}}catch{}return e}function xH(e){for(let t of e.replace(/\r\n|\r/g,`
252
+ `):`${a}${l}${i}\n`,d=y.parseEnv;if(d){let t=d(a),i=d(u),o=new Set([...Object.keys(t),...Object.keys(i)]);if(o.delete(n),i[n]!==r||[...o].some(e=>t[e]!==i[e]))throw Error(`could not update ${n} in ${e} safely: edit it by hand`)}t.writeFileSync(e,u)}function yV(e,t,n){let r={};for(let t of[`"`,`'`,"`"]){let n=Array(e.length+1);n[e.length]=-1;for(let r=e.length-1;r>=0;r--)n[r]=bV(e[r],t)?r:n[r+1];r[t]=n}let i=[],a=!1;for(let o=0;o<e.length;o++){let s=o,c=/^[ \t]*[^#=\s][^=]*=[ \t]*(["'`])(.*)$/s.exec(e[o]);if(c&&!bV(c[2],c[1])){let e=r[c[1]][o+1];e!==-1&&(s=e)}let l=t.test(e[o]);if(l&&!a&&i.push(e[o].endsWith(`\r`)?`${n}\r`:n),a||=l,!l)for(let t=o;t<=s;t++)i.push(e[t]);o=s}return{lines:i,found:a}}function bV(e,t){return e.includes(t)}function xV(e){let t=e.findIndex((t,n)=>t===`stripe`&&e[n+1]===`address`);if(t===-1)return[...e];let n=e.slice(0,t+2);for(let r=t+2;r<e.length;r++){let t=e[r];if(n.push(t),t===`--`){n.push(...e.slice(r+1));break}let i=e[r+1];t===`--env`&&(i===void 0||i.startsWith(`-`))&&n.push(`.env`)}return n}DO();function Q(e,t){return t?{label:e,detail:t,severity:`pass`}:{label:e,severity:`pass`}}function $(e,t,n){let r={label:e,severity:`fail`};return t&&(r.detail=t),n&&(r.hint=n),r}function SV(e,t,n){let r={label:e,severity:`warn`};return t&&(r.detail=t),n&&(r.hint=n),r}function CV(e,t,n){let r=t?{label:e,detail:t,severity:`skip`}:{label:e,severity:`skip`};return n&&(r.hint=n),r}async function wV(e,t,n=15e3){let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{let n=globalThis.fetch,i=QD(n),a=XD(n),o={[bO]:!0,...t,redirect:`error`,signal:r.signal};return a?(await a.send((e,t)=>i(e,{...t,[bO]:!0}),new Request(e,o))).response:await i(e,o)}finally{clearTimeout(i)}}function TV(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}const EV=new Set([`get`,`post`,`put`,`patch`,`delete`,`head`,`options`,`trace`]);function DV(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)}function OV(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function kV(e){let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t).toLowerCase();if(!EV.has(n))return null;let r=e.slice(t+1);if(!r)return null;let i=r.startsWith(`/`)?r:`/`+r;return{method:n.toUpperCase(),path:i}}function AV(e,t){if(e){try{let n=JSON.parse(e);if(n&&typeof n==`object`&&!Array.isArray(n)){let e=Object.keys(n);if(e.length>0&&e.every(e=>e.startsWith(`/`))){let e=n[t];return e===void 0?void 0:typeof e==`string`?e:JSON.stringify(e)}}}catch{}return e}}function jV(e){if(!e)return{};let t={};for(let n of e){let e=n.indexOf(`:`);e>0&&(t[n.slice(0,e).trim().toLowerCase()]=n.slice(e+1).trim())}return t}async function MV(e){let t=new URL(`openapi.json`,e.replace(/\/?$/,`/`)).href;try{let e=await wV(t,{});if(!e.ok)return{error:`HTTP ${e.status}`};let n=await e.text();return{doc:JSON.parse(n),raw:n}}catch(e){return e instanceof DOMException&&e.name===`AbortError`?{error:`Request timed out after 15s`}:e instanceof SyntaxError?{error:`Invalid JSON`}:{error:e.message}}}async function NV(e){let t=new URL(`/llms.txt`,e).href,n=`llms.txt found and nonempty`;try{let e=await wV(t,{});if(!e.ok)throw Error(`HTTP ${e.status}`);let r=(await e.text()).trim();if(!r)throw Error(`Empty document`);let i=e.headers.get(`content-type`)?.split(`;`)[0]?.trim().toLowerCase();if(i&&!i.startsWith(`text/`)||i===`text/html`||/^<(?:!doctype html|html|head|body)\b/i.test(r))throw Error(`Expected text documentation, received non-text or HTML content`);return Q(n,t)}catch(e){return{label:n,detail:`${t}: ${e.message}`,severity:`suggested`,hint:`Serve nonempty text documentation at /llms.txt.`}}}function PV(e){let t=[],n=[],r=e.paths;if(!r)return[];for(let[e,i]of Object.entries(r)){let r=LV(i.parameters);for(let[a,o]of Object.entries(i)){if(!EV.has(a)||!o||typeof o!=`object`||Array.isArray(o))continue;let i=o,s=RV(r,LV(i.parameters)),c=s.length>0?s:void 0;if(i[`x-payment-info`]){let n=i[`x-payment-info`];t.push({method:a.toUpperCase(),path:e,amount:n.amount,parameters:c})}else{let t=i.responses;t&&`402`in t&&n.push({method:a.toUpperCase(),path:e,parameters:c})}}}return t.length>0?t:n}function FV(e,t){let n=e.paths;if(!n)return;let r=n[t.path];if(!r)return;let i=r[t.method.toLowerCase()];if(!i?.requestBody)return;let a=i.requestBody.content?.[`application/json`];if(!a)return;if(a.example)return JSON.stringify(a.example);if(a.examples&&typeof a.examples==`object`){let e=Object.values(a.examples)[0];if(e?.value)return JSON.stringify(e.value)}let o=a.schema,s=new Set;if(o=BV(o,e,s),!o||o.type!==`object`)return;let c=VV(o,e,s);if(c&&typeof c==`object`&&Object.keys(c).length>0)return JSON.stringify(c)}function IV(e,t,n){if(!t.path.startsWith(`/`)||t.path.startsWith(`//`)||t.path.includes(`\\`))throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let r=t.path;t.parameters&&(r=zV(r,t.parameters));let i=r.startsWith(`/`)?r.slice(1):r,a=new URL(e.replace(/\/?$/,`/`)),o=new URL(i,a);if(o.origin!==a.origin)throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let s=o.href;if(n){let e=new URL(s);for(let t of n){let[n,...r]=t.split(`=`);n&&e.searchParams.set(n,r.join(`=`))}s=e.href}return s}function LV(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;e.in===`path`&&typeof e.name==`string`&&t.push(e.schema&&typeof e.schema==`object`?{name:e.name,in:`path`,schema:e.schema,example:e.example}:{name:e.name,in:`path`,example:e.example})}return t}function RV(e,t){let n=[...e];for(let e of t){let t=n.findIndex(t=>t.name===e.name);t>=0?n[t]=e:n.push(e)}return n}function zV(e,t){return e.replace(/\{([^}]+)\}/g,(e,n)=>{let r=t.find(e=>e.name===n&&e.in===`path`);if(!r)return e;let i=r.example??r.schema?.example??r.schema?.default;return i===void 0?e:encodeURIComponent(String(i))})}function BV(e,t,n){if(!e||typeof e.$ref!=`string`)return e;if(n?.has(e.$ref))return;let r=e.$ref.replace(/^#\//,``).split(`/`),i=t;for(let e of r)if(i&&typeof i==`object`)i=i[e];else return;return i}function VV(e,t,n){let r=BV(e,t,n)??e;if(r.const!==void 0)return r.const;if(r.example!==void 0)return r.example;if(r.default!==void 0)return r.default;switch(r.type){case`string`:return r.enum&&Array.isArray(r.enum)?r.enum[0]:r.format===`email`?`test@example.com`:r.format===`uuid`?`00000000-0000-0000-0000-000000000000`:r.format===`uri`||r.format===`url`?`https://example.com`:r.format===`date`?`2026-01-01`:r.pattern===`^\\d{5}(?:-\\d{4})?$`?`10001`:r.pattern===`^[A-Z]{2}$`?`US`:`test`;case`number`:case`integer`:return r.minimum??1;case`boolean`:return!0;case`array`:return[];case`object`:{let e=r.properties;if(!e)return{};let i=r.required||[],a={};for(let r of i){let i=e[r];i&&(a[r]=VV(i,t,n))}return a}default:return null}}sC(),Gx(),Qj(),HT();const HV=Object.values(Qe);function UV(e){let t=e.request.methodDetails;return typeof t?.chainId==`number`&&HV.find(e=>e.id===t.chainId)?.testnet===!0}async function WV(e,t,n,r){let i=[],a;try{a=IV(e,t,r?.query)}catch(e){return i.push($(`Request URL valid`,e.message)),{results:i}}let o=jV(r?.extraHeaders),s;r?.body&&!r.bodyIsAutogenerated&&(s=r.body,o[`content-type`]||=`application/json`);let c;try{let e={method:t.method};Object.keys(o).length>0&&(e.headers=o),s&&(e.body=s),c=await wV(a,e)}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}if(!s&&(c.status===400||c.status===422)){let e=r?.body??(r?.discoveryDoc?FV(r.discoveryDoc,t):void 0);if(e){n&&console.log(X.dim(` Retrying with body: ${e}`)),s=e,o[`content-type`]=`application/json`;try{c=await wV(a,{method:t.method,headers:o,body:s})}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}}}if(c.status!==402)return c.status===200?i.push(CV(`Returns 402 without credentials`,`Got 200 (endpoint may not require payment in all cases)`)):c.status===401||c.status===403?i.push(CV(`Returns 402 without credentials`,`Got ${c.status} (endpoint requires auth before payment gate)`)):i.push($(`Returns 402 without credentials`,`Got ${c.status} instead`,c.status===400||c.status===422?`Server requires a valid request body before returning 402. Add a requestBody schema with examples to your OpenAPI doc, or use --body.`:`Endpoints that require payment must return HTTP 402 with a WWW-Authenticate: Payment header when no valid credential is provided.`)),{results:i};i.push(Q(`Returns 402 without credentials`));let l=c.headers.get(q.wwwAuthenticate),u=tH(c);if(!l)return u.length>0?(i.push(CV(`Not an MPP endpoint`,`No WWW-Authenticate header — x402 protocol detected`)),i.push(...u)):i.push(CV(`Not an MPP endpoint`,`No WWW-Authenticate header (may be x402 or other protocol)`)),{results:i};if(u.length>0&&i.push(...u),!l.startsWith(`${Bx.payment} `))return i.push(CV(`Not an MPP endpoint`,`WWW-Authenticate scheme is not Payment`)),{results:i};i.push(Q(`WWW-Authenticate header present`,`Payment scheme`));let d;try{d=RS(c)}catch(e){let t=e.message;i.push($(`Challenge parseable`,t,`The Payment challenge must include a request="<base64url>" parameter containing JSON-encoded payment details.`));let n=l.slice(l.indexOf(` `)+1);return i.push(SV(`Received`,n.length>200?n.slice(0,200)+`...`:n)),{results:i}}if(d.length===0){let e=`No Payment challenges found in header`;try{LS(c)}catch(t){e=t.message}return i.push($(`Challenge parseable`,e)),{results:i}}let f=d.map(e=>`${e.method}/${e.intent}`).join(`, `);i.push(Q(`Challenge parseable`,d.length===1?f:`${d.length} methods: ${f}`));let p=VS(l);p>0&&i.push($(`Challenge credential header`,`${p} of ${d.length+p} challenges select a credential header other than Payment-Authorization`,`A challenge may only set header="Payment-Authorization"; omit header to use Authorization.`));let m=new URL(e).hostname;GV(d,i),KV(d,i),qV(d,i),JV(d,m,i);let h=d.length>1;for(let e of d){let t=e.request;YV(e,t,i,h)}if(n)for(let e of d)console.log(X.dim(` Challenge (${e.method}/${e.intent}): ${JSON.stringify(e,null,2)}`));return{results:i,resolvedBody:s,challenges:d}}function GV(e,t){let n=e.filter(e=>!e.id);n.length===0?t.push(Q(`Challenge has id`)):t.push($(`Challenge has id`,`${n.length} missing`,`Every challenge must include a unique id field.`))}function KV(e,t){let n=e.filter(e=>!e.realm);n.length===0?t.push(Q(`Challenge has realm`)):t.push($(`Challenge has realm`,`${n.length} missing`,`Set realm to your server's hostname.`))}function qV(e,t){let n=new Date;for(let r of e){if(!r.expires){t.push(SV(`Challenge has expiration`,`missing expires field`,`Add an expires field (ISO 8601) to prevent replay attacks.`));return}if(new Date(r.expires)<=n){t.push($(`Challenge expires in the future`,`Expired at ${r.expires}`,`The expires timestamp must be in the future.`));return}}let r=Math.min(...e.map(e=>new Date(e.expires).getTime()-n.getTime()));t.push(Q(`Challenge expires in the future`,`${Math.round(r/6e4)}m from now`))}function JV(e,t,n){let r=e=>e.toLowerCase().replace(/\.$/,``),i=r(t),a=[...new Set(e.map(e=>e.realm??``))].filter(e=>{let t=r(e);return!t||t!==i&&!i.endsWith(`.${t}`)});a.length>0?n.push($(`Realm matches server hostname`,`realm="${a[0]}" vs host="${t}"`,`Set the realm to your production hostname (or base domain) in the challenge.`)):n.push(Q(`Realm matches server hostname`))}function YV(e,t,n,r){let i=r?`[${e.method}] `:``;e.method===Vx.tempo?XV(t,i,n,e):e.method===Vx.stripe?ZV(t,i,n):e.method===Vx.evm&&QV(e,t,i,n)}function XV(e,t,n,r){let i=e.methodDetails,a=Array.isArray(i?.splits)&&i.splits.length>0;if(DV(e.recipient)?n.push(Q(`${t}Valid recipient address`)):e.recipient===void 0&&a?n.push(Q(`${t}Uses splits (no single recipient)`)):e.recipient===void 0?n.push($(`${t}Valid recipient address`,`Missing recipient (and no splits defined)`,`Set request.recipient to a valid 0x address, or use methodDetails.splits for multiple recipients.`)):n.push($(`${t}Valid recipient address`,`Got: ${String(e.recipient)}`,`Set request.recipient to a valid 0x-prefixed 40-hex-char address.`)),DV(e.currency)){let e=UV(r)?`testnet`:`mainnet`;n.push(Q(`${t}Valid currency address`,e))}else n.push($(`${t}Valid currency address`,`Got: ${String(e.currency)}`,`Set request.currency to a valid token address.`));$V(e,t,n,`token's smallest unit (e.g. "10000" = $0.01 for 6-decimal tokens)`)}function ZV(e,t,n){$V(e,t,n,`currency's smallest unit (e.g. "100" = $1.00 for USD)`);let r=e.currency;typeof r==`string`&&/^[a-z]{3}$/i.test(r)?n.push(Q(`${t}Valid currency code`,r.toUpperCase())):n.push($(`${t}Valid currency code`,r?`Got: ${r}`:`missing`,`Must be a three-letter ISO currency code (e.g. "usd").`));let i=e.methodDetails,a=i?.networkId;a?n.push(Q(`${t}Has networkId`,a.slice(0,20))):n.push($(`${t}Has networkId`,`Missing methodDetails.networkId`,`Set methodDetails.networkId to your Stripe Business Network profile ID.`));let o=i?.paymentMethodTypes;Array.isArray(o)&&o.length>0?n.push(Q(`${t}Has paymentMethodTypes`,o.join(`, `))):n.push($(`${t}Has paymentMethodTypes`,`Missing or empty`,`Set methodDetails.paymentMethodTypes to an array (e.g. ["card"]).`))}function QV(e,t,n,r){if(DV(t.recipient)?r.push(Q(`${n}Valid recipient address`)):r.push($(`${n}Valid recipient address`,`Got: ${String(t.recipient)}`,`Set request.recipient to a valid 0x-prefixed Ethereum address.`)),DV(t.currency)){let t=UV(e)?`testnet`:`mainnet`;r.push(Q(`${n}Valid currency address`,t))}else r.push($(`${n}Valid currency address`,`Got: ${String(t.currency)}`,`Set request.currency to a valid ERC-20 token contract address.`));$V(t,n,r,`token's smallest unit`);let i=t.methodDetails?.chainId;typeof i==`number`&&i>0?r.push(Q(`${n}Has chainId`,String(i))):r.push($(`${n}Has chainId`,`Missing methodDetails.chainId`,`Set methodDetails.chainId to the EVM chain ID.`))}function $V(e,t,n,r){OV(e.amount)?n.push(Q(`${t}Amount is valid integer string`)):e.amount===void 0||e.amount===null?n.push($(`${t}Amount is valid integer string`,`Missing amount`,`Set request.amount to a string of digits in the ${r}.`)):n.push($(`${t}Amount is valid integer string`,`Got: ${String(e.amount)}`,`request.amount must be a string of digits (no decimals, no prefix).`))}async function eH(e,t,n){let r=[],i=IV(e,t,n?.query),a=jV(n?.extraHeaders),o=n?.challenge?GS(n.challenge):q.authorization;a[o.toLowerCase()]=`${Bx.payment} dGhpcyBpcyBnYXJiYWdl`;let s;n?.body&&(s=n.body,a[`content-type`]||=`application/json`);try{let e=await wV(i,{method:t.method,headers:a,body:s??null});e.status===402?(r.push(Q(`Malformed credential returns 402`,`not 500`)),e.headers.get(q.wwwAuthenticate)?.startsWith(`${Bx.payment} `)?r.push(Q(`Error response includes fresh challenge`)):r.push(SV(`Error response includes fresh challenge`,`No WWW-Authenticate header`,`When rejecting an invalid credential, respond with 402 and include a fresh WWW-Authenticate: Payment challenge so the client can retry.`))):e.status>=500?r.push($(`Malformed credential returns 402`,`Got ${e.status} (server error)`,`When the ${o} header contains an invalid credential, respond with 402 (not 500). Catch credential validation errors and return a fresh challenge.`)):r.push(SV(`Malformed credential returns 402`,`Got ${e.status}`,`When the ${o} header contains an invalid Payment credential, respond with 402 and a fresh WWW-Authenticate challenge. Returning ${e.status} prevents the client from retrying with a valid payment.`))}catch(e){r.push($(`Error handling test`,e.message))}return r}function tH(e){let t=[],n=e.headers.get(`payment-required`)??e.headers.get(`x-payment-required`);if(!n)return t;let r=e.headers.get(`payment-required`)?`PAYMENT-REQUIRED`:`X-Payment-Required`;try{let e=PT(n);t.push(Q(`x402 payment challenge`,`${r} with valid x402 v${e.x402Version} payload`))}catch{t.push(SV(`x402 payment challenge`,`${r} header present but failed schema validation`,`Ensure the PAYMENT-REQUIRED header contains a valid base64-encoded JSON payload matching the x402 schema.`))}return t}const nH=[`No discovery document found, endpoints could not be automatically found.`,`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,`The MPP SDKs can automatically expose this endpoint. See https://mpp.dev/sdk.`,``,`To test a specific endpoint: mppx validate <url> --endpoint POST:/your/path`].join(`
253
+ `);async function*rH(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n=e.verbose??!1,r=await cH(t,e);yield{phase:`discovery`,discovery:r,results:r.checks};for(let i of r.endpoints){yield{phase:`endpoint`,endpoint:i};let a,o=!1;e.endpoint?a=e.body:(a=AV(e.body,i.path),!a&&r.doc&&(a=FV(r.doc,i),o=!!a));let{results:s,resolvedBody:c,challenges:l}=await WV(t,i,n,{body:a,bodyIsAutogenerated:o,query:e.query,extraHeaders:e.headers,discoveryDoc:r.doc??void 0}),u=c??a,d=s.some(e=>e.severity===`pass`&&e.label===`Challenge parseable`),f=!s.some(e=>e.severity===`fail`),p=(l??[]).filter(e=>e.method!==`stripe`).map(e=>e.request.methodDetails?.chainId).filter(e=>typeof e==`number`),m=p.some(sH),h=p.some(e=>!sH(e)),g=!d&&s.some(e=>e.label===`Not an MPP endpoint`),_=s.some(e=>e.severity===`pass`&&e.label===`WWW-Authenticate header present`),v=s.some(e=>e.severity===`fail`&&e.label===`Challenge parseable`);if(yield{phase:`challenge`,endpoint:i,results:s,isMpp:d,isTestnet:m,isMainnet:h,isNonMppPayment:g,isMalformedChallenge:!d&&_&&v,methods:l?.map(e=>e.method)??[]},d&&(yield{phase:`errorHandling`,endpoint:i,results:await eH(t,i,{body:u,challenge:l?.[0],extraHeaders:e.headers,query:e.query})},!e.skipPayment&&f)){let r=e.onPaymentResults;if(!e.payment){let e=[CV(`Payment: not tested`,`no payment validator configured`,"Run `mppx validate` to test payment, or pass `payment` to validate().")];r?.(e),yield{phase:`payment`,endpoint:i,results:e,succeeded:!1};continue}let a=await e.payment(t,i,n,{body:u,query:e.query,extraHeaders:e.headers,yes:e.yes,silent:!r,interactive:e.interactive,...r&&{onResults:r}}),o=Array.isArray(a)?a:a.results,s=Array.isArray(a)?a.some(e=>e.severity===`pass`&&e.label===`Payment: successful`):a.succeeded;if(!Array.isArray(a)&&!s&&!o.some(e=>e.severity===`fail`)){let e=$(`Payment: failed`,`the payment validator reported that the payment did not succeed`);o=[...o,e],r?.([{...e}])}yield{phase:`payment`,endpoint:i,results:o,succeeded:s}}}}async function iH(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n,r=[],i,a=!1,o=!1;for await(let t of rH(e))switch(t.phase){case`discovery`:n=t.discovery;break;case`endpoint`:i={method:t.endpoint.method,path:t.endpoint.path,challenge:[],errorHandling:[],payment:[]},r.push(i);break;case`challenge`:i&&(i.challenge=t.results),t.isMpp&&(t.isTestnet&&(a=!0),t.isMainnet&&(o=!0));break;case`errorHandling`:i&&(i.errorHandling=t.results);break;case`payment`:i&&(i.payment=t.results,e.payment&&(i.paymentSucceeded=t.succeeded))}let s={passed:0,failed:0,warnings:0,suggested:0,skipped:0};if(n)for(let e of n.checks)e.severity===`pass`?s.passed++:e.severity===`fail`?s.failed++:e.severity===`warn`?s.warnings++:e.severity===`suggested`?s.suggested++:e.severity===`skip`&&s.skipped++;for(let e of r)for(let t of[...e.challenge,...e.errorHandling,...e.payment])t.severity===`pass`?s.passed++:t.severity===`fail`?s.failed++:t.severity===`warn`?s.warnings++:t.severity===`suggested`?s.suggested++:t.severity===`skip`&&s.skipped++;if(!n)throw Error(`Discovery phase did not complete`);let c=aH(r,n,{sawTestnet:a,sawMainnet:o,hasPaymentValidator:!!e.payment});return{url:t,discovery:n,endpoints:r,summary:s,suggestions:c}}function aH(e,t,n){let r=[],i=e.flatMap(e=>[...e.challenge,...e.payment]);t.found||r.push(nH);let a=n.sawMainnet,o=n.sawTestnet,s=i.some(e=>e.label.includes(`[stripe]`)&&e.label.includes(`livemode`));return a&&!o?r.push(n.hasPaymentValidator?`Validate your testnet server to test without real funds (Tempo wallets are automatically provisioned).`:"Validate your testnet server to test without real funds. Run `mppx validate` to test payment with an automatically provisioned Tempo wallet."):o&&!a&&r.push(`Validate your mainnet server to confirm real payments work end-to-end.`),s&&r.push(`Validate your testmode Stripe server to test card payments end-to-end (auto-pays with test card).`),r}const oH=Object.values(Qe);function sH(e){return oH.find(t=>t.id===e)?.testnet===!0}async function cH(e,t){let n=[],r=[],i=null,a=!1,o=!1;n.push(await NV(e));let s=new URL(e).origin,c;t.discoveryPath?c=[new URL(t.discoveryPath,e+`/`).href.replace(/\/openapi\.json$/i,``)]:(c=[e,s,`${s}/api`],c=[...new Set(c)]);let l,u=[];for(let e of c)if(l=await MV(e),`error`in l)u.push(`${e}/openapi.json: ${l.error}`);else break;if(!l||`error`in l)n.push({label:`Document found`,detail:u.join(`; `),hint:`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,severity:`fail`});else{a=!0,n.push({label:`Document found and parseable`,severity:`pass`});let e=dk(l.doc),t=e.filter(e=>e.severity===`error`),r=e.filter(e=>e.severity===`warning`);if(t.length>0){n.push({label:`Valid OpenAPI structure`,detail:`${t.length} error(s)`,severity:`fail`});for(let e of t)n.push({label:e.message,detail:e.path,severity:`fail`})}else o=!0,n.push({label:`Valid OpenAPI structure`,severity:`pass`});for(let e of r)n.push({label:e.message,detail:e.path,severity:`warn`});i=l.doc}if(t.endpoint){let e=kV(t.endpoint);e&&r.push(e)}else if(i){r=PV(i);let e=BigInt(`999999999999999999`);r.sort((t,n)=>{let r=OV(t.amount)?BigInt(t.amount):e,i=OV(n.amount)?BigInt(n.amount):e;return r<i?-1:+(r>i)}),r.length>0?n.push({label:`Paid endpoints found`,detail:`${r.length} endpoint(s)`,severity:`pass`}):n.push({label:`Paid endpoints found`,detail:`No endpoints with x-payment-info`,severity:`warn`})}return{found:a,valid:o,endpoints:r,checks:n,doc:i}}sC(),bE(),Gx(),Jw(),ZR(),aM(),Zj(),CA(),YM(),PM();async function lH(e,t,n){try{n||console.log(X.dim(` Provisioning testnet wallet and funding via faucet...`));let t=ge(),r=R(t),i=N({chain:ye,transport:L()});if(pj(e)){let{chainId:t,operator:n}=e.request.methodDetails??{};if(t===ye.id&&typeof n==`string`&&le(n)&&n!==he){let e=await Be.faucet.fund(i,{account:n});await Promise.all(e.map(e=>Le(i,{hash:e})))}}let a=await Be.faucet.fund(i,{account:r});await Promise.all(a.map(e=>Le(i,{hash:e}))),n||console.log(X.dim(` Using wallet: ${r.address}`));let o=e.request.currency;if(typeof o==`string`)for(let e=0;e<10;e++){let e=await Be.token.getBalance(i,{account:r.address,token:o}).catch(()=>void 0);if(e&&e.amount>0n)break;await new Promise(e=>setTimeout(e,500))}return{methods:[...JR({account:r})]}}catch(e){t&&console.log(X.dim(` Provisioning failed: ${e.message}`));return}}async function uH(){let e=HM(),{isTempoAccount:t}=await Promise.resolve().then(()=>(PM(),oM)),{resolveTempoAccount:n}=await Promise.resolve().then(()=>(jz(),QR));if(t(e)){let t=n(e);if(t)return t.wallet_address}try{return(await KM()).address}catch{return}}function dH(e){try{let{execSync:t}=m,n=t(`stripe config --list`,{encoding:`utf8`,timeout:5e3}).match(/test_mode_api_key\s*=\s*'([^']+)'/);if(n?.[1])return e&&console.log(X.dim(` Using Stripe test key from stripe CLI`)),n[1]}catch{}}async function fH(e,t,n){let r=N({chain:e,transport:L()}),[i,a,o]=await Promise.all([n?je(r,{address:t,abi:F,functionName:`balanceOf`,args:[n]}):0n,je(r,{address:t,abi:F,functionName:`decimals`}),je(r,{address:t,abi:F,functionName:`symbol`}).catch(()=>void 0)]);return{balance:i,decimals:a,symbol:o??void 0}}function pH(e){return Object.values(Qe).find(t=>t.id===e)}function mH(e,t){return`$${(Number(e)/10**t).toFixed(2)}`}function hH(e){switch(e.method){case Vx.evm:return`no EVM payment plugin yet`;case`solana`:return`no Solana payment plugin yet`;default:return`no plugin for ${e.method}/${e.intent}`}}async function gH(e,t,n,r){let i=[],a=IV(e,t,r.query),o=jV(r.extraHeaders),s;r.body&&(s=r.body,o[`content-type`]=`application/json`);let c;try{c=await wV(a,{method:t.method,headers:o,body:s??null})}catch(e){return i.push($(`Payment: fetch challenge`,e.message)),i}if(c.status!==402)return i.push(CV(`Payment: skipped`,`Endpoint returned ${c.status}`)),i;let l;try{l=RS(c)}catch(e){return i.push($(`Payment: parse challenge`,e.message)),i}if(l.length===0)return i.push($(`Payment: parse challenge`,`No Payment challenges in response`)),i;let u=[];JV(l,new URL(a).hostname,u);let d=u.filter(e=>e.severity===`fail`);if(d.length>0)return i.push(...d),r.onResults?.(d),i;let f=await Uz().catch(()=>void 0),p=l.find(e=>{if(e.method!==Vx.tempo||Vz(f?.config)?.some(t=>t.name===e.method&&t.intent===e.intent))return!1;let t=e.request.methodDetails;return typeof t?.chainId==`number`&&t.chainId!==$j.mainnet});if(p){let e=await lH(p,n,r.silent);if(e)try{let r=CH((e,t)=>wV(e,t??{},3e4));await xH(i,await jO({methods:e.methods,polyfill:!1,async onChallenge(e,{createCredential:t}){Gz(p,e);let n=await t(await Lz(e,f?.config.extensions));return i.push(Q(`Payment: submitted`,`ephemeral testnet wallet`)),n},fetch:r.fetch}).fetch(a,{method:t.method,headers:o,body:s??null}),n,ye,pj(p),r.receipt)}catch(e){i.push($(`Payment: create credential`,e.message))}else i.push($(`Payment: auto-provision wallet`,`Failed to create and fund testnet wallet`));r.onResults?.(i)}let m=r.interactive,h=process.env.MPPX_STRIPE_SECRET_KEY??dH(n),g=h?.startsWith(`sk_test_`)||h?.startsWith(`rk_test_`),_=new Set([Vx.tempo,Vx.evm,Vx.stripe]);for(let e of l){if(e===p||!_.has(e.method))continue;r.silent||console.log(``);let c=i.length,l=()=>{r.onResults&&i.length>c&&r.onResults(i.slice(c))},u=`Payment [${e.method}]`;try{switch(e.method){case Vx.tempo:case Vx.evm:await _H(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,options:r});break;case Vx.stripe:await vH(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,isStripeTestKey:g??!1,stripeKey:h,options:r})}}finally{l()}}return i}async function _H(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u}=n,d=e.request,f=d.methodDetails,p=OV(d.amount)?BigInt(d.amount):void 0,m=f?.decimals??d.decimals??6,h=d.currency,{plugin:g,method:_}=Rz(e,l?.config);if(!g&&!_){r.push(CV(t,hH(e)));return}let v;if(!_){try{v=await uH()}catch{}if(!v){r.push(CV(t,`no wallet configured. Run "mppx account create" to create one.`));return}}let y;if(e.method===Vx.tempo){let e=f?.chainId??(_?void 0:ve.id);e!==void 0&&(y=e===ye.id?ye:pH(e))}else if(e.method===Vx.evm){let e=f?.chainId;e&&(y=pH(e))}if(p&&h&&!y){r.push(CV(t,`unable to resolve payment chain and verify token decimals`));return}let b;if(p&&h&&y)try{let n;if(e.method===Vx.tempo){let e=await EM(N({chain:y,transport:L()}),h,v??he,{requireDecimals:!0});n=e.balance,m=e.decimals,b=e.symbol}else{let e=await fH(y,h,v);n=e.balance,m=e.decimals,b=e.symbol}if(v&&n<p){let e=mH(p,m),i=mH(n,m),a=b??`tokens`;r.push(CV(t,`insufficient balance (have ${i}, need ${e} ${a} on ${y.name})`,`Fund wallet ${v} with at least ${e} ${a} on ${y.name}.`));return}}catch(e){c&&console.log(X.dim(` Balance check skipped: ${e.message}`)),r.push(CV(t,`unable to verify token balance and decimals from the payment chain`));return}let x=p?mH(p,m):`unknown amount`,S=b??(h?.length===3?h.toUpperCase():``),C=y?.name,w=`${x}${S?` ${S}`:``}${C?` on ${C}`:``}`;if(u.silent||console.log(X.dim(v?` Attempting payment with wallet ${v}`:` Attempting payment with configured method`)),!_&&y?.testnet)u.silent||console.log(X.dim(` Auto-approved: ${w} (testnet)`));else if(!u.yes&&!n.isInteractive){r.push(CV(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${w}`));else if(!await vM(` ${X.yellow(`Pay`)} ${w}. Continue?`,!1)){r.push(CV(t,`declined`));return}let T,E,ee;if(g)try{let t=await g.setup({challenge:e,options:{network:`mainnet`},methodOpts:{}});T=t.methods,E=t.createCredential,ee=t.credentialContext}catch(e){r.push(CV(t,e.message));return}else T=[_];if(_&&pj(e)){let n=!0,u=CH((e,t)=>wV(e,t??{},3e4)),d=jO({methods:[_],polyfill:!1,async onChallenge(n,{createCredential:i}){let a=await Lz(n,l?.config.extensions);Gz(e,n);let o=await i(a);return r.push(Q(`${t}: submitted`)),o},fetch:async(t,r)=>n?(n=!1,new Response(null,{status:402,headers:{[q.wwwAuthenticate]:CS(e)}})):u.fetch(t,r)});try{await xH(r,await d.fetch(i,{method:a.method,headers:o,body:s??null}),c,y,!0,u.receipt)}catch(e){r.push($(t,e.message))}return}let D=await yH(e,T,E,t,r,l?.config.extensions,ee,i);D&&(g?.prepareCredentialRequest?.({challenge:e,credential:D,headers:o}),await bH(r,i,a,D,o,s,c,y,GS(e),pj(e)))}async function vH(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u,stripeKey:d}=n,{plugin:f,method:p}=Rz(e,l?.config);if(!f&&!p){r.push(CV(t,`no Stripe payment method available`));return}let m=!!(f&&!l?.config.plugins?.includes(f)&&n.isStripeTestKey),h=e.request,g=OV(h.amount)?BigInt(h.amount):void 0,_=h.decimals??2,v=h.currency,y=g?mH(g,_):`unknown amount`,b=v?.length===3?v.toUpperCase():``,x=`${y}${b?` ${b}`:``} via Stripe${m?` (testmode)`:``}`;if(m)u.silent||console.log(X.dim(` Attempting: ${x}`));else if(!u.yes&&!n.isInteractive){r.push(CV(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${x}`));else if(!await vM(` ${X.yellow(`Pay`)} ${x}. Continue?`,!1)){r.push(CV(t,`declined`));return}let S,C,w;if(f)try{let t={paymentMethod:`pm_card_visa`};d&&(t.secretKey=d);let n=await f.setup({challenge:e,options:{},methodOpts:t});S=n.methods,C=n.createCredential,w=n.credentialContext}catch(e){r.push(CV(t,e.message));return}else S=[p];let T=await yH(e,S,C,t,r,l?.config.extensions,w,i);if(T){if(f?.prepareCredentialRequest?.({challenge:e,credential:T,headers:o}),m){let n=await wV(i,{method:a.method,headers:{...o,[GS(e)]:T},body:s??null},3e4);n.status>=200&&n.status<300?r.push(Q(`${t}: successful`,`HTTP ${n.status}`)):r.push(CV(`${t}: server is in livemode`,void 0,`Run your server with a Stripe test key to automatically validate Stripe payments in testmode.`));return}await bH(r,i,a,T,o,s,c,void 0,GS(e))}}async function yH(e,t,n,r,i,a,o,s){let c=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:CS(e)}});try{gE(e,new URL(s),void 0);let l=await Lz(e,a,o),u;return u=n?await n(c,l):await jO({methods:t,polyfill:!1}).createCredential(c,l),i.push(Q(`${r}: submitted`)),u}catch(e){let t=e.message;t.toLowerCase().includes(`insufficient`)?i.push(CV(r,`insufficient balance: ${t}`)):i.push($(r,t));return}}async function bH(e,t,n,r,i,a,o,s,c=q.authorization,l=!1){let u;try{u=await wV(t,{method:n.method,headers:{...i,[c]:r},body:a??null},3e4)}catch(t){return e.push($(`Payment: send credential`,t.message)),e}return xH(e,u,o,s,l)}async function xH(e,t,n,r,i=!1,a){if(t.status===402){let n=await t.text().catch(()=>``),r=`Payment rejected`;try{let e=JSON.parse(n);r=e.detail??e.title??r}catch{}return e.push($(`Payment: accepted`,r,`The server rejected a valid credential. Check that your payment verification logic accepts the credential format and that the payment was processed on-chain.`)),e}if(t.status>=400&&t.status<500)e.push(SV(`Payment: post-payment response`,`Got ${t.status}`,`Payment succeeded but the endpoint returned a client error. The endpoint likely requires request body parameters. Use --body to provide them.`));else if(t.status>=500)return e.push($(`Payment: server response`,`Got ${t.status}`,`Payment was accepted but the server errored while generating the response. Check server logs for the underlying error.`)),e;else e.push(Q(`Payment: successful`,`HTTP ${t.status}`));let o=t.headers.get(`content-type`)??``,s=t.headers.get(q.paymentReceipt),c=!s&&i&&pA(t),l=await t.text().catch(()=>``);if(c){let t=a?.(),n=t===void 0?SH(l):t??void 0;n?e.push(Q(`Payment receipt in event stream`,n.reference)):e.push($(`Payment receipt in event stream`,void 0,`SSE session responses without a Payment-Receipt header must end with an "event: payment-receipt" carrying the session receipt.`))}else if(!s)e.push($(`Payment-Receipt header present`,void 0,`After accepting payment, include a Payment-Receipt header with a base64url-encoded JSON object containing: method, reference, status ("success"), and timestamp (ISO 8601).`));else{e.push(Q(`Payment-Receipt header present`));try{let t=Ww(s);if(e.push(Q(`Receipt parseable`)),t.status===`success`?e.push(Q(`Receipt status is "success"`)):e.push($(`Receipt status is "success"`,`Got: ${t.status}`)),t.reference){let n=/^0x[0-9a-fA-F]{64}$/.test(t.reference),r=t.reference.startsWith(`pi_`);n||r?e.push(Q(`Receipt reference valid`,t.reference.slice(0,20)+`...`)):e.push(SV(`Receipt reference format`,t.reference.slice(0,40)))}else e.push(SV(`Receipt has reference`,`No reference field`));if(t.timestamp){let n=new Date(t.timestamp),r=Date.now()-n.getTime();r<6e4?e.push(Q(`Receipt timestamp recent`,`${Math.round(r/1e3)}s ago`)):e.push(SV(`Receipt timestamp recent`,`${Math.round(r/6e4)}m ago`))}n&&console.log(X.dim(` Receipt: ${JSON.stringify(t,null,2)}`))}catch(t){e.push($(`Receipt parseable`,t.message))}}if(l.length>0)e.push(Q(`Response body non-empty`,`${o.split(`;`)[0]}, ${TV(l.length)}`));else{let n=[...t.headers.entries()].filter(([e])=>!e.startsWith(`x-`)&&![`content-type`,`content-length`,`date`,`server`,`connection`,`keep-alive`,`cache-control`,`vary`,`access-control-allow-origin`,`payment-receipt`,`payment-session`,`payment-session-snapshot`].includes(e.toLowerCase()));n.length>0?e.push(SV(`Response body empty -- data may be in headers only`,n.map(([e])=>e).join(`, `))):e.push(SV(`Response body empty`))}if(o?e.push(Q(`Content-Type header set`,o.split(`;`)[0])):e.push(SV(`Content-Type header set`)),s)try{let t=Ww(s);if(t.reference&&/^0x[0-9a-fA-F]{64}$/.test(t.reference)){let n=r?.blockExplorers?.default?.url;if(n){let r=n.includes(`tempo`)?`receipt`:`tx`;e.push(Q(`On-chain transaction`,`${n}/${r}/${t.reference}`))}}}catch{}return e}function SH(e){for(let t of e.replace(/\r\n|\r/g,`
254
254
  `).split(`
255
255
 
256
- `)){let e=mA(t);if(e?.type===`payment-receipt`)return e.data}}function SH(e){let t;return{async fetch(n,r){let i=await e(n,r);if(!i.body||!pA(i)||i.headers.get(q.paymentReceipt))return i;t??=null;let a=new TextDecoder,o=[],s=0,c=!1,l=!1,u=(e,n)=>{let r=c?`\r${e}`:e;c=!n&&r.endsWith(`\r`),c&&(r=r.slice(0,-1));let i=r.replace(/\r\n|\r/g,`
256
+ `)){let e=mA(t);if(e?.type===`payment-receipt`)return e.data}}function CH(e){let t;return{async fetch(n,r){let i=await e(n,r);if(!i.body||!pA(i)||i.headers.get(q.paymentReceipt))return i;t??=null;let a=new TextDecoder,o=[],s=0,c=!1,l=!1,u=(e,n)=>{let r=c?`\r${e}`:e;c=!n&&r.endsWith(`\r`),c&&(r=r.slice(0,-1));let i=r.replace(/\r\n|\r/g,`
257
257
  `),a=[];i.startsWith(`
258
258
  `)&&o.at(-1)?.endsWith(`
259
259
  `)&&(a.push(o.join(``).slice(0,-1)),o=[],s=0,i=i.slice(1));for(let e=i.indexOf(`
@@ -262,18 +262,18 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
262
262
 
263
263
  `))a.push(o.join(``)+i.slice(0,e)),o=[],s=0,i=i.slice(e+2);i&&(o.push(i),s+=i.length),n&&(a.push(o.join(``)),o=[],s=0),l&&a.length>0&&(a.shift(),l=!1),s>1048576&&(o=o.at(-1)?.endsWith(`
264
264
  `)?[`
265
- `]:[],s=o.length,l=!0);for(let e of a){let n=mA(e);n?.type===`payment-receipt`&&!t&&(t=n.data)}},d=i.body.pipeThrough(new TransformStream({transform(e,t){u(a.decode(e,{stream:!0}),!1),t.enqueue(e)},flush(){u(a.decode(),!0)}})),f=new Response(d,{headers:i.headers,status:i.status,statusText:i.statusText});return Object.defineProperty(f,"url",{value:i.url}),f},receipt:()=>t}}PM();const CH={pass:X.green(`✓`),fail:X.red(`✗`),warn:X.yellow(`⚠`),suggested:X.cyan(`◇`),skip:X.dim(`○`)};function wH(e){let t=CH[e.severity],n=e.detail?`${e.label} (${e.detail})`:e.label;console.log(` ${t} ${n}`),e.hint&&e.severity!==`pass`&&console.log(X.dim(` → ${e.hint}`))}function TH(e){console.log(`\n${X.bold(e)}`)}function EH(e,t){for(let n of e)wH(n),n.severity===`pass`?t.passed++:n.severity===`fail`?t.failed++:n.severity===`warn`?t.warnings++:n.severity===`suggested`?t.suggested++:n.severity===`skip`&&t.skipped++}Rx(),PM();const DH=vb(`validate`,{description:`Validate an MPP server implementation end-to-end`,args:p.object({url:p.string().describe(`Base URL of the MPP server to validate`)}),options:p.object({endpoint:p.string().optional().describe(`Endpoint to test (METHOD:path). Skips discovery.`),body:p.string().optional().describe(`Request body. With --endpoint, used directly. In discovery mode, JSON with / keys is a per-path mapping.`),query:p.array(p.string()).optional().describe(`Query parameter (key=value, repeatable)`),header:p.array(p.string()).optional().describe(`Request header (key:value, repeatable)`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity level`),yes:p.boolean().default(!1).describe(`Auto-approve mainnet payments`),outputJson:p.boolean().default(!1).describe(`Output results as JSON (auto-enabled in known agent environments)`)}),alias:{endpoint:`e`,header:`H`,verbose:`v`,yes:`y`,outputJson:`j`},async run(e){if(e.options.outputJson||hM()){let t=await rH({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!1,payment:hH});console.log(JSON.stringify(t,null,2));let n=t.endpoints.length===0&&!e.options.endpoint;(t.summary.failed>0||!t.discovery.found||n)&&process.exit(1);return}let t=e.args.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``);console.log(`\n${X.bold(`mppx validate`)} ${X.dim(t)}\n`);let n={passed:0,failed:0,warnings:0,suggested:0,skipped:0},r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=0;for await(let t of nH({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!!process.stdin.isTTY,onPaymentResults:e=>EH(e,n),payment:hH}))switch(t.phase){case`discovery`:if(TH(`Discovery (/openapi.json)`),EH(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=tH.split(`
266
- `);console.log(X.yellow(` ${e}`));for(let e of t)console.log(e?X.dim(` ${e}`):``);console.log(``),process.exit(1)}t.discovery.endpoints.length===0&&!e.options.endpoint&&l&&(console.log(X.dim(` Use --endpoint to specify endpoints manually.`)),console.log(``),process.exit(1));break;case`endpoint`:u++,TH(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),EH(t.results,n),t.isMpp&&(r=!0,t.isTestnet&&(o=!0),t.isMainnet&&(s=!0)),t.isNonMppPayment&&(i=!0),t.isMalformedChallenge&&(a=!0);break;case`errorHandling`:console.log(X.dim(` Error Handling`)),EH(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}OH(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function OH(e,t,n){!t.sawMppEndpoint&&n>0&&(console.log(``),t.sawMalformedChallenge?(console.log(X.yellow(` Payment scheme detected but challenge format is invalid on ${n} endpoint(s).`)),console.log(X.dim(` The server uses WWW-Authenticate: Payment but the challenge parameters do not conform to MPP.`)),console.log(X.dim(` Fix: encode payment details as base64url JSON in a request="..." parameter. See errors above.`))):t.sawNonMppPaymentEndpoint?(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))):e.skipped>0&&e.failed===0?(console.log(X.yellow(` Could not reach payment gate on any endpoint (all returned 401/403/200).`)),console.log(X.dim(` The server may require authentication before payment. Try providing auth or use --endpoint with a public path.`))):(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))),console.log(``),process.exit(1)),console.log(``);let r=[];e.passed>0&&r.push(X.green(`${e.passed} passed`)),e.failed>0&&r.push(X.red(`${e.failed} failed`)),e.warnings>0&&r.push(X.yellow(`${e.warnings} warning(s)`)),e.suggested>0&&r.push(X.cyan(`${e.suggested} suggested`)),e.skipped>0&&r.push(X.yellow(`${e.skipped} skipped`)),console.log(`${X.bold(`Summary:`)} ${r.join(`, `)}`),t.paymentSucceeded&&t.sawTestnet&&!t.sawMainnet?(console.log(``),console.log(X.dim(` Tip: also validate your mainnet server to confirm real payments work end-to-end.`))):t.sawMainnet&&!t.sawTestnet&&(console.log(``),console.log(X.dim(` Tip: also validate your testnet server for free. This CLI automatically provisions and funds a testnet wallet for testing.`))),console.log(``),e.failed>0&&process.exit(1)}function kH(e){return jH(e)?e.offers:[e]}function AH(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=MH(t.amount)??MH(i.amount)??null,o=MH(t.currency)??MH(i.currency),s=MH(e.description)??MH(t.description),c={amount:a,...o?{currency:o}:{},...s?{description:s}:{},intent:n,method:r},l=new Set([`amount`,`currency`,`description`,`methodDetails`]);for(let[e,n]of Object.entries(t))!l.has(e)&&n!==void 0&&(c[e]=n);return c}function jH(e){return`offers`in e&&!(`_canonicalRequest`in e)}function MH(e){return typeof e==`string`?e:void 0}var NH=z((()=>{})),PH=it({generate:()=>FH,generateProxy:()=>IH});function FH(e,t){let n=e.methods,r=new Map,i={};for(let e of n)r.set(`${e.name}/${e.intent}`,e),i[e.intent]=(i[e.intent]??0)+1;for(let e of n)i[e.intent]===1&&r.set(e.intent,e);let a=t.routes.map(e=>RH(e,r));return LH({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function IH(e){let t=e.routes.map(t=>({...t,path:zH(e.basePath,t.path)}));return LH({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function LH(e){let t={};for(let n of e.routes){let e=n.method.toLowerCase(),r={responses:{...n.payment?{402:{description:`Payment Required`}}:{},200:{description:`Successful response`}}};n.payment&&(r[`x-payment-info`]=ik.parse(n.payment)),n.summary&&(r.summary=n.summary),n.requestBody&&(r.requestBody=n.requestBody),t[n.path]||(t[n.path]={}),t[n.path][e]=r}let n={info:e.info,openapi:`3.1.0`,paths:t};return e.serviceInfo&&(n[`x-service-info`]=e.serviceInfo),n}function RH(e,t){if(`handler`in e){let t=e.handler._internal;if(!t)throw Error(`Route ${e.method.toUpperCase()} ${e.path} is missing discovery metadata`);return{method:e.method,path:e.path,payment:{offers:kH(t).map(AH)},...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}let n=t.get(e.intent);if(!n)throw Error(`Unknown intent "${e.intent}" for route ${e.method.toUpperCase()} ${e.path}. Available: ${[...t.keys()].join(`, `)}`);let{description:r,...i}=e.options,a={_canonicalRequest:sS(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:AH(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function zH(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var BH=z((()=>{lS(),uk(),NH()}));Rx(),sC(),DO(),bE(),AT(),WT(),qT(),Gx(),aS(),ZC(),HT(),Uw(),Zj(),JM(),PM();const VH=`0.22.0`,HH=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),UH=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),WH=p.object({message:p.string(),path:p.string(),severity:p.string()}),GH=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),KH=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function qH(e){return e.format===`json`&&e.formatExplicit}function JH(e,t,n){if(qH(e))return e.ok(t);n()}async function YH(t){if(!t.body)return;let n=t.body.getReader();try{for(;;){let{done:t,value:r}=await n.read();if(t)break;process.stdout.write(Buffer.from(r))||await e(process.stdout,`drain`)}}finally{n.releaseLock()}}function XH(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function ZH(e){return typeof e==`string`?e:void 0}function QH(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function $H(e){let t=QH(e);return{...ZH(e.description)?{description:ZH(e.description)}:{},id:ZH(e.id)??ZH(e.name)??`unknown`,...ZH(e.name)?{name:ZH(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...ZH(e.status)?{status:ZH(e.status)}:{},...ZH(e.serviceUrl)||ZH(e.url)?{url:ZH(e.serviceUrl)??ZH(e.url)}:{}}}function eU(e){return{...ZH(e.description)?{description:ZH(e.description)}:{},method:ZH(e.method)??`GET`,path:ZH(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function tU(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=ZH(t.amount),r=ZH(t.currency),i=ZH(t.method),a=ZH(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function nU(e){return e.request.currency??e.request.asset}function rU(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=nU(e);return typeof t==`string`&&t.toLowerCase()===n})}async function iU(e,t,n={}){let r=()=>DT().getChallenges(e),i=()=>UT().getChallenges(n.ignoreX402ResponseUrl?new Response(null,{headers:e.headers,status:e.status}):e);if(t===`mpp`)return r();if(t===`x402`)return i();let a=[],o;try{a=await r()}catch(e){o=e}let s=[],c;try{s=await i()}catch(e){c=e}if(a.length||s.length)return[...a,...s];if(o)throw o;if(c)throw c;return[]}async function aU(e,t){let n=[],r=0,i=e.body?.getReader(),a=!0;if(i)for(;;){let{done:e,value:o}=await i.read();if(e)break;if(n.push(o),r+=o.byteLength,r>t){a=!1;break}}let o=a?i?new Blob(n):null:new ReadableStream({start(e){for(let t of n)e.enqueue(t)},async pull(e){let{done:t,value:n}=await i.read();t?e.close():e.enqueue(n)},cancel(e){return i.cancel(e)}}),s=new Response(o,{headers:e.headers,status:e.status,statusText:e.statusText});return Object.defineProperty(s,"url",{value:e.url}),{complete:a,response:s}}function oU(e){if(!YC(e))return`mpp:${e.id}`;let{description:t,id:n,request:r,...i}=e,{description:a,...o}=r.resource??{};return`x402:${CS({...i,id:``,request:{...r,...r.resource?{resource:o}:{}}})}`}function sU(e,t){if(!e||!t)return!0;try{return new URL(e).origin===new URL(t).origin}catch{return!1}}async function cU(e,t){return Rz(rU(await iU(e,t.protocol,{ignoreX402ResponseUrl:t.ignoreX402ResponseUrl}).catch(()=>[]),t.currency),t.config)!==void 0}function lU(e){return GT({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function uU(e,t){if(!YC(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:CS(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[ww]:RT({accepts:[yw(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function dU(e){let{host:t,hostname:n,protocol:r}=new URL(e);return r===`https:`||!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function fU(e,t,n,r){let i=!1,a=t,o=dU(a),s={...n,redirect:`manual`,headers:OD(n.headers)};o.host&&gU(s.headers,o.host);for(let t=0;t<=20;t++){let{protocol:n,hostname:c}=new URL(o.url),l=[`localhost`,`127.0.0.1`,`[::1]`].includes(c);i||=n!==`https:`&&!(n===`http:`&&l);let u=await e(o.url,s),d=u.headers.get(`location`);if(!r||!d||![301,302,303,307,308].includes(u.status))return{insecureTransport:i,init:s,logicalUrl:a,response:u,target:o};if(t===20)throw TypeError(`Too many redirects`);await u.body?.cancel().catch(()=>{});let f=new URL(d,a),p=new URL(a),m=OD(s.headers);if(f.origin!==p.origin)for(let e of[`authorization`,`cookie`,`host`,`proxy-authorization`])for(let t of Object.keys(m))t.toLowerCase()===e&&delete m[t];let h=(s.method??(s.body?`POST`:`GET`)).toUpperCase(),g=u.status===303&&h!==`GET`&&h!==`HEAD`||(u.status===301||u.status===302)&&h===`POST`;if(g)for(let e of[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`])for(let t of Object.keys(m))t.toLowerCase()===e&&delete m[t];a=f.href,o=dU(a),o.host&&gU(m,o.host);let _={...s};g&&(delete _.body,_.method=`GET`),s={..._,headers:m,redirect:`manual`}}throw TypeError(`Too many redirects`)}function pU(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&hU(i),dU(i.href)}function mU(e,t){let n=new URL(e),r=new URL(t||e),i=new URL(dU(e).url);return r.origin!==n.origin&&r.origin!==i.origin&&hU(r),dU(r.href)}function hU(e){throw new B({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function gU(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function _U(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function vU(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new B({code:`SERVICES_FETCH_FAILED`,message:`Failed to fetch services registry: HTTP ${t.status}`,exitCode:1});let n=await t.json();if(!n||typeof n!=`object`||!Array.isArray(n.services))throw new B({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function yU(e,t){let n=t.toLowerCase();return e.find(e=>{let t=ZH(e.id)?.toLowerCase(),r=ZH(e.name)?.toLowerCase();return t===n||r===n})}const bU=vb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:VH,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:p.object({url:p.string().describe(`URL to make request to`)}),options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:p.string().optional().describe(`Path to config file`),confirm:p.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:p.string().optional().describe(`Payment currency/token address to select`),data:p.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:p.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:p.array(p.string()).optional().describe(`Add header (repeatable)`),include:p.boolean().optional().describe(`Include response headers in output`),insecure:p.boolean().optional().describe(`Skip TLS certificate verification (disables payment retries)`),jsonBody:p.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:p.boolean().optional().describe(`Follow redirects`),method:p.string().optional().describe(`HTTP method`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),protocol:p.enum([`auto`,`mpp`,`x402`]).default(`auto`).describe(`Payment protocol to use`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:p.string().optional().default(`auto`).refine(e=>e===`auto`||e===`new`||/^0x[0-9a-fA-F]{64}$/.test(e),`Expected auto, new, or a 32-byte channel ID`).describe(`Session selection: auto, new, or channel ID`),silent:p.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:p.string().optional().describe(`Set User-Agent header`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity (-v details, -vv headers)`)}),alias:{account:`a`,config:`c`,data:`d`,fail:`f`,header:`H`,include:`i`,insecure:`k`,jsonBody:`J`,location:`L`,method:`X`,methodOpt:`M`,rpcUrl:`r`,silent:`s`,userAgent:`A`,verbose:`v`},examples:[{args:{url:`mpp.dev/api/ping/paid`},description:`Make a payment request`}],async run(e){let t=e.options.silent?e=>{}:e=>process.stderr.write(e),n=await Hz(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=XM(),i={"User-Agent":e.options.userAgent??`mppx/${VH}${r?` AIAgent/${r}`:``}`};if(e.options.header)for(let t of e.options.header){let n=t.indexOf(`:`);if(n===-1)return e.error({code:`INVALID_HEADER`,message:`Invalid header format: ${t}`,exitCode:2});i[t.slice(0,n).trim()]=t.slice(n+1).trim()}let a=zz(n?.config);a&&!Object.keys(i).some(e=>e.toLowerCase()===`accept-payment`)&&(i[`Accept-Payment`]=a);let o=(()=>{let t=/^https?:\/\//.test(e.args.url),n=/^(localhost|.*\.localhost|127\.0\.0\.1|\[::1\])(:\d+)?/.test(e.args.url);return t?e.args.url:`${n?`http`:`https`}://${e.args.url}`})(),{hostname:s}=new URL(o),l=e.options.insecure??!1,u=l?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,d=dU(o),f=d.url;d.host&&(i.Host=d.host);try{let r=mM(e.options.methodOpt),a=oB(),s={redirect:e.options.location?`follow`:`manual`};e.options.jsonBody?(s.body=e.options.jsonBody,i[`Content-Type`]??=`application/json`,i.Accept??=`application/json`):e.options.data&&(s.body=e.options.data),e.options.method?s.method=e.options.method.toUpperCase():s.body&&(s.method=`POST`),Object.keys(i).length>0&&(s.headers=i);let c={include:e.options.include??!1,verbose:e.options.verbose,silent:e.options.silent};e.options.verbose>=2&&sM(o,s,t);let p=await fU(u,o,s,e.options.location??!1),m=p.response;if((l||p.insecureTransport)&&m.status===402)return e.error({code:`INSECURE_PAYMENT`,message:`Payment requires verified HTTPS (except loopback HTTP). Use HTTPS and omit --insecure.`,exitCode:2});if(m.status!==402){if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});if(e.options.fail&&m.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${m.status}`,exitCode:22});cM(m,c),await YH(m);return}let h;for(let i=0;;i++){let l=m.url?new URL(m.url):void 0,g=d.host!==void 0&&l?.hostname===`127.0.0.1`,_=await iU(m,e.options.protocol,{ignoreX402ResponseUrl:g});if(_.length===0)return e.error({code:`UNSUPPORTED_PROTOCOL`,message:e.options.protocol===`auto`?`Server did not offer a payment challenge.`:`Server did not offer an ${e.options.protocol} payment challenge.`,exitCode:2});let v=rU(_,e.options.currency);if(e.options.currency&&v.length===0){let t=_.map(nU).filter(e=>typeof e==`string`).join(`, `);return e.error({code:`UNSUPPORTED_CURRENCY`,message:`Server did not offer payment currency ${e.options.currency}.${t?` Offered currencies: ${t}.`:``}`,exitCode:2})}let y=Bz(n?.config)?.length?v:await $R(v,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),b=h?y.findIndex(e=>oU(e)===h.key):-1;b>0&&y.unshift(...y.splice(b,1));let x=Rz(y,n?.config);if(!x){let t=y.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:S,plugin:C,method:w}=x,T=YC(S),E=T?mU(p.logicalUrl,(_U(S)??m.url)||p.logicalUrl):pU(o,d,p.logicalUrl);if(!T)try{gE(S,new URL(p.logicalUrl||o),void 0)}catch(t){return e.error({code:`UNTRUSTED_PROOF_REALM`,message:t.message,exitCode:1})}let ee=uU(S,m),D=S.request.currency??``,O=S.request.decimals??6,k,A;C&&(A=await C.setup({challenge:S,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),D=A.tokenSymbol,O=A.tokenDecimals,k=A.explorerUrl);let j=!e.options.silent&&e.options.confirm,M=new Set;{cM(m,S.method===`tempo`&&S.intent===`session`&&e.options.include?{...c,include:!1,verbose:Math.max(c.verbose,2)}:c);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(S))e.has(n)||r===void 0||t.push([n,dM(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:D,tokenDecimals:O,explorerUrl:k},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(S.request))e.has(n)||i===void 0||t.push([n,lM(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=S.request.methodDetails;if(!e)return[];let t=[];for(let[n,i]of Object.entries(e))if(i!==void 0){if(n===`memo`&&typeof i==`string`){let e=uM(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,lM(n,i,r)])}return t.sort(([e],[t])=>e.localeCompare(t))})(),o=[[`Challenge`,n],[`Request`,i],...a.length?[[`Details`,a]]:[]];for(let[,e]of o)for(let[t]of e)M.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||j){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
265
+ `]:[],s=o.length,l=!0);for(let e of a){let n=mA(e);n?.type===`payment-receipt`&&!t&&(t=n.data)}},d=i.body.pipeThrough(new TransformStream({transform(e,t){u(a.decode(e,{stream:!0}),!1),t.enqueue(e)},flush(){u(a.decode(),!0)}})),f=new Response(d,{headers:i.headers,status:i.status,statusText:i.statusText});return Object.defineProperty(f,"url",{value:i.url}),f},receipt:()=>t}}PM();const wH={pass:X.green(`✓`),fail:X.red(`✗`),warn:X.yellow(`⚠`),suggested:X.cyan(`◇`),skip:X.dim(`○`)};function TH(e){let t=wH[e.severity],n=e.detail?`${e.label} (${e.detail})`:e.label;console.log(` ${t} ${n}`),e.hint&&e.severity!==`pass`&&console.log(X.dim(` → ${e.hint}`))}function EH(e){console.log(`\n${X.bold(e)}`)}function DH(e,t){for(let n of e)TH(n),n.severity===`pass`?t.passed++:n.severity===`fail`?t.failed++:n.severity===`warn`?t.warnings++:n.severity===`suggested`?t.suggested++:n.severity===`skip`&&t.skipped++}Rx(),PM();const OH=vb(`validate`,{description:`Validate an MPP server implementation end-to-end`,args:p.object({url:p.string().describe(`Base URL of the MPP server to validate`)}),options:p.object({endpoint:p.string().optional().describe(`Endpoint to test (METHOD:path). Skips discovery.`),body:p.string().optional().describe(`Request body. With --endpoint, used directly. In discovery mode, JSON with / keys is a per-path mapping.`),query:p.array(p.string()).optional().describe(`Query parameter (key=value, repeatable)`),header:p.array(p.string()).optional().describe(`Request header (key:value, repeatable)`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity level`),yes:p.boolean().default(!1).describe(`Auto-approve mainnet payments`),outputJson:p.boolean().default(!1).describe(`Output results as JSON (auto-enabled in known agent environments)`)}),alias:{endpoint:`e`,header:`H`,verbose:`v`,yes:`y`,outputJson:`j`},async run(e){if(e.options.outputJson||hM()){let t=await iH({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!1,payment:gH});console.log(JSON.stringify(t,null,2));let n=t.endpoints.length===0&&!e.options.endpoint;(t.summary.failed>0||!t.discovery.found||n)&&process.exit(1);return}let t=e.args.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``);console.log(`\n${X.bold(`mppx validate`)} ${X.dim(t)}\n`);let n={passed:0,failed:0,warnings:0,suggested:0,skipped:0},r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=0;for await(let t of rH({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!!process.stdin.isTTY,onPaymentResults:e=>DH(e,n),payment:gH}))switch(t.phase){case`discovery`:if(EH(`Discovery (/openapi.json)`),DH(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=nH.split(`
266
+ `);console.log(X.yellow(` ${e}`));for(let e of t)console.log(e?X.dim(` ${e}`):``);console.log(``),process.exit(1)}t.discovery.endpoints.length===0&&!e.options.endpoint&&l&&(console.log(X.dim(` Use --endpoint to specify endpoints manually.`)),console.log(``),process.exit(1));break;case`endpoint`:u++,EH(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),DH(t.results,n),t.isMpp&&(r=!0,t.isTestnet&&(o=!0),t.isMainnet&&(s=!0)),t.isNonMppPayment&&(i=!0),t.isMalformedChallenge&&(a=!0);break;case`errorHandling`:console.log(X.dim(` Error Handling`)),DH(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}kH(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function kH(e,t,n){!t.sawMppEndpoint&&n>0&&(console.log(``),t.sawMalformedChallenge?(console.log(X.yellow(` Payment scheme detected but challenge format is invalid on ${n} endpoint(s).`)),console.log(X.dim(` The server uses WWW-Authenticate: Payment but the challenge parameters do not conform to MPP.`)),console.log(X.dim(` Fix: encode payment details as base64url JSON in a request="..." parameter. See errors above.`))):t.sawNonMppPaymentEndpoint?(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))):e.skipped>0&&e.failed===0?(console.log(X.yellow(` Could not reach payment gate on any endpoint (all returned 401/403/200).`)),console.log(X.dim(` The server may require authentication before payment. Try providing auth or use --endpoint with a public path.`))):(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))),console.log(``),process.exit(1)),console.log(``);let r=[];e.passed>0&&r.push(X.green(`${e.passed} passed`)),e.failed>0&&r.push(X.red(`${e.failed} failed`)),e.warnings>0&&r.push(X.yellow(`${e.warnings} warning(s)`)),e.suggested>0&&r.push(X.cyan(`${e.suggested} suggested`)),e.skipped>0&&r.push(X.yellow(`${e.skipped} skipped`)),console.log(`${X.bold(`Summary:`)} ${r.join(`, `)}`),t.paymentSucceeded&&t.sawTestnet&&!t.sawMainnet?(console.log(``),console.log(X.dim(` Tip: also validate your mainnet server to confirm real payments work end-to-end.`))):t.sawMainnet&&!t.sawTestnet&&(console.log(``),console.log(X.dim(` Tip: also validate your testnet server for free. This CLI automatically provisions and funds a testnet wallet for testing.`))),console.log(``),e.failed>0&&process.exit(1)}function AH(e){return MH(e)?e.offers:[e]}function jH(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=NH(t.amount)??NH(i.amount)??null,o=NH(t.currency)??NH(i.currency),s=NH(e.description)??NH(t.description),c={amount:a,...o?{currency:o}:{},...s?{description:s}:{},intent:n,method:r},l=new Set([`amount`,`currency`,`description`,`methodDetails`]);for(let[e,n]of Object.entries(t))!l.has(e)&&n!==void 0&&(c[e]=n);return c}function MH(e){return`offers`in e&&!(`_canonicalRequest`in e)}function NH(e){return typeof e==`string`?e:void 0}var PH=z((()=>{})),FH=it({generate:()=>IH,generateProxy:()=>LH});function IH(e,t){let n=e.methods,r=new Map,i={};for(let e of n)r.set(`${e.name}/${e.intent}`,e),i[e.intent]=(i[e.intent]??0)+1;for(let e of n)i[e.intent]===1&&r.set(e.intent,e);let a=t.routes.map(e=>zH(e,r));return RH({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function LH(e){let t=e.routes.map(t=>({...t,path:BH(e.basePath,t.path)}));return RH({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function RH(e){let t={};for(let n of e.routes){let e=n.method.toLowerCase(),r={responses:{...n.payment?{402:{description:`Payment Required`}}:{},200:{description:`Successful response`}}};n.payment&&(r[`x-payment-info`]=ik.parse(n.payment)),n.summary&&(r.summary=n.summary),n.requestBody&&(r.requestBody=n.requestBody),t[n.path]||(t[n.path]={}),t[n.path][e]=r}let n={info:e.info,openapi:`3.1.0`,paths:t};return e.serviceInfo&&(n[`x-service-info`]=e.serviceInfo),n}function zH(e,t){if(`handler`in e){let t=e.handler._internal;if(!t)throw Error(`Route ${e.method.toUpperCase()} ${e.path} is missing discovery metadata`);return{method:e.method,path:e.path,payment:{offers:AH(t).map(jH)},...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}let n=t.get(e.intent);if(!n)throw Error(`Unknown intent "${e.intent}" for route ${e.method.toUpperCase()} ${e.path}. Available: ${[...t.keys()].join(`, `)}`);let{description:r,...i}=e.options,a={_canonicalRequest:sS(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:jH(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function BH(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var VH=z((()=>{lS(),uk(),PH()}));Rx(),sC(),DO(),bE(),AT(),WT(),qT(),Gx(),aS(),ZC(),HT(),Uw(),Zj(),YM(),PM();const HH=`0.22.2`,UH=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),WH=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),GH=p.object({message:p.string(),path:p.string(),severity:p.string()}),KH=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),qH=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function JH(e){return e.format===`json`&&e.formatExplicit}function YH(e,t,n){if(JH(e))return e.ok(t);n()}async function XH(t){if(!t.body)return;let n=t.body.getReader();try{for(;;){let{done:t,value:r}=await n.read();if(t)break;process.stdout.write(Buffer.from(r))||await e(process.stdout,`drain`)}}finally{n.releaseLock()}}function ZH(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function QH(e){return typeof e==`string`?e:void 0}function $H(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function eU(e){let t=$H(e);return{...QH(e.description)?{description:QH(e.description)}:{},id:QH(e.id)??QH(e.name)??`unknown`,...QH(e.name)?{name:QH(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...QH(e.status)?{status:QH(e.status)}:{},...QH(e.serviceUrl)||QH(e.url)?{url:QH(e.serviceUrl)??QH(e.url)}:{}}}function tU(e){return{...QH(e.description)?{description:QH(e.description)}:{},method:QH(e.method)??`GET`,path:QH(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function nU(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=QH(t.amount),r=QH(t.currency),i=QH(t.method),a=QH(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function rU(e){return e.request.currency??e.request.asset}function iU(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=rU(e);return typeof t==`string`&&t.toLowerCase()===n})}async function aU(e,t,n={}){let r=()=>DT().getChallenges(e),i=()=>UT().getChallenges(n.ignoreX402ResponseUrl?new Response(null,{headers:e.headers,status:e.status}):e);if(t===`mpp`)return r();if(t===`x402`)return i();let a=[],o;try{a=await r()}catch(e){o=e}let s=[],c;try{s=await i()}catch(e){c=e}if(a.length||s.length)return[...a,...s];if(o)throw o;if(c)throw c;return[]}async function oU(e,t){let n=[],r=0,i=e.body?.getReader(),a=!0;if(i)for(;;){let{done:e,value:o}=await i.read();if(e)break;if(n.push(o),r+=o.byteLength,r>t){a=!1;break}}let o=a?i?new Blob(n):null:new ReadableStream({start(e){for(let t of n)e.enqueue(t)},async pull(e){let{done:t,value:n}=await i.read();t?e.close():e.enqueue(n)},cancel(e){return i.cancel(e)}}),s=new Response(o,{headers:e.headers,status:e.status,statusText:e.statusText});return Object.defineProperty(s,"url",{value:e.url}),{complete:a,response:s}}function sU(e){if(!YC(e))return`mpp:${e.id}`;let{description:t,id:n,request:r,...i}=e,{description:a,...o}=r.resource??{};return`x402:${CS({...i,id:``,request:{...r,...r.resource?{resource:o}:{}}})}`}function cU(e,t){if(!e||!t)return!0;try{return new URL(e).origin===new URL(t).origin}catch{return!1}}async function lU(e,t){return zz(iU(await aU(e,t.protocol,{ignoreX402ResponseUrl:t.ignoreX402ResponseUrl}).catch(()=>[]),t.currency),t.config)!==void 0}function uU(e){return GT({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function dU(e,t){if(!YC(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:CS(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[ww]:RT({accepts:[yw(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function fU(e){let{host:t,hostname:n,protocol:r}=new URL(e);return r===`https:`||!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function pU(e,t,n,r){let i=!1,a=t,o=fU(a),s={...n,redirect:`manual`,headers:OD(n.headers)};o.host&&_U(s.headers,o.host);for(let t=0;t<=20;t++){let{protocol:n,hostname:c}=new URL(o.url),l=[`localhost`,`127.0.0.1`,`[::1]`].includes(c);i||=n!==`https:`&&!(n===`http:`&&l);let u=await e(o.url,s),d=u.headers.get(`location`);if(!r||!d||![301,302,303,307,308].includes(u.status))return{insecureTransport:i,init:s,logicalUrl:a,response:u,target:o};if(t===20)throw TypeError(`Too many redirects`);await u.body?.cancel().catch(()=>{});let f=new URL(d,a),p=new URL(a),m=OD(s.headers);if(f.origin!==p.origin)for(let e of[`authorization`,`cookie`,`host`,`proxy-authorization`])for(let t of Object.keys(m))t.toLowerCase()===e&&delete m[t];let h=(s.method??(s.body?`POST`:`GET`)).toUpperCase(),g=u.status===303&&h!==`GET`&&h!==`HEAD`||(u.status===301||u.status===302)&&h===`POST`;if(g)for(let e of[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`])for(let t of Object.keys(m))t.toLowerCase()===e&&delete m[t];a=f.href,o=fU(a),o.host&&_U(m,o.host);let _={...s};g&&(delete _.body,_.method=`GET`),s={..._,headers:m,redirect:`manual`}}throw TypeError(`Too many redirects`)}function mU(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&gU(i),fU(i.href)}function hU(e,t){let n=new URL(e),r=new URL(t||e),i=new URL(fU(e).url);return r.origin!==n.origin&&r.origin!==i.origin&&gU(r),fU(r.href)}function gU(e){throw new B({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function _U(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function vU(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function yU(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new B({code:`SERVICES_FETCH_FAILED`,message:`Failed to fetch services registry: HTTP ${t.status}`,exitCode:1});let n=await t.json();if(!n||typeof n!=`object`||!Array.isArray(n.services))throw new B({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function bU(e,t){let n=t.toLowerCase();return e.find(e=>{let t=QH(e.id)?.toLowerCase(),r=QH(e.name)?.toLowerCase();return t===n||r===n})}const xU=vb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:HH,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:p.object({url:p.string().describe(`URL to make request to`)}),options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:p.string().optional().describe(`Path to config file`),confirm:p.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:p.string().optional().describe(`Payment currency/token address to select`),data:p.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:p.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:p.array(p.string()).optional().describe(`Add header (repeatable)`),include:p.boolean().optional().describe(`Include response headers in output`),insecure:p.boolean().optional().describe(`Skip TLS certificate verification (disables payment retries)`),jsonBody:p.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:p.boolean().optional().describe(`Follow redirects`),method:p.string().optional().describe(`HTTP method`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),protocol:p.enum([`auto`,`mpp`,`x402`]).default(`auto`).describe(`Payment protocol to use`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:p.string().optional().default(`auto`).refine(e=>e===`auto`||e===`new`||/^0x[0-9a-fA-F]{64}$/.test(e),`Expected auto, new, or a 32-byte channel ID`).describe(`Session selection: auto, new, or channel ID`),silent:p.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:p.string().optional().describe(`Set User-Agent header`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity (-v details, -vv headers)`)}),alias:{account:`a`,config:`c`,data:`d`,fail:`f`,header:`H`,include:`i`,insecure:`k`,jsonBody:`J`,location:`L`,method:`X`,methodOpt:`M`,rpcUrl:`r`,silent:`s`,userAgent:`A`,verbose:`v`},examples:[{args:{url:`mpp.dev/api/ping/paid`},description:`Make a payment request`}],async run(e){let t=e.options.silent?e=>{}:e=>process.stderr.write(e),n=await Uz(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=ZM(),i={"User-Agent":e.options.userAgent??`mppx/${HH}${r?` AIAgent/${r}`:``}`};if(e.options.header)for(let t of e.options.header){let n=t.indexOf(`:`);if(n===-1)return e.error({code:`INVALID_HEADER`,message:`Invalid header format: ${t}`,exitCode:2});i[t.slice(0,n).trim()]=t.slice(n+1).trim()}let a=Bz(n?.config);a&&!Object.keys(i).some(e=>e.toLowerCase()===`accept-payment`)&&(i[`Accept-Payment`]=a);let o=(()=>{let t=/^https?:\/\//.test(e.args.url),n=/^(localhost|.*\.localhost|127\.0\.0\.1|\[::1\])(:\d+)?/.test(e.args.url);return t?e.args.url:`${n?`http`:`https`}://${e.args.url}`})(),{hostname:s}=new URL(o),l=e.options.insecure??!1,u=l?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,d=fU(o),f=d.url;d.host&&(i.Host=d.host);try{let r=mM(e.options.methodOpt),a=sB(),s={redirect:e.options.location?`follow`:`manual`};e.options.jsonBody?(s.body=e.options.jsonBody,i[`Content-Type`]??=`application/json`,i.Accept??=`application/json`):e.options.data&&(s.body=e.options.data),e.options.method?s.method=e.options.method.toUpperCase():s.body&&(s.method=`POST`),Object.keys(i).length>0&&(s.headers=i);let c={include:e.options.include??!1,verbose:e.options.verbose,silent:e.options.silent};e.options.verbose>=2&&sM(o,s,t);let p=await pU(u,o,s,e.options.location??!1),m=p.response;if((l||p.insecureTransport)&&m.status===402)return e.error({code:`INSECURE_PAYMENT`,message:`Payment requires verified HTTPS (except loopback HTTP). Use HTTPS and omit --insecure.`,exitCode:2});if(m.status!==402){if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});if(e.options.fail&&m.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${m.status}`,exitCode:22});cM(m,c),await XH(m);return}let h;for(let i=0;;i++){let l=m.url?new URL(m.url):void 0,g=d.host!==void 0&&l?.hostname===`127.0.0.1`,_=await aU(m,e.options.protocol,{ignoreX402ResponseUrl:g});if(_.length===0)return e.error({code:`UNSUPPORTED_PROTOCOL`,message:e.options.protocol===`auto`?`Server did not offer a payment challenge.`:`Server did not offer an ${e.options.protocol} payment challenge.`,exitCode:2});let v=iU(_,e.options.currency);if(e.options.currency&&v.length===0){let t=_.map(rU).filter(e=>typeof e==`string`).join(`, `);return e.error({code:`UNSUPPORTED_CURRENCY`,message:`Server did not offer payment currency ${e.options.currency}.${t?` Offered currencies: ${t}.`:``}`,exitCode:2})}let y=Vz(n?.config)?.length?v:await ez(v,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),b=h?y.findIndex(e=>sU(e)===h.key):-1;b>0&&y.unshift(...y.splice(b,1));let x=zz(y,n?.config);if(!x){let t=y.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:S,plugin:C,method:w}=x,T=YC(S),E=T?hU(p.logicalUrl,(vU(S)??m.url)||p.logicalUrl):mU(o,d,p.logicalUrl);if(!T)try{gE(S,new URL(p.logicalUrl||o),void 0)}catch(t){return e.error({code:`UNTRUSTED_PROOF_REALM`,message:t.message,exitCode:1})}let ee=dU(S,m),D=S.request.currency??``,O=S.request.decimals??6,k,A;C&&(A=await C.setup({challenge:S,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),D=A.tokenSymbol,O=A.tokenDecimals,k=A.explorerUrl);let j=!e.options.silent&&e.options.confirm,M=new Set;{cM(m,S.method===`tempo`&&S.intent===`session`&&e.options.include?{...c,include:!1,verbose:Math.max(c.verbose,2)}:c);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(S))e.has(n)||r===void 0||t.push([n,dM(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:D,tokenDecimals:O,explorerUrl:k},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(S.request))e.has(n)||i===void 0||t.push([n,lM(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=S.request.methodDetails;if(!e)return[];let t=[];for(let[n,i]of Object.entries(e))if(i!==void 0){if(n===`memo`&&typeof i==`string`){let e=uM(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,lM(n,i,r)])}return t.sort(([e],[t])=>e.localeCompare(t))})(),o=[[`Challenge`,n],[`Request`,i],...a.length?[[`Details`,a]]:[]];for(let[,e]of o)for(let[t]of e)M.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||j){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
267
267
  `);t(` ${X.dim(e.padEnd(s))} ${n}\n`);for(let e of i)t(`${l}${e}\n`)}}}if(j&&(t(`
268
268
  `),!await vM(`Proceed with ${S.intent}?`,!0))){t(`Aborted.
269
- `);return}}let ne=process.env.MPPX_PRIVATE_KEY?.trim()||!gM(VM(e.options.account));if(pj(S)&&ne&&!w&&!(C&&n?.config.plugins?.includes(C))){try{await sV({challenge:S,challengeResponse:ee,credentialContext:await Iz(S,n?.config.extensions,A?.credentialContext),endpoint:p.logicalUrl,fetch:u,fetchInput:E.url,init:{...p.init,redirect:`manual`},info:t,methodOptions:r,options:{account:e.options.account,fail:e.options.fail,include:e.options.include,network:e.options.network,rpcUrl:e.options.rpcUrl,session:e.options.session,silent:e.options.silent,verbose:e.options.verbose},registry:a})}catch(e){return XB(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:w&&pj(S)?`--session cannot override a configured session method. Configure its channelStore instead.`:`--session requires a tempo/session payment challenge.`,exitCode:2});let N=w&&pj(S)?void 0:await Iz(S,n?.config.extensions,A?.credentialContext),P,re;if(w&&pj(S)){let e=ee;P=await jO({methods:[w],polyfill:!1,async onChallenge(e,{createCredential:t}){let r=await Iz(e,n?.config.extensions,A?.credentialContext);return Wz(S,e),t(r)},fetch:async(t,n)=>{if(e){let t=e;return e=void 0,t}return u(t,n)}}).fetch(E.url,{...p.init,context:N,redirect:`manual`})}else{if(h?.key===oU(S))re=h.credential;else if(A?.createCredential)re=await A.createCredential(ee,N);else if(A)re=await jO({methods:A.methods,polyfill:!1,transport:lU(S)}).createCredential(ee,N);else if(w)re=await jO({methods:[w],polyfill:!1,transport:lU(S)}).createCredential(ee,N);else throw Error(`unreachable`);let n=T?Tw:GS(S),r={...OD(p.init.headers),[n]:re};T&&gU(r,E.host),C?.prepareCredentialRequest?.({challenge:S,credential:re,headers:r});let i={...p.init,redirect:`manual`,headers:r};e.options.verbose>=2&&sM(E.url,i,t),P=await u(E.url,i)}if(h=re===void 0?void 0:{credential:re,key:oU(S)},P.status===402&&!(w&&pj(S))&&i+1<3&&sU(P.url,p.response.url)){let t=t=>cU(t,{config:n?.config,currency:e.options.currency,ignoreX402ResponseUrl:g,protocol:e.options.protocol}),r=new Response(null,{headers:P.headers,status:P.status,statusText:P.statusText});if(Object.defineProperty(r,"url",{value:P.url}),await t(r.clone())){await P.body?.cancel().catch(()=>{}),m=r;continue}if(e.options.protocol!==`mpp`&&!g){let e=await aU(P,1048576);if(e.complete&&await t(e.response.clone())){m=e.response;continue}P=e.response}}if(e.options.fail&&P.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${P.status}`,exitCode:22});if(P.status===402){let n=await P.text();t(`${X.bold(X.red(`Payment Rejected`))}\n`);try{let e=JSON.parse(n),r=[];for(let[t,n]of Object.entries(e))n!==void 0&&r.push([t,fM(n)]);r.sort(([e],[t])=>e.localeCompare(t));let i=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(i))} ${n}\n`)}catch{n&&t(` ${n}\n`)}return e.error({code:`PAYMENT_REJECTED`,message:`Payment rejected`,exitCode:75})}if(cM(P,c),!(re&&await C?.handleResponse?.({challenge:S,credential:re,response:P,fetchUrl:f,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:j,confirm:vM,tokenSymbol:D,tokenDecimals:O,explorerUrl:k,shownKeys:M}))){let n=P.headers.get(q.paymentReceipt);if(n&&e.options.verbose>=1)try{let e=JSON.parse(te.toString(n));t(`\n${X.bold(X.green(`Payment Receipt`))}\n`);let r=[],i=e.channelId,a=e.reference,o=i&&a&&i===a,s=new Set([`acceptedCumulative`,`spent`]);for(let[t,n]of Object.entries(e)){if(n===void 0||M.has(t)||t===`reference`&&o)continue;let e=C?.formatReceiptField?.(t,n);e===void 0?s.has(t)&&typeof n==`string`?r.push([t,`${n} ${X.dim(`(${yM(BigInt(n),D,O)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&k?r.push([t,pM(`${k}/tx/${n}`,n)]):r.push([t,String(n)]):r.push([t,e])}r.sort(([e],[t])=>e.localeCompare(t));let c=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(c))} ${n}\n`);t(`
270
- `)}catch{}await YH(P)}return}}catch(t){if(t instanceof B)throw t;let n=t instanceof Error?t.cause:void 0,r=n instanceof Error?n:void 0;if(r&&`code`in r){let t=r.code;return t===`ENOTFOUND`?e.error({code:`DNS_ERROR`,message:`Could not resolve host "${s}". Check the URL and try again.`,exitCode:6}):t===`ECONNREFUSED`?e.error({code:`CONNECTION_REFUSED`,message:`Connection refused by "${s}". Is the server running?`,retryable:!0,exitCode:7}):t===`ECONNRESET`?e.error({code:`CONNECTION_RESET`,message:`Connection to "${s}" was reset.`,retryable:!0,exitCode:56}):t===`ETIMEDOUT`?e.error({code:`CONNECTION_TIMEOUT`,message:`Connection to "${s}" timed out.`,retryable:!0,exitCode:28}):t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?e.error({code:`TLS_ERROR`,message:`TLS certificate error for "${s}". Use --insecure to skip verification.`,exitCode:60}):e.error({code:`REQUEST_FAILED`,message:`Request to "${s}" failed: ${r.message}`})}{let n=t instanceof Error?t.message:String(t);return e.error({code:`REQUEST_FAILED`,message:r?`Request failed: ${n} (Cause: ${r.message})`:`Request failed: ${n}`})}}}}),xU=vb(`account`,{description:`Manage accounts (create, default, delete, export, fund, list, view)`}).command(`create`,{description:`Create new account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({address:p.string(),name:p.string()}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=qH(e),n=e.options.account;if(!n){if((await HM().list()).length===0)n=`main`;else{if(t)return e.error({code:`ACCOUNT_REQUIRED`,message:`Account name is required in structured mode.`,exitCode:2});let r=await _M(`Account name`);if(!r)return;n=r}}let r=HM(n);for(;await r.get();){if(t)return e.error({code:`ACCOUNT_EXISTS`,message:`Account "${n}" already exists.`,exitCode:1});process.stderr.write(`${X.dim(`Account "${n}" already exists.`)}\n\n`);let i=await _M(`Enter different name`);if(!i)return;n=i,r=HM(n)}let i=ge(),a=R(i);await r.set(i),(await HM().list()).length===1&&BM().set(n);let o=ve.blockExplorers?.default?.url,s=o?pM(`${o}/address/${a.address}`,a.address):a.address,c=xM(e.options),l=bM(e.options.rpcUrl,{network:c});return SM({network:c,rpcUrl:l}).then(e=>N({chain:e,transport:L(l)})).then(e=>import(`viem/tempo`).then(({Actions:t})=>t.faucet.fund(e,{account:a}).catch(()=>{}))),JH(e,{address:a.address,name:n},()=>{console.log(`Account "${n}" saved to keychain.`),console.log(X.dim(`Address ${s}`)),console.log(X.dim(`Fund testnet tokens: mppx account fund --account ${n} --network testnet`))})}}).command(`default`,{description:`Set default account`,options:p.object({account:p.string().describe(`Account name`)}),output:p.object({name:p.string()}),alias:{account:`a`},async run(e){let t=e.options.account;return gM(t)?bz(t)?(BM().set(t),JH(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69}):await HM(t).get()?(BM().set(t),JH(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69})}}).command(`delete`,{description:`Delete account`,options:p.object({account:p.string().describe(`Account name`),yes:p.boolean().optional().describe(`DANGER!! Skip confirmation prompts`)}),output:p.object({defaultAccount:p.string().optional(),name:p.string()}),alias:{account:`a`},async run(e){let t=HM(e.options.account),n=await t.get();if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${e.options.account}" not found.`,exitCode:69});let r=R(n),i=await DM(r.address,{includeTestnet:!1});if(!e.options.yes){if(qH(e))return e.error({code:`CONFIRMATION_REQUIRED`,message:`Pass --yes to delete an account in structured mode.`,exitCode:2});let t=ve.blockExplorers?.default?.url,n=t?pM(`${t}/address/${r.address}`,r.address):r.address;process.stderr.write(X.dim(`Delete account "${e.options.account}"\n`)),process.stderr.write(X.dim(` Address ${n}\n`));for(let e=0;e<i.length;e++)process.stderr.write(X.dim(` ${e===0?`Balance`:` `} ${i[e]}\n`));if(process.stderr.write(X.dim(`This action cannot be undone
269
+ `);return}}let ne=process.env.MPPX_PRIVATE_KEY?.trim()||!gM(HM(e.options.account));if(pj(S)&&ne&&!w&&!(C&&n?.config.plugins?.includes(C))){try{await cV({challenge:S,challengeResponse:ee,credentialContext:await Lz(S,n?.config.extensions,A?.credentialContext),endpoint:p.logicalUrl,fetch:u,fetchInput:E.url,init:{...p.init,redirect:`manual`},info:t,methodOptions:r,options:{account:e.options.account,fail:e.options.fail,include:e.options.include,network:e.options.network,rpcUrl:e.options.rpcUrl,session:e.options.session,silent:e.options.silent,verbose:e.options.verbose},registry:a})}catch(e){return ZB(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:w&&pj(S)?`--session cannot override a configured session method. Configure its channelStore instead.`:`--session requires a tempo/session payment challenge.`,exitCode:2});let N=w&&pj(S)?void 0:await Lz(S,n?.config.extensions,A?.credentialContext),P,re;if(w&&pj(S)){let e=ee;P=await jO({methods:[w],polyfill:!1,async onChallenge(e,{createCredential:t}){let r=await Lz(e,n?.config.extensions,A?.credentialContext);return Gz(S,e),t(r)},fetch:async(t,n)=>{if(e){let t=e;return e=void 0,t}return u(t,n)}}).fetch(E.url,{...p.init,context:N,redirect:`manual`})}else{if(h?.key===sU(S))re=h.credential;else if(A?.createCredential)re=await A.createCredential(ee,N);else if(A)re=await jO({methods:A.methods,polyfill:!1,transport:uU(S)}).createCredential(ee,N);else if(w)re=await jO({methods:[w],polyfill:!1,transport:uU(S)}).createCredential(ee,N);else throw Error(`unreachable`);let n=T?Tw:GS(S),r={...OD(p.init.headers),[n]:re};T&&_U(r,E.host),C?.prepareCredentialRequest?.({challenge:S,credential:re,headers:r});let i={...p.init,redirect:`manual`,headers:r};e.options.verbose>=2&&sM(E.url,i,t),P=await u(E.url,i)}if(h=re===void 0?void 0:{credential:re,key:sU(S)},P.status===402&&!(w&&pj(S))&&i+1<3&&cU(P.url,p.response.url)){let t=t=>lU(t,{config:n?.config,currency:e.options.currency,ignoreX402ResponseUrl:g,protocol:e.options.protocol}),r=new Response(null,{headers:P.headers,status:P.status,statusText:P.statusText});if(Object.defineProperty(r,"url",{value:P.url}),await t(r.clone())){await P.body?.cancel().catch(()=>{}),m=r;continue}if(e.options.protocol!==`mpp`&&!g){let e=await oU(P,1048576);if(e.complete&&await t(e.response.clone())){m=e.response;continue}P=e.response}}if(e.options.fail&&P.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${P.status}`,exitCode:22});if(P.status===402){let n=await P.text();t(`${X.bold(X.red(`Payment Rejected`))}\n`);try{let e=JSON.parse(n),r=[];for(let[t,n]of Object.entries(e))n!==void 0&&r.push([t,fM(n)]);r.sort(([e],[t])=>e.localeCompare(t));let i=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(i))} ${n}\n`)}catch{n&&t(` ${n}\n`)}return e.error({code:`PAYMENT_REJECTED`,message:`Payment rejected`,exitCode:75})}if(cM(P,c),!(re&&await C?.handleResponse?.({challenge:S,credential:re,response:P,fetchUrl:f,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:j,confirm:vM,tokenSymbol:D,tokenDecimals:O,explorerUrl:k,shownKeys:M}))){let n=P.headers.get(q.paymentReceipt);if(n&&e.options.verbose>=1)try{let e=JSON.parse(te.toString(n));t(`\n${X.bold(X.green(`Payment Receipt`))}\n`);let r=[],i=e.channelId,a=e.reference,o=i&&a&&i===a,s=new Set([`acceptedCumulative`,`spent`]);for(let[t,n]of Object.entries(e)){if(n===void 0||M.has(t)||t===`reference`&&o)continue;let e=C?.formatReceiptField?.(t,n);e===void 0?s.has(t)&&typeof n==`string`?r.push([t,`${n} ${X.dim(`(${yM(BigInt(n),D,O)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&k?r.push([t,pM(`${k}/tx/${n}`,n)]):r.push([t,String(n)]):r.push([t,e])}r.sort(([e],[t])=>e.localeCompare(t));let c=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(c))} ${n}\n`);t(`
270
+ `)}catch{}await XH(P)}return}}catch(t){if(t instanceof B)throw t;let n=t instanceof Error?t.cause:void 0,r=n instanceof Error?n:void 0;if(r&&`code`in r){let t=r.code;return t===`ENOTFOUND`?e.error({code:`DNS_ERROR`,message:`Could not resolve host "${s}". Check the URL and try again.`,exitCode:6}):t===`ECONNREFUSED`?e.error({code:`CONNECTION_REFUSED`,message:`Connection refused by "${s}". Is the server running?`,retryable:!0,exitCode:7}):t===`ECONNRESET`?e.error({code:`CONNECTION_RESET`,message:`Connection to "${s}" was reset.`,retryable:!0,exitCode:56}):t===`ETIMEDOUT`?e.error({code:`CONNECTION_TIMEOUT`,message:`Connection to "${s}" timed out.`,retryable:!0,exitCode:28}):t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?e.error({code:`TLS_ERROR`,message:`TLS certificate error for "${s}". Use --insecure to skip verification.`,exitCode:60}):e.error({code:`REQUEST_FAILED`,message:`Request to "${s}" failed: ${r.message}`})}{let n=t instanceof Error?t.message:String(t);return e.error({code:`REQUEST_FAILED`,message:r?`Request failed: ${n} (Cause: ${r.message})`:`Request failed: ${n}`})}}}}),SU=vb(`account`,{description:`Manage accounts (create, default, delete, export, fund, list, view)`}).command(`create`,{description:`Create new account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({address:p.string(),name:p.string()}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=JH(e),n=e.options.account;if(!n){if((await UM().list()).length===0)n=`main`;else{if(t)return e.error({code:`ACCOUNT_REQUIRED`,message:`Account name is required in structured mode.`,exitCode:2});let r=await _M(`Account name`);if(!r)return;n=r}}let r=UM(n);for(;await r.get();){if(t)return e.error({code:`ACCOUNT_EXISTS`,message:`Account "${n}" already exists.`,exitCode:1});process.stderr.write(`${X.dim(`Account "${n}" already exists.`)}\n\n`);let i=await _M(`Enter different name`);if(!i)return;n=i,r=UM(n)}let i=ge(),a=R(i);await r.set(i),(await UM().list()).length===1&&VM().set(n);let o=ve.blockExplorers?.default?.url,s=o?pM(`${o}/address/${a.address}`,a.address):a.address,c=xM(e.options),l=bM(e.options.rpcUrl,{network:c});return SM({network:c,rpcUrl:l}).then(e=>N({chain:e,transport:L(l)})).then(e=>import(`viem/tempo`).then(({Actions:t})=>t.faucet.fund(e,{account:a}).catch(()=>{}))),YH(e,{address:a.address,name:n},()=>{console.log(`Account "${n}" saved to keychain.`),console.log(X.dim(`Address ${s}`)),console.log(X.dim(`Fund testnet tokens: mppx account fund --account ${n} --network testnet`))})}}).command(`default`,{description:`Set default account`,options:p.object({account:p.string().describe(`Account name`)}),output:p.object({name:p.string()}),alias:{account:`a`},async run(e){let t=e.options.account;return gM(t)?xz(t)?(VM().set(t),YH(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69}):await UM(t).get()?(VM().set(t),YH(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69})}}).command(`delete`,{description:`Delete account`,options:p.object({account:p.string().describe(`Account name`),yes:p.boolean().optional().describe(`DANGER!! Skip confirmation prompts`)}),output:p.object({defaultAccount:p.string().optional(),name:p.string()}),alias:{account:`a`},async run(e){let t=UM(e.options.account),n=await t.get();if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${e.options.account}" not found.`,exitCode:69});let r=R(n),i=await DM(r.address,{includeTestnet:!1});if(!e.options.yes){if(JH(e))return e.error({code:`CONFIRMATION_REQUIRED`,message:`Pass --yes to delete an account in structured mode.`,exitCode:2});let t=ve.blockExplorers?.default?.url,n=t?pM(`${t}/address/${r.address}`,r.address):r.address;process.stderr.write(X.dim(`Delete account "${e.options.account}"\n`)),process.stderr.write(X.dim(` Address ${n}\n`));for(let e=0;e<i.length;e++)process.stderr.write(X.dim(` ${e===0?`Balance`:` `} ${i[e]}\n`));if(process.stderr.write(X.dim(`This action cannot be undone
271
271
 
272
- `)),!await vM(`Confirm delete?`)){console.log(`Canceled`);return}}await t.delete();let a=BM().get(),o;if(a===e.options.account){let e=await HM().list();e.length>0?(o=e[0],BM().set(o)):BM().clear()}return JH(e,{defaultAccount:o,name:e.options.account},()=>{o&&console.log(`Default account set to "${o}"`),console.log(`Account "${e.options.account}" deleted`)})}}).command(`fund`,{description:`Fund account with testnet tokens`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({account:p.string(),chain:p.string(),transactions:p.array(p.string())}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=qH(e),n=VM(e.options.account),r=await HM(n).get();if(!r)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${n}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let i=R(r),a=xM(e.options),o=bM(e.options.rpcUrl,{network:a}),s=await SM({network:a,rpcUrl:o}),c=N({chain:s,transport:L(o)});t||console.log(`Funding "${n}" on ${CM(s)}`);try{let{Actions:r}=await import(`viem/tempo`),a=await r.faucet.fund(c,{account:i}),o=s.blockExplorers?.default?.url;if(!t)for(let e of a){let t=o?pM(`${o}/tx/${e}`,X.gray(e)):e;console.log(` ${t}`)}let{waitForTransactionReceipt:l}=await import(`viem/actions`);return await Promise.all(a.map(e=>l(c,{hash:e}))),JH(e,{account:n,chain:CM(s),transactions:[...a]},()=>{console.log(`Funded successfully`)})}catch(n){let r=n instanceof Error?n.message:String(n);return t?e.error({code:`FUNDING_FAILED`,message:r,exitCode:1}):e.error({code:`FUNDING_FAILED`,message:`Funding failed: ${r}`,exitCode:1})}}}).command(`list`,{description:`List all accounts`,output:p.object({accounts:p.array(HH)}),async run(e){let t=BM().get(),n=(await HM().list()).sort(),r=[];for(let e of n){let t=await HM(e).get();t&&r.push({name:e,address:R(t).address})}let i=yz();for(let e=0;e<i.length;e++){let t=i[e],n=e===0?`tempo:default`:`tempo:${e}`;t.wallet_address&&r.push({name:n,address:t.wallet_address,source:`tempo wallet`})}if(r.length===0)return JH(e,{accounts:[]},()=>{console.log(`No accounts found.`)});let a=ve.blockExplorers?.default?.url,o=Math.max(...r.map(e=>e.name.length+ +(e.name===t)));return JH(e,{accounts:r.map(e=>({...e,...e.name===t?{isDefault:!0}:void 0}))},()=>{for(let e of r){let n=e.name===t,r=n?`${e.name}${X.dim(`*`)}`:e.name,i=e.name.length+ +!!n,s=a?pM(`${a}/address/${e.address}`,e.address):e.address,c=e.source?` ${X.dim(`(${e.source})`)}`:``;console.log(`${r}${` `.repeat(o-i+2)}${X.dim(s)}${c}`)}})}}).command(`export`,{description:`Export the private key for a local account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`)}),output:p.object({privateKey:p.string()}),alias:{account:`a`},async run(e){let t=VM(e.options.account);if(gM(t))return e.error({code:`UNSUPPORTED_ACCOUNT`,message:`Account "${t}" is managed by Tempo wallet and does not expose a private key via mppx.`,exitCode:2});let n=await HM(t).get();return n?JH(e,{privateKey:n},()=>{console.log(n)}):e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}}).command(`view`,{description:`View account address`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:UH,alias:{account:`a`,rpcUrl:`r`},async run(e){let t=VM(e.options.account);if(gM(t)){let n=bz(t);if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69});let r=n.wallet_address,i=bM(e.options.rpcUrl,{network:e.options.network}),a=await SM({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?pM(`${o}/address/${r}`,r):r,c=await DM(r,a&&i?{chain:a,rpcUrl:i}:void 0);return JH(e,{address:r,balances:c,name:t,type:`${n.wallet_type} (tempo wallet)`},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`),console.log(`${X.dim(`Type`)} ${n.wallet_type} ${X.dim(`(tempo wallet)`)}`)})}let n=await HM(t).get();if(!n)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let r=R(n),i=bM(e.options.rpcUrl,{network:e.options.network}),a=await SM({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?pM(`${o}/address/${r.address}`,r.address):r.address,c=await DM(r.address,a&&i?{chain:a,rpcUrl:i}:void 0);return JH(e,{address:r.address,balances:c,name:t},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`)})}}),SU=vb(`sign`,{description:`Sign a payment challenge and output the Authorization header`,usage:[{suffix:`--challenge <value> [options]`},{prefix:`echo <challenge> |`,suffix:`[options]`}],options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),challenge:p.string().optional().describe(`WWW-Authenticate challenge value`),config:p.string().optional().describe(`Path to config file`),dryRun:p.boolean().optional().describe(`Validate and parse the challenge without signing`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`)}),output:p.object({authorization:p.string()}),alias:{account:`a`,challenge:`C`,config:`c`,methodOpt:`M`,rpcUrl:`r`},async run(e){let t=e.options.challenge||(XH()?await new Promise((e,t)=>{let n=``;process.stdin.setEncoding(`utf-8`),process.stdin.on(`data`,e=>{n+=e}),process.stdin.on(`end`,()=>e(n.trim())),process.stdin.on(`error`,t)}):void 0);if(!t)return e.error({code:`NO_CHALLENGE`,message:`No challenge provided. Use --challenge or pipe via stdin.`,exitCode:2});let n;try{n=BS(t)}catch(t){return e.error({code:`INVALID_CHALLENGE`,message:`Failed to parse challenge: ${t instanceof Error?t.message:t}`,exitCode:2})}if(e.options.dryRun){process.stderr.write(`Challenge is valid.
273
- `);return}let r=n.filter(e=>!DS(e));if(n.length>0&&r.length===0)return e.error({code:`LEGACY_UNICODE_ESCAPED_CHALLENGE`,message:new Qx().message,exitCode:2});let i=await Hz(e.options.config),a=Rz(r,i?.config);if(!a){let t=n.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:o,plugin:s,method:c}=a,l=mM(e.options.methodOpt),u=CS(o),d=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:u}}),f;s&&(f=await s.setup({challenge:o,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:l}));let p=await Iz(o,i?.config.extensions,f?.credentialContext),m;if(f)m=f.createCredential?await f.createCredential(d,p):await jO({methods:f.methods,polyfill:!1}).createCredential(d,p);else if(c)m=await jO({methods:[c],polyfill:!1}).createCredential(d,p);else return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method: ${o.method}/${o.intent}. Add it to mppx.config.ts using defineConfig().`,exitCode:2});return JH(e,{authorization:m},()=>{console.log(m)})}}),CU=vb(`init`,{description:`Create an mppx.config.ts file in the current directory`,options:p.object({force:p.boolean().optional().describe(`Overwrite existing config file`)}),output:p.object({file:p.string()}),alias:{force:`f`},async run(e){let n=process.cwd(),r=`mppx.config${(()=>{if(t.existsSync(c.join(n,`tsconfig.json`)))return`.ts`;try{if(JSON.parse(t.readFileSync(c.join(n,`package.json`),`utf-8`)).type===`module`)return`.mjs`}catch{}return`.js`})()}`,i=c.join(n,r);return t.existsSync(i)&&!e.options.force?e.error({code:`CONFIG_EXISTS`,message:`${r} already exists. Use --force to overwrite.`,exitCode:1}):(t.writeFileSync(i,`import { defineConfig } from 'mppx/cli'
272
+ `)),!await vM(`Confirm delete?`)){console.log(`Canceled`);return}}await t.delete();let a=VM().get(),o;if(a===e.options.account){let e=await UM().list();e.length>0?(o=e[0],VM().set(o)):VM().clear()}return YH(e,{defaultAccount:o,name:e.options.account},()=>{o&&console.log(`Default account set to "${o}"`),console.log(`Account "${e.options.account}" deleted`)})}}).command(`fund`,{description:`Fund account with testnet tokens`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({account:p.string(),chain:p.string(),transactions:p.array(p.string())}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=JH(e),n=HM(e.options.account),r=await UM(n).get();if(!r)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${n}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let i=R(r),a=xM(e.options),o=bM(e.options.rpcUrl,{network:a}),s=await SM({network:a,rpcUrl:o}),c=N({chain:s,transport:L(o)});t||console.log(`Funding "${n}" on ${CM(s)}`);try{let{Actions:r}=await import(`viem/tempo`),a=await r.faucet.fund(c,{account:i}),o=s.blockExplorers?.default?.url;if(!t)for(let e of a){let t=o?pM(`${o}/tx/${e}`,X.gray(e)):e;console.log(` ${t}`)}let{waitForTransactionReceipt:l}=await import(`viem/actions`);return await Promise.all(a.map(e=>l(c,{hash:e}))),YH(e,{account:n,chain:CM(s),transactions:[...a]},()=>{console.log(`Funded successfully`)})}catch(n){let r=n instanceof Error?n.message:String(n);return t?e.error({code:`FUNDING_FAILED`,message:r,exitCode:1}):e.error({code:`FUNDING_FAILED`,message:`Funding failed: ${r}`,exitCode:1})}}}).command(`list`,{description:`List all accounts`,output:p.object({accounts:p.array(UH)}),async run(e){let t=VM().get(),n=(await UM().list()).sort(),r=[];for(let e of n){let t=await UM(e).get();t&&r.push({name:e,address:R(t).address})}let i=bz();for(let e=0;e<i.length;e++){let t=i[e],n=e===0?`tempo:default`:`tempo:${e}`;t.wallet_address&&r.push({name:n,address:t.wallet_address,source:`tempo wallet`})}if(r.length===0)return YH(e,{accounts:[]},()=>{console.log(`No accounts found.`)});let a=ve.blockExplorers?.default?.url,o=Math.max(...r.map(e=>e.name.length+ +(e.name===t)));return YH(e,{accounts:r.map(e=>({...e,...e.name===t?{isDefault:!0}:void 0}))},()=>{for(let e of r){let n=e.name===t,r=n?`${e.name}${X.dim(`*`)}`:e.name,i=e.name.length+ +!!n,s=a?pM(`${a}/address/${e.address}`,e.address):e.address,c=e.source?` ${X.dim(`(${e.source})`)}`:``;console.log(`${r}${` `.repeat(o-i+2)}${X.dim(s)}${c}`)}})}}).command(`export`,{description:`Export the private key for a local account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`)}),output:p.object({privateKey:p.string()}),alias:{account:`a`},async run(e){let t=HM(e.options.account);if(gM(t))return e.error({code:`UNSUPPORTED_ACCOUNT`,message:`Account "${t}" is managed by Tempo wallet and does not expose a private key via mppx.`,exitCode:2});let n=await UM(t).get();return n?YH(e,{privateKey:n},()=>{console.log(n)}):e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}}).command(`view`,{description:`View account address`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:WH,alias:{account:`a`,rpcUrl:`r`},async run(e){let t=HM(e.options.account);if(gM(t)){let n=xz(t);if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69});let r=n.wallet_address,i=bM(e.options.rpcUrl,{network:e.options.network}),a=await SM({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?pM(`${o}/address/${r}`,r):r,c=await DM(r,a&&i?{chain:a,rpcUrl:i}:void 0);return YH(e,{address:r,balances:c,name:t,type:`${n.wallet_type} (tempo wallet)`},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`),console.log(`${X.dim(`Type`)} ${n.wallet_type} ${X.dim(`(tempo wallet)`)}`)})}let n=await UM(t).get();if(!n)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let r=R(n),i=bM(e.options.rpcUrl,{network:e.options.network}),a=await SM({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?pM(`${o}/address/${r.address}`,r.address):r.address,c=await DM(r.address,a&&i?{chain:a,rpcUrl:i}:void 0);return YH(e,{address:r.address,balances:c,name:t},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`)})}}),CU=vb(`sign`,{description:`Sign a payment challenge and output the Authorization header`,usage:[{suffix:`--challenge <value> [options]`},{prefix:`echo <challenge> |`,suffix:`[options]`}],options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),challenge:p.string().optional().describe(`WWW-Authenticate challenge value`),config:p.string().optional().describe(`Path to config file`),dryRun:p.boolean().optional().describe(`Validate and parse the challenge without signing`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`)}),output:p.object({authorization:p.string()}),alias:{account:`a`,challenge:`C`,config:`c`,methodOpt:`M`,rpcUrl:`r`},async run(e){let t=e.options.challenge||(ZH()?await new Promise((e,t)=>{let n=``;process.stdin.setEncoding(`utf-8`),process.stdin.on(`data`,e=>{n+=e}),process.stdin.on(`end`,()=>e(n.trim())),process.stdin.on(`error`,t)}):void 0);if(!t)return e.error({code:`NO_CHALLENGE`,message:`No challenge provided. Use --challenge or pipe via stdin.`,exitCode:2});let n;try{n=BS(t)}catch(t){return e.error({code:`INVALID_CHALLENGE`,message:`Failed to parse challenge: ${t instanceof Error?t.message:t}`,exitCode:2})}if(e.options.dryRun){process.stderr.write(`Challenge is valid.
273
+ `);return}let r=n.filter(e=>!DS(e));if(n.length>0&&r.length===0)return e.error({code:`LEGACY_UNICODE_ESCAPED_CHALLENGE`,message:new Qx().message,exitCode:2});let i=await Uz(e.options.config),a=zz(r,i?.config);if(!a){let t=n.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:o,plugin:s,method:c}=a,l=mM(e.options.methodOpt),u=CS(o),d=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:u}}),f;s&&(f=await s.setup({challenge:o,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:l}));let p=await Lz(o,i?.config.extensions,f?.credentialContext),m;if(f)m=f.createCredential?await f.createCredential(d,p):await jO({methods:f.methods,polyfill:!1}).createCredential(d,p);else if(c)m=await jO({methods:[c],polyfill:!1}).createCredential(d,p);else return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method: ${o.method}/${o.intent}. Add it to mppx.config.ts using defineConfig().`,exitCode:2});return YH(e,{authorization:m},()=>{console.log(m)})}}),wU=vb(`init`,{description:`Create an mppx.config.ts file in the current directory`,options:p.object({force:p.boolean().optional().describe(`Overwrite existing config file`)}),output:p.object({file:p.string()}),alias:{force:`f`},async run(e){let n=process.cwd(),r=`mppx.config${(()=>{if(t.existsSync(c.join(n,`tsconfig.json`)))return`.ts`;try{if(JSON.parse(t.readFileSync(c.join(n,`package.json`),`utf-8`)).type===`module`)return`.mjs`}catch{}return`.js`})()}`,i=c.join(n,r);return t.existsSync(i)&&!e.options.force?e.error({code:`CONFIG_EXISTS`,message:`${r} already exists. Use --force to overwrite.`,exitCode:1}):(t.writeFileSync(i,`import { defineConfig } from 'mppx/cli'
274
274
 
275
275
  export default defineConfig({
276
276
  methods: [],
277
277
  plugins: [],
278
278
  })
279
- `),JH(e,{file:i},()=>{console.log(`Created ${r}`)}))}}),wU=vb(`services`,{description:`Browse the MPP services registry`}).command(`list`,{description:`List registered MPP services`,options:p.object({query:p.string().optional().describe(`Filter by id, name, category, tag, or description`)}),output:p.object({services:p.array(GH)}),alias:{query:`q`},async run(e){let t=e.options.query?.toLowerCase(),n=await vU(),r=(t?n.filter(e=>[e.id,e.name,e.description,...Array.isArray(e.categories)?e.categories:[],...Array.isArray(e.tags)?e.tags:[]].filter(e=>typeof e==`string`).some(e=>e.toLowerCase().includes(t))):n).map($H).sort((e,t)=>e.id.localeCompare(t.id));return JH(e,{services:r},()=>{if(r.length===0){console.log(`No services found.`);return}let e=Math.max(...r.map(e=>e.id.length)),t=Math.max(...r.map(e=>String(e.paidEndpoints).length));for(let n of r){let r=n.name&&n.name!==n.id?` ${n.name}`:``,i=n.url?` ${X.dim(n.url)}`:``;console.log(`${n.id.padEnd(e)} ${String(n.paidEndpoints).padStart(t)} paid${r}${i}`)}})}}).command(`show`,{description:`Show one registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({service:p.record(p.string(),p.unknown())}),async run(e){let t=yU(await vU(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=$H(t),r=QH(t);return JH(e,{service:t},()=>{console.log(`${n.name??n.id} ${X.dim(`(${n.id})`)}`),n.description&&console.log(n.description),n.url&&console.log(`${X.dim(`URL`)} ${pM(n.url,n.url)}`),n.status&&console.log(`${X.dim(`Status`)} ${n.status}`),console.log(`${X.dim(`Endpoints`)} ${r.length} (${n.paidEndpoints} paid)`);let e=t.docs,i=e&&ZH(e.homepage);i&&console.log(`${X.dim(`Docs`)} ${pM(i,i)}`)})}}).command(`endpoints`,{description:`List endpoints for a registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({endpoints:p.array(KH),service:GH}),async run(e){let t=yU(await vU(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=$H(t),r=QH(t).map(eU);return JH(e,{endpoints:r,service:n},()=>{if(r.length===0){console.log(`No endpoints found for ${n.id}.`);return}let e=Math.max(...r.map(e=>e.method.length)),t=Math.max(...r.map(e=>e.path.length));for(let n of r){let r=tU(n.payment),i=n.description?` ${X.dim(n.description)}`:``;console.log(`${n.method.padEnd(e)} ${n.path.padEnd(t)} ${r}${i}`)}})}}),TU=vb(`discover`,{description:`Discovery tooling`}).command(`generate`,{description:`Generate a static OpenAPI discovery document from a module`,args:p.object({module:p.string().describe(`Path to a module that default-exports a discovery config`)}),options:p.object({output:p.string().optional().describe(`Write output to a file instead of stdout`)}),output:p.record(p.string(),p.unknown()),alias:{output:`o`},async run(e){let n=c.resolve(e.args.module);if(!t.existsSync(n))return e.error({code:`MODULE_NOT_FOUND`,message:`Module not found: ${n}`,exitCode:1});let r;try{r=await import(n)}catch(t){return e.error({code:`MODULE_IMPORT_FAILED`,message:`Failed to import module: ${t.message}`,exitCode:1})}let i=r.default??r,a;if(typeof i.openapi==`string`)a=i;else{let{generate:t}=await Promise.resolve().then(()=>(BH(),PH)),n=i.mppx;if(!n)return e.error({code:`INVALID_MODULE`,message:"Module must default-export an OpenAPI document (with `openapi` key) or an object with `mppx` (server instance) and `routes`.",exitCode:1});a=t(n,i)}let o=JSON.stringify(a,null,2);if(e.options.output){let n=c.resolve(e.options.output);return t.writeFileSync(n,`${o}\n`),process.stderr.write(`Wrote ${n}\n`),JH(e,a,()=>{})}return JH(e,a,()=>{console.log(o)})}}).command(`validate`,{description:`Validate an OpenAPI discovery document from a file or URL`,args:p.object({input:p.string().describe(`Path or URL to a discovery document`)}),output:p.object({errorCount:p.number(),issues:p.array(WH),valid:p.boolean(),warningCount:p.number()}),async run(e){let n=e.args.input,r;if(/^https?:\/\//.test(n)){let t=new AbortController,i=setTimeout(()=>t.abort(),3e4),a;try{a=await globalThis.fetch(n,{signal:t.signal})}catch(t){clearTimeout(i);let n=t instanceof DOMException&&t.name===`AbortError`?`Request timed out after 30s`:t.message;return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: ${n}`,exitCode:1})}if(clearTimeout(i),!a.ok)return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: HTTP ${a.status}`,exitCode:1});let o=10485760,s=a.headers.get(`content-length`);if(s&&Number(s)>o||(r=await a.text(),r.length>o))return e.error({code:`DISCOVERY_TOO_LARGE`,message:`Discovery document exceeds 10 MB limit`,exitCode:1})}else{let i=c.resolve(n);if(!t.existsSync(i))return e.error({code:`DISCOVERY_NOT_FOUND`,message:`Discovery document not found: ${i}`,exitCode:1});r=t.readFileSync(i,`utf-8`)}let i;try{i=JSON.parse(r)}catch(t){return e.error({code:`DISCOVERY_INVALID_JSON`,message:`Invalid discovery JSON: ${t.message}`,exitCode:1})}let a=dk(i);if(!qH(e))for(let e of a)console.log(`[${e.severity}] ${e.path}: ${e.message}`);let o=a.filter(e=>e.severity===`error`).length,s=a.filter(e=>e.severity===`warning`).length;return o>0?e.error({code:`DISCOVERY_INVALID`,message:`Discovery document has ${o} error(s) and ${s} warning(s).`,exitCode:1}):JH(e,{errorCount:o,issues:a,valid:!0,warningCount:s},()=>{console.log(s>0?`Discovery document is valid with ${s} warning(s).`:`Discovery document is valid.`)})}}),EU=p.object({address:p.string(),id:p.string(),livemode:p.boolean(),network:p.string(),supportedTokens:p.array(p.object({contractAddress:p.string(),currency:p.string()}))}),DU=vb(`stripe`,{description:`Stripe machine payments tooling`}).command(`address`,{description:`Create a Stripe crypto deposit address and print its public address`,usage:[{suffix:`[--network tempo|base|solana] [--env [path]] [--secret-key <key>] [options]`}],options:p.object({customer:p.string().optional().describe(`Scope the address to a Stripe customer (cus_...); it then only accepts their funds`),env:p.string().optional().describe(`Write <NETWORK>_DEPOSIT_ADDRESS to this env file instead of printing (default path: .env)`),live:p.boolean().optional().describe(`Use the Stripe CLI's live mode key instead of its test mode key`),network:p.enum([`tempo`,`base`,`solana`]).default(`tempo`).describe(`Network to create the address on`),projectName:p.string().optional().describe(`Stripe CLI project to read the key from (env: STRIPE_PROJECT_NAME, default: default)`),secretKey:p.string().optional().describe(`Stripe secret key (sk_...); else STRIPE_SECRET_KEY, else the Stripe CLI's login`),stripeAccount:p.string().optional().describe(`Connected account to create the address for (acct_...)`)}),output:EU,alias:{network:`n`},async run(e){let{customer:t,env:n,live:r,network:i,projectName:a,secretKey:o,stripeAccount:s}=e.options;if(n&&t)return e.error({code:`INVALID_OPTIONS`,message:`--env can't be combined with --customer: that address only accepts the customer's funds.`,exitCode:2});let c=lV({live:r,projectName:a,secretKey:o});if(!c)return e.error({code:`MISSING_STRIPE_SECRET_KEY`,message:`No Stripe key found. Pass --secret-key <sk_...>, set STRIPE_SECRET_KEY, or run \`stripe login\` so mppx can read the Stripe CLI's ${r?`live`:`test`} mode key.`,exitCode:2});let l=new URLSearchParams({network:i});t&&l.set(`customer`,t);let u=await globalThis.fetch(new URL(`/v1/crypto/deposit_addresses`,process.env.MPPX_STRIPE_API_URL??`https://api.stripe.com`),{method:`POST`,headers:{Authorization:`Bearer ${c.key}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":fk,...s?{"Stripe-Account":s}:{}},body:l}),d=await u.json().catch(()=>({}));if(!u.ok||!d.address){let t=d.error?.code&&/^[a-z_]+$/.test(d.error.code)?`, ${d.error.code}`:``,n=`HTTP ${u.status}${t}`,r=u.status===401||u.status===403,i=c.source===`stripe-cli`?`the Stripe CLI's login`:c.source===`flag`?`--secret-key`:`STRIPE_SECRET_KEY`,a=r&&c.key.startsWith(`rk_`)?`Stripe refused the restricted key (rk_...) from ${i} for crypto deposit addresses (${n}). Pass a secret key with --secret-key <sk_...> or STRIPE_SECRET_KEY.`:r&&c.source===`stripe-cli`?`Stripe refused the key from the Stripe CLI's login (${n}). Run \`stripe login\` again, or pass --secret-key <sk_...>.`:`Stripe could not create a deposit address (${n}).`;return e.error({code:`STRIPE_REQUEST_FAILED`,message:a,exitCode:1})}if(!hV(i,d.address))return e.error({code:`STRIPE_INVALID_ADDRESS`,message:`Stripe returned a deposit address that isn't a valid ${i} address.`,exitCode:1});let f={address:d.address,id:d.id??``,livemode:d.livemode??!1,network:d.network??i,supportedTokens:(d.supported_tokens??[]).map(e=>({contractAddress:e.token_contract_address,currency:e.token_currency}))};if(n){let t=`${i.toUpperCase()}_DEPOSIT_ADDRESS`;return _V(n,t,f.address),console.error(`Wrote ${t} to ${n}`),JH(e,f,()=>{})}return JH(e,f,()=>console.log(f.address))}});bU.command(xU),bU.command(TU),bU.command(CU),bU.command(wU),bU.command($B),bU.command(SU),bU.command(DU),bU.command(DH);const OU=bU.serve.bind(bU);bU.serve=(e=process.argv.slice(2),t)=>OU(bV(e),t);export{bU as default,pU as resolveMppCredentialTarget,mU as resolveX402CredentialTarget};
279
+ `),YH(e,{file:i},()=>{console.log(`Created ${r}`)}))}}),TU=vb(`services`,{description:`Browse the MPP services registry`}).command(`list`,{description:`List registered MPP services`,options:p.object({query:p.string().optional().describe(`Filter by id, name, category, tag, or description`)}),output:p.object({services:p.array(KH)}),alias:{query:`q`},async run(e){let t=e.options.query?.toLowerCase(),n=await yU(),r=(t?n.filter(e=>[e.id,e.name,e.description,...Array.isArray(e.categories)?e.categories:[],...Array.isArray(e.tags)?e.tags:[]].filter(e=>typeof e==`string`).some(e=>e.toLowerCase().includes(t))):n).map(eU).sort((e,t)=>e.id.localeCompare(t.id));return YH(e,{services:r},()=>{if(r.length===0){console.log(`No services found.`);return}let e=Math.max(...r.map(e=>e.id.length)),t=Math.max(...r.map(e=>String(e.paidEndpoints).length));for(let n of r){let r=n.name&&n.name!==n.id?` ${n.name}`:``,i=n.url?` ${X.dim(n.url)}`:``;console.log(`${n.id.padEnd(e)} ${String(n.paidEndpoints).padStart(t)} paid${r}${i}`)}})}}).command(`show`,{description:`Show one registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({service:p.record(p.string(),p.unknown())}),async run(e){let t=bU(await yU(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=eU(t),r=$H(t);return YH(e,{service:t},()=>{console.log(`${n.name??n.id} ${X.dim(`(${n.id})`)}`),n.description&&console.log(n.description),n.url&&console.log(`${X.dim(`URL`)} ${pM(n.url,n.url)}`),n.status&&console.log(`${X.dim(`Status`)} ${n.status}`),console.log(`${X.dim(`Endpoints`)} ${r.length} (${n.paidEndpoints} paid)`);let e=t.docs,i=e&&QH(e.homepage);i&&console.log(`${X.dim(`Docs`)} ${pM(i,i)}`)})}}).command(`endpoints`,{description:`List endpoints for a registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({endpoints:p.array(qH),service:KH}),async run(e){let t=bU(await yU(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=eU(t),r=$H(t).map(tU);return YH(e,{endpoints:r,service:n},()=>{if(r.length===0){console.log(`No endpoints found for ${n.id}.`);return}let e=Math.max(...r.map(e=>e.method.length)),t=Math.max(...r.map(e=>e.path.length));for(let n of r){let r=nU(n.payment),i=n.description?` ${X.dim(n.description)}`:``;console.log(`${n.method.padEnd(e)} ${n.path.padEnd(t)} ${r}${i}`)}})}}),EU=vb(`discover`,{description:`Discovery tooling`}).command(`generate`,{description:`Generate a static OpenAPI discovery document from a module`,args:p.object({module:p.string().describe(`Path to a module that default-exports a discovery config`)}),options:p.object({output:p.string().optional().describe(`Write output to a file instead of stdout`)}),output:p.record(p.string(),p.unknown()),alias:{output:`o`},async run(e){let n=c.resolve(e.args.module);if(!t.existsSync(n))return e.error({code:`MODULE_NOT_FOUND`,message:`Module not found: ${n}`,exitCode:1});let r;try{r=await import(n)}catch(t){return e.error({code:`MODULE_IMPORT_FAILED`,message:`Failed to import module: ${t.message}`,exitCode:1})}let i=r.default??r,a;if(typeof i.openapi==`string`)a=i;else{let{generate:t}=await Promise.resolve().then(()=>(VH(),FH)),n=i.mppx;if(!n)return e.error({code:`INVALID_MODULE`,message:"Module must default-export an OpenAPI document (with `openapi` key) or an object with `mppx` (server instance) and `routes`.",exitCode:1});a=t(n,i)}let o=JSON.stringify(a,null,2);if(e.options.output){let n=c.resolve(e.options.output);return t.writeFileSync(n,`${o}\n`),process.stderr.write(`Wrote ${n}\n`),YH(e,a,()=>{})}return YH(e,a,()=>{console.log(o)})}}).command(`validate`,{description:`Validate an OpenAPI discovery document from a file or URL`,args:p.object({input:p.string().describe(`Path or URL to a discovery document`)}),output:p.object({errorCount:p.number(),issues:p.array(GH),valid:p.boolean(),warningCount:p.number()}),async run(e){let n=e.args.input,r;if(/^https?:\/\//.test(n)){let t=new AbortController,i=setTimeout(()=>t.abort(),3e4),a;try{a=await globalThis.fetch(n,{signal:t.signal})}catch(t){clearTimeout(i);let n=t instanceof DOMException&&t.name===`AbortError`?`Request timed out after 30s`:t.message;return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: ${n}`,exitCode:1})}if(clearTimeout(i),!a.ok)return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: HTTP ${a.status}`,exitCode:1});let o=10485760,s=a.headers.get(`content-length`);if(s&&Number(s)>o||(r=await a.text(),r.length>o))return e.error({code:`DISCOVERY_TOO_LARGE`,message:`Discovery document exceeds 10 MB limit`,exitCode:1})}else{let i=c.resolve(n);if(!t.existsSync(i))return e.error({code:`DISCOVERY_NOT_FOUND`,message:`Discovery document not found: ${i}`,exitCode:1});r=t.readFileSync(i,`utf-8`)}let i;try{i=JSON.parse(r)}catch(t){return e.error({code:`DISCOVERY_INVALID_JSON`,message:`Invalid discovery JSON: ${t.message}`,exitCode:1})}let a=dk(i);if(!JH(e))for(let e of a)console.log(`[${e.severity}] ${e.path}: ${e.message}`);let o=a.filter(e=>e.severity===`error`).length,s=a.filter(e=>e.severity===`warning`).length;return o>0?e.error({code:`DISCOVERY_INVALID`,message:`Discovery document has ${o} error(s) and ${s} warning(s).`,exitCode:1}):YH(e,{errorCount:o,issues:a,valid:!0,warningCount:s},()=>{console.log(s>0?`Discovery document is valid with ${s} warning(s).`:`Discovery document is valid.`)})}}),DU=p.object({address:p.string(),id:p.string(),livemode:p.boolean(),network:p.string(),supportedTokens:p.array(p.object({contractAddress:p.string(),currency:p.string()}))}),OU=vb(`stripe`,{description:`Stripe machine payments tooling`}).command(`address`,{description:`Create a Stripe crypto deposit address and print its public address`,usage:[{suffix:`[--network tempo|base|solana] [--env [path]] [--secret-key <key>] [options]`}],options:p.object({customer:p.string().optional().describe(`Scope the address to a Stripe customer (cus_...); it then only accepts their funds`),env:p.string().optional().describe(`Write <NETWORK>_DEPOSIT_ADDRESS to this env file instead of printing (default path: .env)`),live:p.boolean().optional().describe(`Use the Stripe CLI's live mode key instead of its test mode key`),network:p.enum([`tempo`,`base`,`solana`]).default(`tempo`).describe(`Network to create the address on`),projectName:p.string().optional().describe(`Stripe CLI project to read the key from (env: STRIPE_PROJECT_NAME, default: default)`),secretKey:p.string().optional().describe(`Stripe secret key (sk_...); else STRIPE_SECRET_KEY, else the Stripe CLI's login`),stripeAccount:p.string().optional().describe(`Connected account to create the address for (acct_...)`)}),output:DU,alias:{network:`n`},async run(e){let{customer:t,env:n,live:r,network:i,projectName:a,secretKey:o,stripeAccount:s}=e.options;if(n&&t)return e.error({code:`INVALID_OPTIONS`,message:`--env can't be combined with --customer: that address only accepts the customer's funds.`,exitCode:2});let c=uV({live:r,projectName:a,secretKey:o});if(!c)return e.error({code:`MISSING_STRIPE_SECRET_KEY`,message:`No Stripe key found. Pass --secret-key <sk_...>, set STRIPE_SECRET_KEY, or run \`stripe login\` so mppx can read the Stripe CLI's ${r?`live`:`test`} mode key.`,exitCode:2});let l=new URLSearchParams({network:i});t&&l.set(`customer`,t);let u=await globalThis.fetch(new URL(`/v1/crypto/deposit_addresses`,process.env.MPPX_STRIPE_API_URL??`https://api.stripe.com`),{method:`POST`,headers:{Authorization:`Bearer ${c.key}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":fk,...s?{"Stripe-Account":s}:{}},body:l}),d=await u.json().catch(()=>({}));if(!u.ok||!d.address){let t=d.error?.code&&/^[a-z_]+$/.test(d.error.code)?`, ${d.error.code}`:``,n=`HTTP ${u.status}${t}`,r=u.status===401||u.status===403,i=c.source===`stripe-cli`?`the Stripe CLI's login`:c.source===`flag`?`--secret-key`:`STRIPE_SECRET_KEY`,a=r&&c.key.startsWith(`rk_`)?`Stripe refused the restricted key (rk_...) from ${i} for crypto deposit addresses (${n}). Pass a secret key with --secret-key <sk_...> or STRIPE_SECRET_KEY.`:r&&c.source===`stripe-cli`?`Stripe refused the key from the Stripe CLI's login (${n}). Run \`stripe login\` again, or pass --secret-key <sk_...>.`:`Stripe could not create a deposit address (${n}).`;return e.error({code:`STRIPE_REQUEST_FAILED`,message:a,exitCode:1})}if(!gV(i,d.address))return e.error({code:`STRIPE_INVALID_ADDRESS`,message:`Stripe returned a deposit address that isn't a valid ${i} address.`,exitCode:1});let f={address:d.address,id:d.id??``,livemode:d.livemode??!1,network:d.network??i,supportedTokens:(d.supported_tokens??[]).map(e=>({contractAddress:e.token_contract_address,currency:e.token_currency}))};if(n){let t=`${i.toUpperCase()}_DEPOSIT_ADDRESS`;return vV(n,t,f.address),console.error(`Wrote ${t} to ${n}`),YH(e,f,()=>{})}return YH(e,f,()=>console.log(f.address))}});xU.command(SU),xU.command(EU),xU.command(wU),xU.command(TU),xU.command(eV),xU.command(CU),xU.command(OU),xU.command(OH);const kU=xU.serve.bind(xU);xU.serve=(e=process.argv.slice(2),t)=>kU(xV(e),t);export{xU as default,mU as resolveMppCredentialTarget,hU as resolveX402CredentialTarget};