import{t as e}from"./defineProperty-BA9XN-c7.js";function t(e){return Object.freeze({...e,decode:(t,n=0)=>e.read(t,n)[0]})}var n=e=>t({read(t,n){let i=n===0||n<=-t.byteLength?t:t.slice(n);if(i.length===0)return[``,0];let a=i.findIndex(e=>e!==0);a=a===-1?i.length:a;let o=e[0].repeat(a);return a===i.length?[o,t.length]:[o+r(i.slice(a).reduce((e,t)=>e*256n+BigInt(t),0n),e),t.length]}});function r(e,t){let n=BigInt(t.length),r=[];for(;e>0n;)r.unshift(t[Number(e%n)]),e/=n;return r.join(``)}var i=`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`,a=()=>n(i);globalThis.TextDecoder,globalThis.TextEncoder;function o(e){let t=`${e.domain} wants you to sign in with your Solana account:\n`;t+=`${e.address}`,e.statement&&(t+=`\n\n${e.statement}`);let n=[];if(e.uri&&n.push(`URI: ${e.uri}`),e.version&&n.push(`Version: ${e.version}`),e.chainId&&n.push(`Chain ID: ${e.chainId}`),e.nonce&&n.push(`Nonce: ${e.nonce}`),e.issuedAt&&n.push(`Issued At: ${e.issuedAt}`),e.expirationTime&&n.push(`Expiration Time: ${e.expirationTime}`),e.notBefore&&n.push(`Not Before: ${e.notBefore}`),e.requestId&&n.push(`Request ID: ${e.requestId}`),e.resources){n.push(`Resources:`);for(let t of e.resources)n.push(`- ${t}`)}return n.length&&(t+=`\n\n${n.join(` `)}`),t}var s={ERROR_ASSOCIATION_PORT_OUT_OF_RANGE:`ERROR_ASSOCIATION_PORT_OUT_OF_RANGE`,ERROR_REFLECTOR_ID_OUT_OF_RANGE:`ERROR_REFLECTOR_ID_OUT_OF_RANGE`,ERROR_FORBIDDEN_WALLET_BASE_URL:`ERROR_FORBIDDEN_WALLET_BASE_URL`,ERROR_SECURE_CONTEXT_REQUIRED:`ERROR_SECURE_CONTEXT_REQUIRED`,ERROR_SESSION_CLOSED:`ERROR_SESSION_CLOSED`,ERROR_SESSION_TIMEOUT:`ERROR_SESSION_TIMEOUT`,ERROR_WALLET_NOT_FOUND:`ERROR_WALLET_NOT_FOUND`,ERROR_INVALID_PROTOCOL_VERSION:`ERROR_INVALID_PROTOCOL_VERSION`,ERROR_BROWSER_NOT_SUPPORTED:`ERROR_BROWSER_NOT_SUPPORTED`,ERROR_LOOPBACK_ACCESS_BLOCKED:`ERROR_LOOPBACK_ACCESS_BLOCKED`,ERROR_ASSOCIATION_CANCELLED:`ERROR_ASSOCIATION_CANCELLED`},c=class extends Error{constructor(...t){let[n,r,i]=t;super(r),e(this,`data`,void 0),e(this,`code`,void 0),this.code=n,this.data=i,this.name=`SolanaMobileWalletAdapterError`}},l=class extends Error{constructor(...t){let[n,r,i,a]=t;super(i),e(this,`data`,void 0),e(this,`code`,void 0),e(this,`jsonRpcMessageId`,void 0),this.code=r,this.data=a,this.jsonRpcMessageId=n,this.name=`SolanaMobileWalletAdapterProtocolError`}};function u(e){return window.btoa(e)}function d(e,t){let n=window.btoa(String.fromCharCode.call(null,...e));return t?n.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``):n}function f(e){return new Uint8Array(window.atob(e).split(``).map(e=>e.charCodeAt(0)))}async function p(e,t){let n=await crypto.subtle.exportKey(`raw`,e),r=await crypto.subtle.sign({hash:`SHA-256`,name:`ECDSA`},t,n),i=new Uint8Array(n.byteLength+r.byteLength);return i.set(new Uint8Array(n),0),i.set(new Uint8Array(r),n.byteLength),i}function m(e){return a().decode(e)}function h(e){return m(f(e))}function g(e){return o(e)}function _(e){return u(g(e)).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}var v=`solana:signTransactions`,y=`solana:cloneAuthorization`;function b(e,t){return new Proxy({},{get(n,r){return r===`then`?null:(n[r]??(n[r]=async function(n){let{method:i,params:a}=x(r,n,e),o=await t(i,a);return i===`authorize`&&a.sign_in_payload&&!o.sign_in_result&&(o.sign_in_result=await C(a.sign_in_payload,o,t)),S(r,o,e)}),n[r])},defineProperty(){return!1},deleteProperty(){return!1}})}function x(e,t,n){let r=t,i=e.toString().replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`).toLowerCase();switch(e){case`authorize`:{let e=r,{chain:t}=e;if(n===`legacy`){switch(t){case`solana:testnet`:t=`testnet`;break;case`solana:devnet`:t=`devnet`;break;case`solana:mainnet`:t=`mainnet-beta`;break;default:t=e.cluster}e.cluster=t,r=e}else{switch(t){case`testnet`:case`devnet`:t=`solana:${t}`;break;case`mainnet-beta`:t=`solana:mainnet`;break}e.chain=t,r=e}}case`reauthorize`:{let{auth_token:e,identity:t}=r;if(e)switch(n){case`legacy`:i=`reauthorize`,r={auth_token:e,identity:t};break;default:i=`authorize`;break}break}}return{method:i,params:r}}function S(e,t,n){switch(e){case`getCapabilities`:{let e=t;switch(n){case`legacy`:{let t=[v];return e.supports_clone_authorization===!0&&t.push(y),{...e,features:t}}case`v1`:return{...e,supports_sign_and_send_transactions:!0,supports_clone_authorization:e.features.includes(y)}}}}return t}async function C(e,t,n){let r=e.domain??window.location.host,i=t.accounts[0].address,a=_({...e,domain:r,address:h(i)}),o=f((await n(`sign_messages`,{addresses:[i],payloads:[a]})).signed_payloads[0]),s=d(o.slice(0,o.length-64)),c=d(o.slice(o.length-64));return{address:i,signed_message:s.length==0?a:s,signature:c}}function w(e){if(e>=4294967296)throw Error(`Outbound sequence number overflow. The maximum sequence number is 32-bytes.`);let t=new ArrayBuffer(4);return new DataView(t).setUint32(0,e,!1),new Uint8Array(t)}var T=12;async function E(e,t,n){let r=w(t),i=new Uint8Array(T);crypto.getRandomValues(i);let a=await crypto.subtle.encrypt(O(r,i),n,new TextEncoder().encode(e)),o=new Uint8Array(r.byteLength+i.byteLength+a.byteLength);return o.set(new Uint8Array(r),0),o.set(new Uint8Array(i),r.byteLength),o.set(new Uint8Array(a),r.byteLength+i.byteLength),o}async function D(e,t){let n=e.slice(0,4),r=e.slice(4,4+T),i=e.slice(4+T),a=await crypto.subtle.decrypt(O(n,r),t,i);return ee().decode(a)}function O(e,t){return{additionalData:e,iv:t,name:`AES-GCM`,tagLength:128}}var k;function ee(){return k===void 0&&(k=new TextDecoder(`utf-8`)),k}async function A(){return await crypto.subtle.generateKey({name:`ECDSA`,namedCurve:`P-256`},!1,[`sign`])}async function j(){return await crypto.subtle.generateKey({name:`ECDH`,namedCurve:`P-256`},!1,[`deriveKey`,`deriveBits`])}function M(e){let t=``,n=new Uint8Array(e),r=n.byteLength;for(let e=0;e65535)throw new c(s.ERROR_ASSOCIATION_PORT_OUT_OF_RANGE,`Association port number must be between 49152 and 65535. ${e} given.`,{port:e});return e}function F(e){return e.replace(/[/+=]/g,e=>({"/":`_`,"+":`-`,"=":`.`})[e])}var I=`solana-wallet`;function L(e){return e.replace(/(^\/+|\/+$)/g,``).split(`/`)}function R(e,t){let n=null;if(t){try{n=new URL(t)}catch{}if(n?.protocol!==`https:`)throw new c(s.ERROR_FORBIDDEN_WALLET_BASE_URL,"Base URLs supplied by wallets must be valid `https` URLs")}n||(n=new URL(`${I}:/`));let r=e.startsWith(`/`)?e:[...L(n.pathname),...L(e)].join(`/`);return new URL(r,n)}async function z(e,t,n,r=[`v1`]){let i=P(t),a=M(await crypto.subtle.exportKey(`raw`,e)),o=R(`v1/associate/local`,n);return o.searchParams.set(`association`,F(a)),o.searchParams.set(`port`,`${i}`),r.forEach(e=>{o.searchParams.set(`v`,e)}),o}async function B(e,t,n,r,i=[`v1`]){let a=M(await crypto.subtle.exportKey(`raw`,e)),o=R(`v1/associate/remote`,r);return o.searchParams.set(`association`,F(a)),o.searchParams.set(`reflector`,`${t}`),o.searchParams.set(`id`,`${d(n,!0)}`),i.forEach(e=>{o.searchParams.set(`v`,e)}),o}async function V(e,t){let n=JSON.stringify(e),r=e.id;return E(n,r,t)}async function H(e,t){let n=await D(e,t),r=JSON.parse(n);if(Object.hasOwnProperty.call(r,`error`))throw new l(r.id,r.error.code,r.error.message);return r}async function U(e,t,n){let[r,i]=await Promise.all([crypto.subtle.exportKey(`raw`,t),crypto.subtle.importKey(`raw`,e.slice(0,65),{name:`ECDH`,namedCurve:`P-256`},!1,[])]),a=await crypto.subtle.deriveBits({name:`ECDH`,public:i},n,256),o=await crypto.subtle.importKey(`raw`,a,`HKDF`,!1,[`deriveKey`]);return await crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:new Uint8Array(r),info:new Uint8Array},o,{name:`AES-GCM`,length:128},!1,[`encrypt`,`decrypt`])}async function W(e,t){let n=await D(e,t),r=JSON.parse(n),i=`legacy`;if(Object.hasOwnProperty.call(r,`v`))switch(r.v){case 1:case`1`:case`v1`:i=`v1`;break;case`legacy`:i=`legacy`;break;default:throw new c(s.ERROR_INVALID_PROTOCOL_VERSION,`Unknown/unsupported protocol version: ${r.v}`)}return{protocol_version:i}}var G={Firefox:0,Other:1};function te(){return navigator.userAgent.indexOf(`Firefox/`)===-1?G.Other:G.Firefox}function ne(){return new Promise((e,t)=>{function n(){clearTimeout(i),window.removeEventListener(`blur`,r)}function r(){n(),e()}window.addEventListener(`blur`,r);let i=setTimeout(()=>{n(),t()},3e3)})}var K=null;function re(e){K??(K=document.createElement(`iframe`),K.style.display=`none`,document.body.appendChild(K)),K.contentWindow.location.href=e.toString()}async function ie(e){if(e.protocol===`https:`)window.location.assign(e);else try{switch(te()){case G.Firefox:re(e);break;case G.Other:{let t=ne();window.location.assign(e),await t;break}default:}}catch{throw new c(s.ERROR_WALLET_NOT_FOUND,`Found no installed wallet that supports the mobile wallet protocol.`)}}async function ae(e,t){let n=N();return await ie(await z(e,n,t)),n}var q={retryDelayScheduleMs:[150,150,200,500,500,750,750,1e3],timeoutMs:3e4},J=`com.solana.mobilewalletadapter.v1`,Y=`com.solana.mobilewalletadapter.v1.base64`;function X(){if(typeof window>`u`||window.isSecureContext!==!0)throw new c(s.ERROR_SECURE_CONTEXT_REQUIRED,"The mobile wallet adapter protocol must be used in a secure context (`https`).")}function Z(e){let t;try{t=new URL(e)}catch{throw new c(s.ERROR_FORBIDDEN_WALLET_BASE_URL,`Invalid base URL supplied by wallet`)}if(t.protocol!==`https:`)throw new c(s.ERROR_FORBIDDEN_WALLET_BASE_URL,"Base URLs supplied by wallets must be valid `https` URLs")}function Q(e){return new DataView(e).getUint32(0,!1)}function oe(e){let t=new Uint8Array(e),n=e.byteLength,r=0,i=0,a;do{if(i>=n||i>10)throw RangeError(`Failed to decode varint`);a=t[i++],r|=(a&127)<<7*i}while(a>=128);return{value:r,offset:i}}function se(e){let{value:t,offset:n}=oe(e);return new Uint8Array(e.slice(n,n+t))}async function ce(e,t){let{wallet:n,close:r}=await $(t);try{return await e(await n)}finally{r()}}async function $(e){X();let t=await A(),n=`ws://localhost:${await ae(t.publicKey,e?.baseUri)}/solana-wallet`,r,i=(()=>{let e=[...q.retryDelayScheduleMs];return()=>e.length>1?e.shift():e[0]})(),a=1,o=0,u={__type:`disconnected`},d,f=!1,m;return{close:()=>{d.close(),m()},wallet:new Promise((e,h)=>{let g={},_=async()=>{if(u.__type!==`connecting`){console.warn(`Expected adapter state to be \`connecting\` at the moment the websocket opens. Got \`${u.__type}\`.`);return}d.removeEventListener(`open`,_);let{associationKeypair:e}=u,t=await j();d.send(await p(t.publicKey,e.privateKey)),u={__type:`hello_req_sent`,associationPublicKey:e.publicKey,ecdhPrivateKey:t.privateKey}},v=e=>{e.wasClean?u={__type:`disconnected`}:h(new c(s.ERROR_SESSION_CLOSED,`The wallet session dropped unexpectedly (${e.code}: ${e.reason}).`,{closeEvent:e})),S()},y=async e=>{S(),Date.now()-r>=q.timeoutMs?h(new c(s.ERROR_SESSION_TIMEOUT,`Failed to connect to the wallet websocket at ${n}.`)):(await new Promise(e=>{let t=i();C=window.setTimeout(e,t)}),w())},x=async n=>{let r=await n.data.arrayBuffer();switch(u.__type){case`connecting`:{if(r.byteLength!==0)throw Error(`Encountered unexpected message while connecting`);let e=await j();d.send(await p(e.publicKey,t.privateKey)),u={__type:`hello_req_sent`,associationPublicKey:t.publicKey,ecdhPrivateKey:e.privateKey};break}case`connected`:try{let e=Q(r.slice(0,4));if(e!==o+1)throw Error(`Encrypted message has invalid sequence number`);o=e;let t=await H(r,u.sharedSecret),n=g[t.id];delete g[t.id],n.resolve(t.result)}catch(e){if(e instanceof l){let t=g[e.jsonRpcMessageId];delete g[e.jsonRpcMessageId],t.reject(e)}else throw e}break;case`hello_req_sent`:{if(r.byteLength===0){let e=await j();d.send(await p(e.publicKey,t.privateKey)),u={__type:`hello_req_sent`,associationPublicKey:t.publicKey,ecdhPrivateKey:e.privateKey};break}let n=await U(r,u.associationPublicKey,u.ecdhPrivateKey),i=r.slice(65),s=i.byteLength===0?{protocol_version:`legacy`}:await(async()=>{let e=Q(i.slice(0,4));if(e!==o+1)throw Error(`Encrypted message has invalid sequence number`);return o=e,W(i,n)})();u={__type:`connected`,sharedSecret:n,sessionProperties:s};let c=b(s.protocol_version,async(e,t)=>{let r=a++;return d.send(await V({id:r,jsonrpc:`2.0`,method:e,params:t??{}},n)),new Promise((t,n)=>{g[r]={resolve(r){switch(e){case`authorize`:case`reauthorize`:{let{wallet_uri_base:e}=r;if(e!=null)try{Z(e)}catch(e){n(e);return}break}}t(r)},reject:n}})});f=!0;try{e(c)}catch(e){h(e)}break}}};m=()=>{d.removeEventListener(`message`,x),S(),f||h(new c(s.ERROR_SESSION_CLOSED,`The wallet session was closed before connection.`,{closeEvent:new CloseEvent(`socket was closed before connection`)}))};let S,C,w=()=>{S&&S(),u={__type:`connecting`,associationKeypair:t},r===void 0&&(r=Date.now()),d=new WebSocket(n,[J]),d.addEventListener(`open`,_),d.addEventListener(`close`,v),d.addEventListener(`error`,y),d.addEventListener(`message`,x),S=()=>{window.clearTimeout(C),d.removeEventListener(`open`,_),d.removeEventListener(`close`,v),d.removeEventListener(`error`,y),d.removeEventListener(`message`,x)}};w()})}}async function le(e){X();let t=await A(),n=`wss://${e?.remoteHostAuthority}/reflect`,r,i=(()=>{let e=[...q.retryDelayScheduleMs];return()=>e.length>1?e.shift():e[0]})(),a=1,o=0,u,m={__type:`disconnected`},h,g,_=async e=>u==`base64`?f(await e.data).buffer:await e.data.arrayBuffer(),v=await new Promise((a,o)=>{let l=async()=>{if(m.__type!==`connecting`){console.warn(`Expected adapter state to be \`connecting\` at the moment the websocket opens. Got \`${m.__type}\`.`);return}u=h.protocol.includes(Y)?`base64`:`binary`,h.removeEventListener(`open`,l)},d=e=>{e.wasClean?m={__type:`disconnected`}:o(new c(s.ERROR_SESSION_CLOSED,`The wallet session dropped unexpectedly (${e.code}: ${e.reason}).`,{closeEvent:e})),g()},f=async e=>{g(),Date.now()-r>=q.timeoutMs?o(new c(s.ERROR_SESSION_TIMEOUT,`Failed to connect to the wallet websocket at ${n}.`)):(await new Promise(e=>{let t=i();v=window.setTimeout(e,t)}),y())},p=async n=>{let r=await _(n);if(m.__type===`connecting`){if(r.byteLength==0)throw Error(`Encountered unexpected message while connecting`);let n=se(r);m={__type:`reflector_id_received`,reflectorId:n};let i=await B(t.publicKey,e.remoteHostAuthority,n,e?.baseUri);h.removeEventListener(`message`,p),a(i)}},v,y=()=>{g&&g(),m={__type:`connecting`,associationKeypair:t},r===void 0&&(r=Date.now()),h=new WebSocket(n,[J,Y]),h.addEventListener(`open`,l),h.addEventListener(`close`,d),h.addEventListener(`error`,f),h.addEventListener(`message`,p),g=()=>{window.clearTimeout(v),h.removeEventListener(`open`,l),h.removeEventListener(`close`,d),h.removeEventListener(`error`,f),h.removeEventListener(`message`,p)}};y()}),y=!1,x;return{associationUrl:v,close:()=>{h.close(),x()},wallet:new Promise((e,n)=>{let r={},i=async i=>{let s=await _(i);switch(m.__type){case`reflector_id_received`:{if(s.byteLength!==0)throw Error(`Encountered unexpected message while awaiting reflection`);let e=await j(),n=await p(e.publicKey,t.privateKey);u==`base64`?h.send(d(n)):h.send(n),m={__type:`hello_req_sent`,associationPublicKey:t.publicKey,ecdhPrivateKey:e.privateKey};break}case`connected`:try{let e=Q(s.slice(0,4));if(e!==o+1)throw Error(`Encrypted message has invalid sequence number`);o=e;let t=await H(s,m.sharedSecret),n=r[t.id];delete r[t.id],n.resolve(t.result)}catch(e){if(e instanceof l){let t=r[e.jsonRpcMessageId];delete r[e.jsonRpcMessageId],t.reject(e)}else throw e}break;case`hello_req_sent`:{let t=await U(s,m.associationPublicKey,m.ecdhPrivateKey),i=s.slice(65),c=i.byteLength===0?{protocol_version:`legacy`}:await(async()=>{let e=Q(i.slice(0,4));if(e!==o+1)throw Error(`Encrypted message has invalid sequence number`);return o=e,W(i,t)})();m={__type:`connected`,sharedSecret:t,sessionProperties:c};let l=b(c.protocol_version,async(e,n)=>{let i=a++,o=await V({id:i,jsonrpc:`2.0`,method:e,params:n??{}},t);return u==`base64`?h.send(d(o)):h.send(o),new Promise((t,n)=>{r[i]={resolve(r){switch(e){case`authorize`:case`reauthorize`:{let{wallet_uri_base:e}=r;if(e!=null)try{Z(e)}catch(e){n(e);return}break}}t(r)},reject:n}})});y=!0;try{e(l)}catch(e){n(e)}break}}};h.addEventListener(`message`,i),x=()=>{h.removeEventListener(`message`,i),g(),y||n(new c(s.ERROR_SESSION_CLOSED,`The wallet session was closed before connection.`,{closeEvent:new CloseEvent(`socket was closed before connection`)}))}})}}export{ce as a,$ as i,s as n,le as r,c as t};