@human.tech/waap-sdk 2.4.2-staging-416db8 → 2.4.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.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @human.tech/waap-sdk
2
2
 
3
- ## 2.4.2-staging-416db8
3
+ ## 2.4.2
4
4
 
5
5
  ### Patch Changes
6
6
 
@@ -1 +1 @@
1
- import{S as e,c as t,d as n,f as r,l as i,m as a,o,t as s,v as c,w as l,x as u}from"./UIMessageManager-D3VN9vM8.mjs";import{EventEmitter as d}from"events";var f=class{constructor(e,t={},r,i=t,a=!0){this.ownsSession=a,this.lastKnownConversion=`pending`,this.name=`WaaP`,this.version=`1.0.0`,this.icon=`data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCI+PHJlY3Qgd2lkdGg9IjY0IiBoZWlnaHQ9IjY0IiByeD0iMTYiIGZpbGw9IiMxMTE4MmMiLz48cGF0aCBkPSJNMTYgNDhoMzJMMzIgMTZ6IiBmaWxsPSIjN2NkNGZmIi8+PC9zdmc+`,this._accounts=[],this.accountMode=`tap`,this.loginMethod=null,this._chains=[`solana:mainnet`,`solana:devnet`,`solana:testnet`],this.internalEventEmitter=new d,this.changeListeners=new Set,this.initializerPromise=null,this.initializedIframeWindow=null,this.defaultChain=this.asSupportedChain(t.defaultChain)??`solana:mainnet`,this.walletMessageManager=new n(e,c(t)),this.ensureIframe=r,this.iframeMounted=!r,this.initializerOptions=i,this.uiMessageManager=new s,this.walletMessageManager.addListener({handleResponse:e=>{this.internalEventEmitter.emit(e.id,e)},handleRequest:e=>{e.method===l.show_modal?this.uiMessageManager.emit(`show_modal`):e.method===l.hide_modal&&this.uiMessageManager.emit(`hide_modal`)},onAccountChanged:async()=>{try{let e=await this.refreshAccounts();this.notifyChange({accounts:e.accounts})}catch(e){console.error(`Failed to refresh Solana accounts:`,e),this._accounts=[],this.notifyChange({accounts:[]})}}})}destroy(){this.walletMessageManager.dispose(),this.internalEventEmitter.removeAllListeners(),this.uiMessageManager.removeAllListeners(),this.changeListeners.clear(),this._accounts=[]}ensureIframeMounted(){if(this.iframeMounted||!this.ensureIframe)return;let e=this.ensureIframe();if(!e)throw Error(`Failed to create WaaP iframe`);this.iframeMounted=!0,this.walletMessageManager.setIframeWindow(e)}async preload(){if(!this.ensureIframe)return;this.ensureIframeMounted();let e=this.walletMessageManager.getIframeWindow();if(!e)throw Error(`WaaP iframe is not mounted`);if(this.initializedIframeWindow===e&&this.initializerPromise)return this.initializerPromise;this.initializedIframeWindow=e,this.initializerPromise=a(e,()=>this.selectAccountMode(this.accountMode,this.initializerOptions));try{await this.initializerPromise}catch(e){throw this.initializerPromise=null,this.initializedIframeWindow=null,e}}async ensureInitialized(){await this.preload()}get chains(){return this._chains}get accounts(){return this._accounts}get features(){return{"standard:connect":{version:`1.0.0`,connect:this.connect.bind(this)},"standard:disconnect":{version:`1.0.0`,disconnect:this.disconnect.bind(this)},"standard:events":{version:`1.0.0`,on:this.on.bind(this)},"solana:signMessage":{version:`1.1.0`,signMessage:this.signStandardMessages.bind(this)},"solana:signTransaction":{version:`1.0.0`,supportedTransactionVersions:[`legacy`,0],signTransaction:this.signStandardTransactions.bind(this)},"solana:signAndSendTransaction":{version:`1.0.0`,supportedTransactionVersions:[`legacy`,0],signAndSendTransaction:this.signAndSendStandardTransactions.bind(this)}}}get ui(){return this.uiMessageManager}getAccountStatus(){return{authenticated:this.loginMethod!==null,loginMethod:this.loginMethod,activeMode:this.loginMethod?this.accountMode:null,mode:this.accountMode,conversion:this.loginMethod?this.lastKnownConversion:`not_required`,tap:null,squid:null,accounts:this._accounts[0]?{solana:this._accounts[0].address}:{}}}get session(){return{login:()=>this.login(),logout:()=>this.logout(),getLoginMethod:()=>this.getLoginMethod(),getAccountStatus:()=>this.getCanonicalAccountStatus()}}async getCanonicalAccountStatus(e){await this.ensureInitialized();let t=await this.postRequestAndWait({method:l.waap_getAccountStatus,params:[],interactionRequired:!1,signal:e?.signal,timeoutMs:e?.timeoutMs});if(t.error)throw Error(t.error.message||`Failed to read WaaP status`);let n=t.data;return this.syncLoginMethodFromCanonicalStatus(n),n?.conversion&&(this.lastKnownConversion=n.conversion),n}setAccountMode(e){this.accountMode=e,this.initializerPromise=null,this.initializedIframeWindow=null}async selectAccountMode(e,t={}){await this.walletMessageManager.pingIframe(),await this.postRequestAndWait({method:l.set_signing_mode,params:[r(e,t)],interactionRequired:!1})}setLoginMethod(e){this.loginMethod=e,e===null&&(this._accounts=[],this.notifyChange({accounts:[]}))}getLoginMethod(){return this.loginMethod}async login(e){await this.ensureInitialized();let t=await this.restoreSession(e);if(t)return t;let n=(await this.postRequestAndWait({method:l.login,params:[],interactionRequired:!0,signal:e?.signal,timeoutMs:e?.timeoutMs})).data;return n!==`waap`&&n!==`human`&&n!==`injected`&&n!==`walletconnect`?(this.setLoginMethod(null),null):(this.loginMethod=n,n)}async logout(){this.lastKnownConversion=`pending`,await this.ensureInitialized(),await this.postRequestAndWait({method:l.logout,params:[],interactionRequired:!1}),this.loginMethod=null,this._accounts=[],this.notifyChange({accounts:[]})}async refreshAccounts(){try{await this.ensureInitialized();let e=await this.postRequestAndWait({method:`solana_connect`,params:[{silent:!0}],interactionRequired:!1});if(e.error)return this._accounts=[],{accounts:[]};let t=this.normalizeAccounts(e.data?.accounts||[]);return this._accounts=t,{accounts:this._accounts}}catch{return this._accounts=[],{accounts:[]}}}normalizeAccounts(e){return e.map(e=>({address:e.address,publicKey:e.publicKey instanceof Uint8Array?e.publicKey:new Uint8Array(e.publicKey??[]),chains:e.chains??this._chains,features:e.features??[]}))}async connect(e){if(e?.signal?.aborted)throw new u(`cancelled`,`WaaP connect cancelled.`,{operation:{chain:`solana`,method:`solana_connect`}});if(!this.ownsSession&&!this.loginMethod)throw new u(`not_authenticated`,`Not authenticated: call session.login() before connect().`,{operation:{chain:`solana`,method:`solana_connect`}});if(await this.ensureInitialized(),this.ownsSession&&e?.silent){try{await this.getCanonicalAccountStatus(e)}catch(e){throw this.setLoginMethod(null),e}if(!this.loginMethod)return{accounts:[]}}else if(this.ownsSession&&!await this.login(e))throw new u(`user_rejected`,`User rejected WaaP login during connect().`,{operation:{chain:`solana`,method:`solana_connect`}});let t=await this.postRequestAndWait({method:`solana_connect`,params:[e||{}],interactionRequired:!e?.silent,signal:e?.signal,timeoutMs:e?.timeoutMs});if(t.error)throw Error(t.error.message||`Failed to connect`);let n=this.normalizeAccounts(t.data?.accounts||[]);return this._accounts=n,this.notifyChange({accounts:this._accounts}),e?.silent||this.internalEventEmitter.emit(`connect`),this.internalEventEmitter.emit(`accountsChanged`,this._accounts.map(e=>e.address)),{accounts:this._accounts}}async restoreSession(e){try{let t=await this.getCanonicalAccountStatus(e);if(t.authenticated&&(t.loginMethod===`waap`||t.loginMethod===`human`||t.loginMethod===`injected`||t.loginMethod===`walletconnect`))return this.loginMethod=t.loginMethod,t.loginMethod}catch(e){if(e instanceof u&&(e.code===`cancelled`||e.code===`timeout`))throw e}return null}syncLoginMethodFromCanonicalStatus(e){let t=e.authenticated&&(e.loginMethod===`waap`||e.loginMethod===`human`||e.loginMethod===`injected`||e.loginMethod===`walletconnect`)?e.loginMethod:null;t!==this.loginMethod&&this.setLoginMethod(t)}async disconnect(){await this.ensureInitialized(),await this.postRequestAndWait({method:`solana_disconnect`,params:[],interactionRequired:!1}),this._accounts=[],this.notifyChange({accounts:[]})}async signMessage(e){await this.ensureInitialized();let t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw Error(`Account ${t} is not connected`);let n=await this.postRequestAndWait({method:`solana_signMessage`,params:[{message:Array.from(e.message),account:t}],interactionRequired:!0,signal:e.signal,timeoutMs:e.timeoutMs});if(n.error)throw Error(n.error.message||`Failed to sign message`);return{signedMessage:new Uint8Array(n.data.signedMessage),signature:new Uint8Array(n.data.signature)}}async signTransaction(e){await this.ensureInitialized();let t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw Error(`Account ${t} is not connected`);let n=this.resolveTransactionBytes(e.transaction),r=await this.postRequestAndWait({method:`solana_signTransaction`,params:[{transaction:Array.from(n),account:t,chain:this.asSupportedChain(e.chain)??this.defaultChain,withPT:e.withPT}],interactionRequired:!0,signal:e.signal,timeoutMs:e.timeoutMs});if(r.error)throw Error(r.error.message||`Failed to sign transaction`);return{signedTransaction:new Uint8Array(r.data.signedTransaction),signature:new Uint8Array(r.data.signature)}}async signAndSendTransaction(e){await this.ensureInitialized();let t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw Error(`Account ${t} is not connected`);let n=this.resolveTransactionBytes(e.transaction),r=await this.postRequestAndWait({method:`solana_signAndSendTransaction`,params:[{transaction:Array.from(n),account:t,chain:this.asSupportedChain(e.chain)??this.defaultChain,options:e.options,withPT:e.withPT}],interactionRequired:!0,signal:e.signal,timeoutMs:e.timeoutMs});if(r.error)throw Error(r.error.message||`Failed to sign and send transaction`);return{signature:r.data.signature}}async signStandardMessages(...e){let t=[];for(let n of e){let e=await this.signMessage({account:n.account,message:n.message});t.push({...e,signatureType:`ed25519`})}return t}async signStandardTransactions(...e){let t=[];for(let n of e){let e=await this.signTransaction({account:n.account,transaction:n.transaction,chain:this.asSupportedChain(n.chain)});t.push({signedTransaction:e.signedTransaction})}return t}async signAndSendStandardTransactions(...e){let t=[];for(let n of e){let e=await this.signAndSendTransaction({account:n.account,transaction:n.transaction,chain:this.asSupportedChain(n.chain),options:this.broadcastOptions(n.options)});t.push({signature:p(e.signature)})}return t}asSupportedChain(e){if(e!==void 0){if(this._chains.includes(e))return e;throw new u(`unsupported_input`,`Unsupported Solana Wallet Standard chain: ${e}`,{operation:{chain:`solana`,method:`wallet_standard`}})}}broadcastOptions(e){if(e?.commitment!==void 0)throw new u(`unsupported_input`,`WaaP returns a submitted signature; confirm the transaction with the dapp RPC instead of setting commitment.`,{operation:{chain:`solana`,method:`wallet_standard`}});return e?{preflightCommitment:e.preflightCommitment,minContextSlot:e.minContextSlot,skipPreflight:e.skipPreflight,maxRetries:e.maxRetries}:void 0}async requestPermissionToken(e){await this.ensureInitialized();let t={...e,walletMode:this.accountMode},n=await this.postRequestAndWait({method:l.waap_requestPermissionToken,params:[t],interactionRequired:!0});if(n.error)throw Error(n.error.message||`Failed to request permission token`);return n.data}async getPermissionTokenStatus(e){return await this.ensureInitialized(),(await this.postRequestAndWait({method:l.waap_getPermissionTokenStatus,params:[e],interactionRequired:!1})).data}async clearPermissionToken(e){return await this.ensureInitialized(),(await this.postRequestAndWait({method:l.waap_clearPermissionToken,params:[e],interactionRequired:!1})).data}resolveTransactionBytes(e){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return new Uint8Array(e);if(e&&typeof e.serialize==`function`){let t=e.serialize();return t instanceof Uint8Array?t:new Uint8Array(t)}throw Error(`Unsupported transaction format. Pass serialized bytes or a @solana/web3.js Transaction.`)}on(e,t){return e===`change`?(this.changeListeners.add(t),()=>{this.changeListeners.delete(t)}):(this.internalEventEmitter.on(e,t),()=>{this.internalEventEmitter.removeListener(e,t)})}removeListener(e,t){if(e===`change`){this.changeListeners.delete(t);return}this.internalEventEmitter.removeListener(e,t)}async postRequestAndWait(n){let r;try{n.interactionRequired&&i({layout:n.method===l.login?`auth`:`signing`}),r=await this.walletMessageManager.postSilkRequest({method:n.method,params:n.params,interactionRequired:n.interactionRequired});let e=await o({eventEmitter:this.internalEventEmitter,id:r,method:n.method,interactionRequired:n.interactionRequired,signal:n.signal,timeoutMs:n.timeoutMs,onCancel:()=>{this.walletMessageManager.cancelSilkRequest(r,n.method),n.interactionRequired&&t()}});if(e.error)throw Error(e.error.message);return e}catch(i){throw n.interactionRequired&&r===void 0&&t(),e(i,{chain:`solana`,method:String(n.method),requestId:r})}}notifyChange(e){Array.from(this.changeListeners).forEach(t=>{t(e)})}};function p(e){let t=[];for(let n of e){let e=`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`.indexOf(n);if(e<0)throw Error(`Invalid base58 transaction signature`);for(let n=0;n<t.length;n+=1)e+=t[n]*58,t[n]=e&255,e>>=8;for(;e>0;)t.push(e&255),e>>=8}let n=0;for(;n<e.length&&e[n]===`1`;)n+=1;return new Uint8Array([...Array(n).fill(0),...t.reverse()])}export{f as t};
1
+ import{S as e,c as t,d as n,f as r,l as i,m as a,o,t as s,v as c,w as l,x as u}from"./UIMessageManager-BSJdvCEF.mjs";import{EventEmitter as d}from"events";var f=class{constructor(e,t={},r,i=t,a=!0){this.ownsSession=a,this.lastKnownConversion=`pending`,this.name=`WaaP`,this.version=`1.0.0`,this.icon=`data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCI+PHJlY3Qgd2lkdGg9IjY0IiBoZWlnaHQ9IjY0IiByeD0iMTYiIGZpbGw9IiMxMTE4MmMiLz48cGF0aCBkPSJNMTYgNDhoMzJMMzIgMTZ6IiBmaWxsPSIjN2NkNGZmIi8+PC9zdmc+`,this._accounts=[],this.accountMode=`tap`,this.loginMethod=null,this._chains=[`solana:mainnet`,`solana:devnet`,`solana:testnet`],this.internalEventEmitter=new d,this.changeListeners=new Set,this.initializerPromise=null,this.initializedIframeWindow=null,this.defaultChain=this.asSupportedChain(t.defaultChain)??`solana:mainnet`,this.walletMessageManager=new n(e,c(t)),this.ensureIframe=r,this.iframeMounted=!r,this.initializerOptions=i,this.uiMessageManager=new s,this.walletMessageManager.addListener({handleResponse:e=>{this.internalEventEmitter.emit(e.id,e)},handleRequest:e=>{e.method===l.show_modal?this.uiMessageManager.emit(`show_modal`):e.method===l.hide_modal&&this.uiMessageManager.emit(`hide_modal`)},onAccountChanged:async()=>{try{let e=await this.refreshAccounts();this.notifyChange({accounts:e.accounts})}catch(e){console.error(`Failed to refresh Solana accounts:`,e),this._accounts=[],this.notifyChange({accounts:[]})}}})}destroy(){this.walletMessageManager.dispose(),this.internalEventEmitter.removeAllListeners(),this.uiMessageManager.removeAllListeners(),this.changeListeners.clear(),this._accounts=[]}ensureIframeMounted(){if(this.iframeMounted||!this.ensureIframe)return;let e=this.ensureIframe();if(!e)throw Error(`Failed to create WaaP iframe`);this.iframeMounted=!0,this.walletMessageManager.setIframeWindow(e)}async preload(){if(!this.ensureIframe)return;this.ensureIframeMounted();let e=this.walletMessageManager.getIframeWindow();if(!e)throw Error(`WaaP iframe is not mounted`);if(this.initializedIframeWindow===e&&this.initializerPromise)return this.initializerPromise;this.initializedIframeWindow=e,this.initializerPromise=a(e,()=>this.selectAccountMode(this.accountMode,this.initializerOptions));try{await this.initializerPromise}catch(e){throw this.initializerPromise=null,this.initializedIframeWindow=null,e}}async ensureInitialized(){await this.preload()}get chains(){return this._chains}get accounts(){return this._accounts}get features(){return{"standard:connect":{version:`1.0.0`,connect:this.connect.bind(this)},"standard:disconnect":{version:`1.0.0`,disconnect:this.disconnect.bind(this)},"standard:events":{version:`1.0.0`,on:this.on.bind(this)},"solana:signMessage":{version:`1.1.0`,signMessage:this.signStandardMessages.bind(this)},"solana:signTransaction":{version:`1.0.0`,supportedTransactionVersions:[`legacy`,0],signTransaction:this.signStandardTransactions.bind(this)},"solana:signAndSendTransaction":{version:`1.0.0`,supportedTransactionVersions:[`legacy`,0],signAndSendTransaction:this.signAndSendStandardTransactions.bind(this)}}}get ui(){return this.uiMessageManager}getAccountStatus(){return{authenticated:this.loginMethod!==null,loginMethod:this.loginMethod,activeMode:this.loginMethod?this.accountMode:null,mode:this.accountMode,conversion:this.loginMethod?this.lastKnownConversion:`not_required`,tap:null,squid:null,accounts:this._accounts[0]?{solana:this._accounts[0].address}:{}}}get session(){return{login:()=>this.login(),logout:()=>this.logout(),getLoginMethod:()=>this.getLoginMethod(),getAccountStatus:()=>this.getCanonicalAccountStatus()}}async getCanonicalAccountStatus(e){await this.ensureInitialized();let t=await this.postRequestAndWait({method:l.waap_getAccountStatus,params:[],interactionRequired:!1,signal:e?.signal,timeoutMs:e?.timeoutMs});if(t.error)throw Error(t.error.message||`Failed to read WaaP status`);let n=t.data;return this.syncLoginMethodFromCanonicalStatus(n),n?.conversion&&(this.lastKnownConversion=n.conversion),n}setAccountMode(e){this.accountMode=e,this.initializerPromise=null,this.initializedIframeWindow=null}async selectAccountMode(e,t={}){await this.walletMessageManager.pingIframe(),await this.postRequestAndWait({method:l.set_signing_mode,params:[r(e,t)],interactionRequired:!1})}setLoginMethod(e){this.loginMethod=e,e===null&&(this._accounts=[],this.notifyChange({accounts:[]}))}getLoginMethod(){return this.loginMethod}async login(e){await this.ensureInitialized();let t=await this.restoreSession(e);if(t)return t;let n=(await this.postRequestAndWait({method:l.login,params:[],interactionRequired:!0,signal:e?.signal,timeoutMs:e?.timeoutMs})).data;return n!==`waap`&&n!==`human`&&n!==`injected`&&n!==`walletconnect`?(this.setLoginMethod(null),null):(this.loginMethod=n,n)}async logout(){this.lastKnownConversion=`pending`,await this.ensureInitialized(),await this.postRequestAndWait({method:l.logout,params:[],interactionRequired:!1}),this.loginMethod=null,this._accounts=[],this.notifyChange({accounts:[]})}async refreshAccounts(){try{await this.ensureInitialized();let e=await this.postRequestAndWait({method:`solana_connect`,params:[{silent:!0}],interactionRequired:!1});if(e.error)return this._accounts=[],{accounts:[]};let t=this.normalizeAccounts(e.data?.accounts||[]);return this._accounts=t,{accounts:this._accounts}}catch{return this._accounts=[],{accounts:[]}}}normalizeAccounts(e){return e.map(e=>({address:e.address,publicKey:e.publicKey instanceof Uint8Array?e.publicKey:new Uint8Array(e.publicKey??[]),chains:e.chains??this._chains,features:e.features??[]}))}async connect(e){if(e?.signal?.aborted)throw new u(`cancelled`,`WaaP connect cancelled.`,{operation:{chain:`solana`,method:`solana_connect`}});if(!this.ownsSession&&!this.loginMethod)throw new u(`not_authenticated`,`Not authenticated: call session.login() before connect().`,{operation:{chain:`solana`,method:`solana_connect`}});if(await this.ensureInitialized(),this.ownsSession&&e?.silent){try{await this.getCanonicalAccountStatus(e)}catch(e){throw this.setLoginMethod(null),e}if(!this.loginMethod)return{accounts:[]}}else if(this.ownsSession&&!await this.login(e))throw new u(`user_rejected`,`User rejected WaaP login during connect().`,{operation:{chain:`solana`,method:`solana_connect`}});let t=await this.postRequestAndWait({method:`solana_connect`,params:[e||{}],interactionRequired:!e?.silent,signal:e?.signal,timeoutMs:e?.timeoutMs});if(t.error)throw Error(t.error.message||`Failed to connect`);let n=this.normalizeAccounts(t.data?.accounts||[]);return this._accounts=n,this.notifyChange({accounts:this._accounts}),e?.silent||this.internalEventEmitter.emit(`connect`),this.internalEventEmitter.emit(`accountsChanged`,this._accounts.map(e=>e.address)),{accounts:this._accounts}}async restoreSession(e){try{let t=await this.getCanonicalAccountStatus(e);if(t.authenticated&&(t.loginMethod===`waap`||t.loginMethod===`human`||t.loginMethod===`injected`||t.loginMethod===`walletconnect`))return this.loginMethod=t.loginMethod,t.loginMethod}catch(e){if(e instanceof u&&(e.code===`cancelled`||e.code===`timeout`))throw e}return null}syncLoginMethodFromCanonicalStatus(e){let t=e.authenticated&&(e.loginMethod===`waap`||e.loginMethod===`human`||e.loginMethod===`injected`||e.loginMethod===`walletconnect`)?e.loginMethod:null;t!==this.loginMethod&&this.setLoginMethod(t)}async disconnect(){await this.ensureInitialized(),await this.postRequestAndWait({method:`solana_disconnect`,params:[],interactionRequired:!1}),this._accounts=[],this.notifyChange({accounts:[]})}async signMessage(e){await this.ensureInitialized();let t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw Error(`Account ${t} is not connected`);let n=await this.postRequestAndWait({method:`solana_signMessage`,params:[{message:Array.from(e.message),account:t}],interactionRequired:!0,signal:e.signal,timeoutMs:e.timeoutMs});if(n.error)throw Error(n.error.message||`Failed to sign message`);return{signedMessage:new Uint8Array(n.data.signedMessage),signature:new Uint8Array(n.data.signature)}}async signTransaction(e){await this.ensureInitialized();let t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw Error(`Account ${t} is not connected`);let n=this.resolveTransactionBytes(e.transaction),r=await this.postRequestAndWait({method:`solana_signTransaction`,params:[{transaction:Array.from(n),account:t,chain:this.asSupportedChain(e.chain)??this.defaultChain,withPT:e.withPT}],interactionRequired:!0,signal:e.signal,timeoutMs:e.timeoutMs});if(r.error)throw Error(r.error.message||`Failed to sign transaction`);return{signedTransaction:new Uint8Array(r.data.signedTransaction),signature:new Uint8Array(r.data.signature)}}async signAndSendTransaction(e){await this.ensureInitialized();let t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw Error(`Account ${t} is not connected`);let n=this.resolveTransactionBytes(e.transaction),r=await this.postRequestAndWait({method:`solana_signAndSendTransaction`,params:[{transaction:Array.from(n),account:t,chain:this.asSupportedChain(e.chain)??this.defaultChain,options:e.options,withPT:e.withPT}],interactionRequired:!0,signal:e.signal,timeoutMs:e.timeoutMs});if(r.error)throw Error(r.error.message||`Failed to sign and send transaction`);return{signature:r.data.signature}}async signStandardMessages(...e){let t=[];for(let n of e){let e=await this.signMessage({account:n.account,message:n.message});t.push({...e,signatureType:`ed25519`})}return t}async signStandardTransactions(...e){let t=[];for(let n of e){let e=await this.signTransaction({account:n.account,transaction:n.transaction,chain:this.asSupportedChain(n.chain)});t.push({signedTransaction:e.signedTransaction})}return t}async signAndSendStandardTransactions(...e){let t=[];for(let n of e){let e=await this.signAndSendTransaction({account:n.account,transaction:n.transaction,chain:this.asSupportedChain(n.chain),options:this.broadcastOptions(n.options)});t.push({signature:p(e.signature)})}return t}asSupportedChain(e){if(e!==void 0){if(this._chains.includes(e))return e;throw new u(`unsupported_input`,`Unsupported Solana Wallet Standard chain: ${e}`,{operation:{chain:`solana`,method:`wallet_standard`}})}}broadcastOptions(e){if(e?.commitment!==void 0)throw new u(`unsupported_input`,`WaaP returns a submitted signature; confirm the transaction with the dapp RPC instead of setting commitment.`,{operation:{chain:`solana`,method:`wallet_standard`}});return e?{preflightCommitment:e.preflightCommitment,minContextSlot:e.minContextSlot,skipPreflight:e.skipPreflight,maxRetries:e.maxRetries}:void 0}async requestPermissionToken(e){await this.ensureInitialized();let t={...e,walletMode:this.accountMode},n=await this.postRequestAndWait({method:l.waap_requestPermissionToken,params:[t],interactionRequired:!0});if(n.error)throw Error(n.error.message||`Failed to request permission token`);return n.data}async getPermissionTokenStatus(e){return await this.ensureInitialized(),(await this.postRequestAndWait({method:l.waap_getPermissionTokenStatus,params:[e],interactionRequired:!1})).data}async clearPermissionToken(e){return await this.ensureInitialized(),(await this.postRequestAndWait({method:l.waap_clearPermissionToken,params:[e],interactionRequired:!1})).data}resolveTransactionBytes(e){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return new Uint8Array(e);if(e&&typeof e.serialize==`function`){let t=e.serialize();return t instanceof Uint8Array?t:new Uint8Array(t)}throw Error(`Unsupported transaction format. Pass serialized bytes or a @solana/web3.js Transaction.`)}on(e,t){return e===`change`?(this.changeListeners.add(t),()=>{this.changeListeners.delete(t)}):(this.internalEventEmitter.on(e,t),()=>{this.internalEventEmitter.removeListener(e,t)})}removeListener(e,t){if(e===`change`){this.changeListeners.delete(t);return}this.internalEventEmitter.removeListener(e,t)}async postRequestAndWait(n){let r;try{n.interactionRequired&&i({layout:n.method===l.login?`auth`:`signing`}),r=await this.walletMessageManager.postSilkRequest({method:n.method,params:n.params,interactionRequired:n.interactionRequired});let e=await o({eventEmitter:this.internalEventEmitter,id:r,method:n.method,interactionRequired:n.interactionRequired,signal:n.signal,timeoutMs:n.timeoutMs,onCancel:()=>{this.walletMessageManager.cancelSilkRequest(r,n.method),n.interactionRequired&&t()}});if(e.error)throw Error(e.error.message);return e}catch(i){throw n.interactionRequired&&r===void 0&&t(),e(i,{chain:`solana`,method:String(n.method),requestId:r})}}notifyChange(e){Array.from(this.changeListeners).forEach(t=>{t(e)})}};function p(e){let t=[];for(let n of e){let e=`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`.indexOf(n);if(e<0)throw Error(`Invalid base58 transaction signature`);for(let n=0;n<t.length;n+=1)e+=t[n]*58,t[n]=e&255,e>>=8;for(;e>0;)t.push(e&255),e>>=8}let n=0;for(;n<e.length&&e[n]===`1`;)n+=1;return new Uint8Array([...Array(n).fill(0),...t.reverse()])}export{f as t};
@@ -1 +1 @@
1
- const e=require("./UIMessageManager-CPw6PggC.js");let t=require("events");var n=class{constructor(n,r={},i,a=r,o=!0){this.ownsSession=o,this.lastKnownConversion=`pending`,this.name=`WaaP`,this.version=`1.0.0`,this.icon=`data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCI+PHJlY3Qgd2lkdGg9IjY0IiBoZWlnaHQ9IjY0IiByeD0iMTYiIGZpbGw9IiMxMTE4MmMiLz48cGF0aCBkPSJNMTYgNDhoMzJMMzIgMTZ6IiBmaWxsPSIjN2NkNGZmIi8+PC9zdmc+`,this._accounts=[],this.accountMode=`tap`,this.loginMethod=null,this._chains=[`solana:mainnet`,`solana:devnet`,`solana:testnet`],this.internalEventEmitter=new t.EventEmitter,this.changeListeners=new Set,this.initializerPromise=null,this.initializedIframeWindow=null,this.defaultChain=this.asSupportedChain(r.defaultChain)??`solana:mainnet`,this.walletMessageManager=new e.d(n,e.v(r)),this.ensureIframe=i,this.iframeMounted=!i,this.initializerOptions=a,this.uiMessageManager=new e.t,this.walletMessageManager.addListener({handleResponse:e=>{this.internalEventEmitter.emit(e.id,e)},handleRequest:t=>{t.method===e.w.show_modal?this.uiMessageManager.emit(`show_modal`):t.method===e.w.hide_modal&&this.uiMessageManager.emit(`hide_modal`)},onAccountChanged:async()=>{try{let e=await this.refreshAccounts();this.notifyChange({accounts:e.accounts})}catch(e){console.error(`Failed to refresh Solana accounts:`,e),this._accounts=[],this.notifyChange({accounts:[]})}}})}destroy(){this.walletMessageManager.dispose(),this.internalEventEmitter.removeAllListeners(),this.uiMessageManager.removeAllListeners(),this.changeListeners.clear(),this._accounts=[]}ensureIframeMounted(){if(this.iframeMounted||!this.ensureIframe)return;let e=this.ensureIframe();if(!e)throw Error(`Failed to create WaaP iframe`);this.iframeMounted=!0,this.walletMessageManager.setIframeWindow(e)}async preload(){if(!this.ensureIframe)return;this.ensureIframeMounted();let t=this.walletMessageManager.getIframeWindow();if(!t)throw Error(`WaaP iframe is not mounted`);if(this.initializedIframeWindow===t&&this.initializerPromise)return this.initializerPromise;this.initializedIframeWindow=t,this.initializerPromise=e.m(t,()=>this.selectAccountMode(this.accountMode,this.initializerOptions));try{await this.initializerPromise}catch(e){throw this.initializerPromise=null,this.initializedIframeWindow=null,e}}async ensureInitialized(){await this.preload()}get chains(){return this._chains}get accounts(){return this._accounts}get features(){return{"standard:connect":{version:`1.0.0`,connect:this.connect.bind(this)},"standard:disconnect":{version:`1.0.0`,disconnect:this.disconnect.bind(this)},"standard:events":{version:`1.0.0`,on:this.on.bind(this)},"solana:signMessage":{version:`1.1.0`,signMessage:this.signStandardMessages.bind(this)},"solana:signTransaction":{version:`1.0.0`,supportedTransactionVersions:[`legacy`,0],signTransaction:this.signStandardTransactions.bind(this)},"solana:signAndSendTransaction":{version:`1.0.0`,supportedTransactionVersions:[`legacy`,0],signAndSendTransaction:this.signAndSendStandardTransactions.bind(this)}}}get ui(){return this.uiMessageManager}getAccountStatus(){return{authenticated:this.loginMethod!==null,loginMethod:this.loginMethod,activeMode:this.loginMethod?this.accountMode:null,mode:this.accountMode,conversion:this.loginMethod?this.lastKnownConversion:`not_required`,tap:null,squid:null,accounts:this._accounts[0]?{solana:this._accounts[0].address}:{}}}get session(){return{login:()=>this.login(),logout:()=>this.logout(),getLoginMethod:()=>this.getLoginMethod(),getAccountStatus:()=>this.getCanonicalAccountStatus()}}async getCanonicalAccountStatus(t){await this.ensureInitialized();let n=await this.postRequestAndWait({method:e.w.waap_getAccountStatus,params:[],interactionRequired:!1,signal:t?.signal,timeoutMs:t?.timeoutMs});if(n.error)throw Error(n.error.message||`Failed to read WaaP status`);let r=n.data;return this.syncLoginMethodFromCanonicalStatus(r),r?.conversion&&(this.lastKnownConversion=r.conversion),r}setAccountMode(e){this.accountMode=e,this.initializerPromise=null,this.initializedIframeWindow=null}async selectAccountMode(t,n={}){await this.walletMessageManager.pingIframe(),await this.postRequestAndWait({method:e.w.set_signing_mode,params:[e.f(t,n)],interactionRequired:!1})}setLoginMethod(e){this.loginMethod=e,e===null&&(this._accounts=[],this.notifyChange({accounts:[]}))}getLoginMethod(){return this.loginMethod}async login(t){await this.ensureInitialized();let n=await this.restoreSession(t);if(n)return n;let r=(await this.postRequestAndWait({method:e.w.login,params:[],interactionRequired:!0,signal:t?.signal,timeoutMs:t?.timeoutMs})).data;return r!==`waap`&&r!==`human`&&r!==`injected`&&r!==`walletconnect`?(this.setLoginMethod(null),null):(this.loginMethod=r,r)}async logout(){this.lastKnownConversion=`pending`,await this.ensureInitialized(),await this.postRequestAndWait({method:e.w.logout,params:[],interactionRequired:!1}),this.loginMethod=null,this._accounts=[],this.notifyChange({accounts:[]})}async refreshAccounts(){try{await this.ensureInitialized();let e=await this.postRequestAndWait({method:`solana_connect`,params:[{silent:!0}],interactionRequired:!1});if(e.error)return this._accounts=[],{accounts:[]};let t=this.normalizeAccounts(e.data?.accounts||[]);return this._accounts=t,{accounts:this._accounts}}catch{return this._accounts=[],{accounts:[]}}}normalizeAccounts(e){return e.map(e=>({address:e.address,publicKey:e.publicKey instanceof Uint8Array?e.publicKey:new Uint8Array(e.publicKey??[]),chains:e.chains??this._chains,features:e.features??[]}))}async connect(t){if(t?.signal?.aborted)throw new e.x(`cancelled`,`WaaP connect cancelled.`,{operation:{chain:`solana`,method:`solana_connect`}});if(!this.ownsSession&&!this.loginMethod)throw new e.x(`not_authenticated`,`Not authenticated: call session.login() before connect().`,{operation:{chain:`solana`,method:`solana_connect`}});if(await this.ensureInitialized(),this.ownsSession&&t?.silent){try{await this.getCanonicalAccountStatus(t)}catch(e){throw this.setLoginMethod(null),e}if(!this.loginMethod)return{accounts:[]}}else if(this.ownsSession&&!await this.login(t))throw new e.x(`user_rejected`,`User rejected WaaP login during connect().`,{operation:{chain:`solana`,method:`solana_connect`}});let n=await this.postRequestAndWait({method:`solana_connect`,params:[t||{}],interactionRequired:!t?.silent,signal:t?.signal,timeoutMs:t?.timeoutMs});if(n.error)throw Error(n.error.message||`Failed to connect`);let r=this.normalizeAccounts(n.data?.accounts||[]);return this._accounts=r,this.notifyChange({accounts:this._accounts}),t?.silent||this.internalEventEmitter.emit(`connect`),this.internalEventEmitter.emit(`accountsChanged`,this._accounts.map(e=>e.address)),{accounts:this._accounts}}async restoreSession(t){try{let e=await this.getCanonicalAccountStatus(t);if(e.authenticated&&(e.loginMethod===`waap`||e.loginMethod===`human`||e.loginMethod===`injected`||e.loginMethod===`walletconnect`))return this.loginMethod=e.loginMethod,e.loginMethod}catch(t){if(t instanceof e.x&&(t.code===`cancelled`||t.code===`timeout`))throw t}return null}syncLoginMethodFromCanonicalStatus(e){let t=e.authenticated&&(e.loginMethod===`waap`||e.loginMethod===`human`||e.loginMethod===`injected`||e.loginMethod===`walletconnect`)?e.loginMethod:null;t!==this.loginMethod&&this.setLoginMethod(t)}async disconnect(){await this.ensureInitialized(),await this.postRequestAndWait({method:`solana_disconnect`,params:[],interactionRequired:!1}),this._accounts=[],this.notifyChange({accounts:[]})}async signMessage(e){await this.ensureInitialized();let t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw Error(`Account ${t} is not connected`);let n=await this.postRequestAndWait({method:`solana_signMessage`,params:[{message:Array.from(e.message),account:t}],interactionRequired:!0,signal:e.signal,timeoutMs:e.timeoutMs});if(n.error)throw Error(n.error.message||`Failed to sign message`);return{signedMessage:new Uint8Array(n.data.signedMessage),signature:new Uint8Array(n.data.signature)}}async signTransaction(e){await this.ensureInitialized();let t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw Error(`Account ${t} is not connected`);let n=this.resolveTransactionBytes(e.transaction),r=await this.postRequestAndWait({method:`solana_signTransaction`,params:[{transaction:Array.from(n),account:t,chain:this.asSupportedChain(e.chain)??this.defaultChain,withPT:e.withPT}],interactionRequired:!0,signal:e.signal,timeoutMs:e.timeoutMs});if(r.error)throw Error(r.error.message||`Failed to sign transaction`);return{signedTransaction:new Uint8Array(r.data.signedTransaction),signature:new Uint8Array(r.data.signature)}}async signAndSendTransaction(e){await this.ensureInitialized();let t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw Error(`Account ${t} is not connected`);let n=this.resolveTransactionBytes(e.transaction),r=await this.postRequestAndWait({method:`solana_signAndSendTransaction`,params:[{transaction:Array.from(n),account:t,chain:this.asSupportedChain(e.chain)??this.defaultChain,options:e.options,withPT:e.withPT}],interactionRequired:!0,signal:e.signal,timeoutMs:e.timeoutMs});if(r.error)throw Error(r.error.message||`Failed to sign and send transaction`);return{signature:r.data.signature}}async signStandardMessages(...e){let t=[];for(let n of e){let e=await this.signMessage({account:n.account,message:n.message});t.push({...e,signatureType:`ed25519`})}return t}async signStandardTransactions(...e){let t=[];for(let n of e){let e=await this.signTransaction({account:n.account,transaction:n.transaction,chain:this.asSupportedChain(n.chain)});t.push({signedTransaction:e.signedTransaction})}return t}async signAndSendStandardTransactions(...e){let t=[];for(let n of e){let e=await this.signAndSendTransaction({account:n.account,transaction:n.transaction,chain:this.asSupportedChain(n.chain),options:this.broadcastOptions(n.options)});t.push({signature:r(e.signature)})}return t}asSupportedChain(t){if(t!==void 0){if(this._chains.includes(t))return t;throw new e.x(`unsupported_input`,`Unsupported Solana Wallet Standard chain: ${t}`,{operation:{chain:`solana`,method:`wallet_standard`}})}}broadcastOptions(t){if(t?.commitment!==void 0)throw new e.x(`unsupported_input`,`WaaP returns a submitted signature; confirm the transaction with the dapp RPC instead of setting commitment.`,{operation:{chain:`solana`,method:`wallet_standard`}});return t?{preflightCommitment:t.preflightCommitment,minContextSlot:t.minContextSlot,skipPreflight:t.skipPreflight,maxRetries:t.maxRetries}:void 0}async requestPermissionToken(t){await this.ensureInitialized();let n={...t,walletMode:this.accountMode},r=await this.postRequestAndWait({method:e.w.waap_requestPermissionToken,params:[n],interactionRequired:!0});if(r.error)throw Error(r.error.message||`Failed to request permission token`);return r.data}async getPermissionTokenStatus(t){return await this.ensureInitialized(),(await this.postRequestAndWait({method:e.w.waap_getPermissionTokenStatus,params:[t],interactionRequired:!1})).data}async clearPermissionToken(t){return await this.ensureInitialized(),(await this.postRequestAndWait({method:e.w.waap_clearPermissionToken,params:[t],interactionRequired:!1})).data}resolveTransactionBytes(e){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return new Uint8Array(e);if(e&&typeof e.serialize==`function`){let t=e.serialize();return t instanceof Uint8Array?t:new Uint8Array(t)}throw Error(`Unsupported transaction format. Pass serialized bytes or a @solana/web3.js Transaction.`)}on(e,t){return e===`change`?(this.changeListeners.add(t),()=>{this.changeListeners.delete(t)}):(this.internalEventEmitter.on(e,t),()=>{this.internalEventEmitter.removeListener(e,t)})}removeListener(e,t){if(e===`change`){this.changeListeners.delete(t);return}this.internalEventEmitter.removeListener(e,t)}async postRequestAndWait(t){let n;try{t.interactionRequired&&e.l({layout:t.method===e.w.login?`auth`:`signing`}),n=await this.walletMessageManager.postSilkRequest({method:t.method,params:t.params,interactionRequired:t.interactionRequired});let r=await e.o({eventEmitter:this.internalEventEmitter,id:n,method:t.method,interactionRequired:t.interactionRequired,signal:t.signal,timeoutMs:t.timeoutMs,onCancel:()=>{this.walletMessageManager.cancelSilkRequest(n,t.method),t.interactionRequired&&e.c()}});if(r.error)throw Error(r.error.message);return r}catch(r){throw t.interactionRequired&&n===void 0&&e.c(),e.S(r,{chain:`solana`,method:String(t.method),requestId:n})}}notifyChange(e){Array.from(this.changeListeners).forEach(t=>{t(e)})}};function r(e){let t=[];for(let n of e){let e=`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`.indexOf(n);if(e<0)throw Error(`Invalid base58 transaction signature`);for(let n=0;n<t.length;n+=1)e+=t[n]*58,t[n]=e&255,e>>=8;for(;e>0;)t.push(e&255),e>>=8}let n=0;for(;n<e.length&&e[n]===`1`;)n+=1;return new Uint8Array([...Array(n).fill(0),...t.reverse()])}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return n}});
1
+ const e=require("./UIMessageManager-Bzrjl7s7.js");let t=require("events");var n=class{constructor(n,r={},i,a=r,o=!0){this.ownsSession=o,this.lastKnownConversion=`pending`,this.name=`WaaP`,this.version=`1.0.0`,this.icon=`data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCI+PHJlY3Qgd2lkdGg9IjY0IiBoZWlnaHQ9IjY0IiByeD0iMTYiIGZpbGw9IiMxMTE4MmMiLz48cGF0aCBkPSJNMTYgNDhoMzJMMzIgMTZ6IiBmaWxsPSIjN2NkNGZmIi8+PC9zdmc+`,this._accounts=[],this.accountMode=`tap`,this.loginMethod=null,this._chains=[`solana:mainnet`,`solana:devnet`,`solana:testnet`],this.internalEventEmitter=new t.EventEmitter,this.changeListeners=new Set,this.initializerPromise=null,this.initializedIframeWindow=null,this.defaultChain=this.asSupportedChain(r.defaultChain)??`solana:mainnet`,this.walletMessageManager=new e.d(n,e.v(r)),this.ensureIframe=i,this.iframeMounted=!i,this.initializerOptions=a,this.uiMessageManager=new e.t,this.walletMessageManager.addListener({handleResponse:e=>{this.internalEventEmitter.emit(e.id,e)},handleRequest:t=>{t.method===e.w.show_modal?this.uiMessageManager.emit(`show_modal`):t.method===e.w.hide_modal&&this.uiMessageManager.emit(`hide_modal`)},onAccountChanged:async()=>{try{let e=await this.refreshAccounts();this.notifyChange({accounts:e.accounts})}catch(e){console.error(`Failed to refresh Solana accounts:`,e),this._accounts=[],this.notifyChange({accounts:[]})}}})}destroy(){this.walletMessageManager.dispose(),this.internalEventEmitter.removeAllListeners(),this.uiMessageManager.removeAllListeners(),this.changeListeners.clear(),this._accounts=[]}ensureIframeMounted(){if(this.iframeMounted||!this.ensureIframe)return;let e=this.ensureIframe();if(!e)throw Error(`Failed to create WaaP iframe`);this.iframeMounted=!0,this.walletMessageManager.setIframeWindow(e)}async preload(){if(!this.ensureIframe)return;this.ensureIframeMounted();let t=this.walletMessageManager.getIframeWindow();if(!t)throw Error(`WaaP iframe is not mounted`);if(this.initializedIframeWindow===t&&this.initializerPromise)return this.initializerPromise;this.initializedIframeWindow=t,this.initializerPromise=e.m(t,()=>this.selectAccountMode(this.accountMode,this.initializerOptions));try{await this.initializerPromise}catch(e){throw this.initializerPromise=null,this.initializedIframeWindow=null,e}}async ensureInitialized(){await this.preload()}get chains(){return this._chains}get accounts(){return this._accounts}get features(){return{"standard:connect":{version:`1.0.0`,connect:this.connect.bind(this)},"standard:disconnect":{version:`1.0.0`,disconnect:this.disconnect.bind(this)},"standard:events":{version:`1.0.0`,on:this.on.bind(this)},"solana:signMessage":{version:`1.1.0`,signMessage:this.signStandardMessages.bind(this)},"solana:signTransaction":{version:`1.0.0`,supportedTransactionVersions:[`legacy`,0],signTransaction:this.signStandardTransactions.bind(this)},"solana:signAndSendTransaction":{version:`1.0.0`,supportedTransactionVersions:[`legacy`,0],signAndSendTransaction:this.signAndSendStandardTransactions.bind(this)}}}get ui(){return this.uiMessageManager}getAccountStatus(){return{authenticated:this.loginMethod!==null,loginMethod:this.loginMethod,activeMode:this.loginMethod?this.accountMode:null,mode:this.accountMode,conversion:this.loginMethod?this.lastKnownConversion:`not_required`,tap:null,squid:null,accounts:this._accounts[0]?{solana:this._accounts[0].address}:{}}}get session(){return{login:()=>this.login(),logout:()=>this.logout(),getLoginMethod:()=>this.getLoginMethod(),getAccountStatus:()=>this.getCanonicalAccountStatus()}}async getCanonicalAccountStatus(t){await this.ensureInitialized();let n=await this.postRequestAndWait({method:e.w.waap_getAccountStatus,params:[],interactionRequired:!1,signal:t?.signal,timeoutMs:t?.timeoutMs});if(n.error)throw Error(n.error.message||`Failed to read WaaP status`);let r=n.data;return this.syncLoginMethodFromCanonicalStatus(r),r?.conversion&&(this.lastKnownConversion=r.conversion),r}setAccountMode(e){this.accountMode=e,this.initializerPromise=null,this.initializedIframeWindow=null}async selectAccountMode(t,n={}){await this.walletMessageManager.pingIframe(),await this.postRequestAndWait({method:e.w.set_signing_mode,params:[e.f(t,n)],interactionRequired:!1})}setLoginMethod(e){this.loginMethod=e,e===null&&(this._accounts=[],this.notifyChange({accounts:[]}))}getLoginMethod(){return this.loginMethod}async login(t){await this.ensureInitialized();let n=await this.restoreSession(t);if(n)return n;let r=(await this.postRequestAndWait({method:e.w.login,params:[],interactionRequired:!0,signal:t?.signal,timeoutMs:t?.timeoutMs})).data;return r!==`waap`&&r!==`human`&&r!==`injected`&&r!==`walletconnect`?(this.setLoginMethod(null),null):(this.loginMethod=r,r)}async logout(){this.lastKnownConversion=`pending`,await this.ensureInitialized(),await this.postRequestAndWait({method:e.w.logout,params:[],interactionRequired:!1}),this.loginMethod=null,this._accounts=[],this.notifyChange({accounts:[]})}async refreshAccounts(){try{await this.ensureInitialized();let e=await this.postRequestAndWait({method:`solana_connect`,params:[{silent:!0}],interactionRequired:!1});if(e.error)return this._accounts=[],{accounts:[]};let t=this.normalizeAccounts(e.data?.accounts||[]);return this._accounts=t,{accounts:this._accounts}}catch{return this._accounts=[],{accounts:[]}}}normalizeAccounts(e){return e.map(e=>({address:e.address,publicKey:e.publicKey instanceof Uint8Array?e.publicKey:new Uint8Array(e.publicKey??[]),chains:e.chains??this._chains,features:e.features??[]}))}async connect(t){if(t?.signal?.aborted)throw new e.x(`cancelled`,`WaaP connect cancelled.`,{operation:{chain:`solana`,method:`solana_connect`}});if(!this.ownsSession&&!this.loginMethod)throw new e.x(`not_authenticated`,`Not authenticated: call session.login() before connect().`,{operation:{chain:`solana`,method:`solana_connect`}});if(await this.ensureInitialized(),this.ownsSession&&t?.silent){try{await this.getCanonicalAccountStatus(t)}catch(e){throw this.setLoginMethod(null),e}if(!this.loginMethod)return{accounts:[]}}else if(this.ownsSession&&!await this.login(t))throw new e.x(`user_rejected`,`User rejected WaaP login during connect().`,{operation:{chain:`solana`,method:`solana_connect`}});let n=await this.postRequestAndWait({method:`solana_connect`,params:[t||{}],interactionRequired:!t?.silent,signal:t?.signal,timeoutMs:t?.timeoutMs});if(n.error)throw Error(n.error.message||`Failed to connect`);let r=this.normalizeAccounts(n.data?.accounts||[]);return this._accounts=r,this.notifyChange({accounts:this._accounts}),t?.silent||this.internalEventEmitter.emit(`connect`),this.internalEventEmitter.emit(`accountsChanged`,this._accounts.map(e=>e.address)),{accounts:this._accounts}}async restoreSession(t){try{let e=await this.getCanonicalAccountStatus(t);if(e.authenticated&&(e.loginMethod===`waap`||e.loginMethod===`human`||e.loginMethod===`injected`||e.loginMethod===`walletconnect`))return this.loginMethod=e.loginMethod,e.loginMethod}catch(t){if(t instanceof e.x&&(t.code===`cancelled`||t.code===`timeout`))throw t}return null}syncLoginMethodFromCanonicalStatus(e){let t=e.authenticated&&(e.loginMethod===`waap`||e.loginMethod===`human`||e.loginMethod===`injected`||e.loginMethod===`walletconnect`)?e.loginMethod:null;t!==this.loginMethod&&this.setLoginMethod(t)}async disconnect(){await this.ensureInitialized(),await this.postRequestAndWait({method:`solana_disconnect`,params:[],interactionRequired:!1}),this._accounts=[],this.notifyChange({accounts:[]})}async signMessage(e){await this.ensureInitialized();let t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw Error(`Account ${t} is not connected`);let n=await this.postRequestAndWait({method:`solana_signMessage`,params:[{message:Array.from(e.message),account:t}],interactionRequired:!0,signal:e.signal,timeoutMs:e.timeoutMs});if(n.error)throw Error(n.error.message||`Failed to sign message`);return{signedMessage:new Uint8Array(n.data.signedMessage),signature:new Uint8Array(n.data.signature)}}async signTransaction(e){await this.ensureInitialized();let t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw Error(`Account ${t} is not connected`);let n=this.resolveTransactionBytes(e.transaction),r=await this.postRequestAndWait({method:`solana_signTransaction`,params:[{transaction:Array.from(n),account:t,chain:this.asSupportedChain(e.chain)??this.defaultChain,withPT:e.withPT}],interactionRequired:!0,signal:e.signal,timeoutMs:e.timeoutMs});if(r.error)throw Error(r.error.message||`Failed to sign transaction`);return{signedTransaction:new Uint8Array(r.data.signedTransaction),signature:new Uint8Array(r.data.signature)}}async signAndSendTransaction(e){await this.ensureInitialized();let t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw Error(`Account ${t} is not connected`);let n=this.resolveTransactionBytes(e.transaction),r=await this.postRequestAndWait({method:`solana_signAndSendTransaction`,params:[{transaction:Array.from(n),account:t,chain:this.asSupportedChain(e.chain)??this.defaultChain,options:e.options,withPT:e.withPT}],interactionRequired:!0,signal:e.signal,timeoutMs:e.timeoutMs});if(r.error)throw Error(r.error.message||`Failed to sign and send transaction`);return{signature:r.data.signature}}async signStandardMessages(...e){let t=[];for(let n of e){let e=await this.signMessage({account:n.account,message:n.message});t.push({...e,signatureType:`ed25519`})}return t}async signStandardTransactions(...e){let t=[];for(let n of e){let e=await this.signTransaction({account:n.account,transaction:n.transaction,chain:this.asSupportedChain(n.chain)});t.push({signedTransaction:e.signedTransaction})}return t}async signAndSendStandardTransactions(...e){let t=[];for(let n of e){let e=await this.signAndSendTransaction({account:n.account,transaction:n.transaction,chain:this.asSupportedChain(n.chain),options:this.broadcastOptions(n.options)});t.push({signature:r(e.signature)})}return t}asSupportedChain(t){if(t!==void 0){if(this._chains.includes(t))return t;throw new e.x(`unsupported_input`,`Unsupported Solana Wallet Standard chain: ${t}`,{operation:{chain:`solana`,method:`wallet_standard`}})}}broadcastOptions(t){if(t?.commitment!==void 0)throw new e.x(`unsupported_input`,`WaaP returns a submitted signature; confirm the transaction with the dapp RPC instead of setting commitment.`,{operation:{chain:`solana`,method:`wallet_standard`}});return t?{preflightCommitment:t.preflightCommitment,minContextSlot:t.minContextSlot,skipPreflight:t.skipPreflight,maxRetries:t.maxRetries}:void 0}async requestPermissionToken(t){await this.ensureInitialized();let n={...t,walletMode:this.accountMode},r=await this.postRequestAndWait({method:e.w.waap_requestPermissionToken,params:[n],interactionRequired:!0});if(r.error)throw Error(r.error.message||`Failed to request permission token`);return r.data}async getPermissionTokenStatus(t){return await this.ensureInitialized(),(await this.postRequestAndWait({method:e.w.waap_getPermissionTokenStatus,params:[t],interactionRequired:!1})).data}async clearPermissionToken(t){return await this.ensureInitialized(),(await this.postRequestAndWait({method:e.w.waap_clearPermissionToken,params:[t],interactionRequired:!1})).data}resolveTransactionBytes(e){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return new Uint8Array(e);if(e&&typeof e.serialize==`function`){let t=e.serialize();return t instanceof Uint8Array?t:new Uint8Array(t)}throw Error(`Unsupported transaction format. Pass serialized bytes or a @solana/web3.js Transaction.`)}on(e,t){return e===`change`?(this.changeListeners.add(t),()=>{this.changeListeners.delete(t)}):(this.internalEventEmitter.on(e,t),()=>{this.internalEventEmitter.removeListener(e,t)})}removeListener(e,t){if(e===`change`){this.changeListeners.delete(t);return}this.internalEventEmitter.removeListener(e,t)}async postRequestAndWait(t){let n;try{t.interactionRequired&&e.l({layout:t.method===e.w.login?`auth`:`signing`}),n=await this.walletMessageManager.postSilkRequest({method:t.method,params:t.params,interactionRequired:t.interactionRequired});let r=await e.o({eventEmitter:this.internalEventEmitter,id:n,method:t.method,interactionRequired:t.interactionRequired,signal:t.signal,timeoutMs:t.timeoutMs,onCancel:()=>{this.walletMessageManager.cancelSilkRequest(n,t.method),t.interactionRequired&&e.c()}});if(r.error)throw Error(r.error.message);return r}catch(r){throw t.interactionRequired&&n===void 0&&e.c(),e.S(r,{chain:`solana`,method:String(t.method),requestId:n})}}notifyChange(e){Array.from(this.changeListeners).forEach(t=>{t(e)})}};function r(e){let t=[];for(let n of e){let e=`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`.indexOf(n);if(e<0)throw Error(`Invalid base58 transaction signature`);for(let n=0;n<t.length;n+=1)e+=t[n]*58,t[n]=e&255,e>>=8;for(;e>0;)t.push(e&255),e>>=8}let n=0;for(;n<e.length&&e[n]===`1`;)n+=1;return new Uint8Array([...Array(n).fill(0),...t.reverse()])}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return n}});
@@ -0,0 +1 @@
1
+ import{EventEmitter as e}from"events";var t;(function(e){e.request=`request`,e.response=`response`,e.notification=`notification`})(t||={});var n;(function(e){e.eth_requestAccounts=`eth_requestAccounts`,e.eth_accounts=`eth_accounts`,e.eth_sendTransaction=`eth_sendTransaction`,e.eth_signTransaction=`eth_signTransaction`,e.eth_getBalance=`eth_getBalance`,e.personal_sign=`personal_sign`,e.eth_signTypedData_v4=`eth_signTypedData_v4`,e.eth_chainId=`eth_chainId`,e.net_version=`net_version`,e.wallet_switchEthereumChain=`wallet_switchEthereumChain`,e.wallet_addEthereumChain=`wallet_addEthereumChain`,e.eth_estimateGas=`eth_estimateGas`,e.eth_blockNumber=`eth_blockNumber`,e.eth_getCode=`eth_getCode`,e.eth_call=`eth_call`,e.eth_getTransactionReceipt=`eth_getTransactionReceipt`,e.eth_getTransactionByHash=`eth_getTransactionByHash`,e.eth_accountsChanged=`eth_accountsChanged`,e.sui_connect=`sui_connect`,e.sui_disconnect=`sui_disconnect`,e.sui_getAccounts=`sui_getAccounts`,e.sui_signPersonalMessage=`sui_signPersonalMessage`,e.sui_signTransaction=`sui_signTransaction`,e.sui_signAndExecuteTransaction=`sui_signAndExecuteTransaction`,e.sui_switchChain=`sui_switchChain`,e.show_modal=`show_modal`,e.hide_modal=`hide_modal`,e.login=`login`,e.auto_conn=`auto_conn`,e.logout=`logout`,e.set_points_referral_code=`set_points_referral_code`,e.set_project=`set_project`,e.silk_requestEmail=`silk_requestEmail`,e.silk_requestSbt=`silk_requestSbt`,e.set_custom_config=`set_custom_config`,e.safe=`safe`,e.set_is_mobile=`set_is_mobile`,e.project_init=`project_init`,e.gastank_get_settings=`gastank_get_settings`,e.gastank_update_settings=`gastank_update_settings`,e.gastank_topup=`gastank_topup`,e.customization_get=`customization_get`,e.customization_update=`customization_update`,e.orcid=`orcid`,e.waap_requestPermissionToken=`waap_requestPermissionToken`,e.waap_getAccountStatus=`waap_getAccountStatus`,e.waap_getPermissionTokenStatus=`waap_getPermissionTokenStatus`,e.waap_clearPermissionToken=`waap_clearPermissionToken`,e.waap_getLinkedAddresses=`waap_getLinkedAddresses`,e.waap_linkAddress=`waap_linkAddress`,e.waap_unlinkAddress=`waap_unlinkAddress`,e.waap_getLinkAddressNonce=`waap_getLinkAddressNonce`,e.solana_connect=`solana_connect`,e.solana_disconnect=`solana_disconnect`,e.solana_signMessage=`solana_signMessage`,e.solana_signTransaction=`solana_signTransaction`,e.solana_signAllTransactions=`solana_signAllTransactions`,e.solana_signAndSendTransaction=`solana_signAndSendTransaction`,e.stellar_connect=`stellar_connect`,e.stellar_disconnect=`stellar_disconnect`,e.stellar_signMessage=`stellar_signMessage`,e.stellar_signTransaction=`stellar_signTransaction`,e.stellar_signAndSendTransaction=`stellar_signAndSendTransaction`,e.set_signing_mode=`set_signing_mode`,e.enter_lite_mode=`enter_lite_mode`})(n||={});var r;(function(e){e.eth_requestAccounts=`eth_requestAccounts`,e.eth_accounts=`eth_accounts`,e.eth_sendTransaction=`eth_sendTransaction`,e.eth_signTransaction=`eth_signTransaction`,e.eth_getBalance=`eth_getBalance`,e.personal_sign=`personal_sign`,e.eth_signTypedData_v4=`eth_signTypedData_v4`,e.eth_chainId=`eth_chainId`,e.net_version=`net_version`,e.wallet_switchEthereumChain=`wallet_switchEthereumChain`,e.wallet_addEthereumChain=`wallet_addEthereumChain`,e.eth_estimateGas=`eth_estimateGas`,e.eth_blockNumber=`eth_blockNumber`,e.eth_getCode=`eth_getCode`,e.eth_call=`eth_call`,e.eth_getTransactionReceipt=`eth_getTransactionReceipt`,e.eth_getTransactionByHash=`eth_getTransactionByHash`})(r||={});var i;(function(e){e.ready=`ready`,e.connect=`connect`,e.account_changed=`account_changed`,e.mobile_oauth_success=`mobile_oauth_success`,e.mobile_oauth_error=`mobile_oauth_error`,e.tx_pending=`waap_txPending`,e.tx_2fa_required=`waap_tx2faRequired`,e.tx_signed=`waap_txSigned`,e.tx_confirmed=`waap_txConfirmed`,e.tx_failed=`waap_txFailed`,e.squid_pending=`waap_squid_pending`,e.squid_ready=`waap_squid_ready`,e.squid_failed=`waap_squid_failed`,e.request_cancel=`waap_requestCancel`})(i||={});var a=class extends Error{constructor(e,t,n={}){super(t),this.name=`WaaPError`,this.code=e,this.operation=n.operation,this.cause=n.cause}};function o(e,t){if(e instanceof a)return e;let n=e&&typeof e==`object`?e:void 0,r=n&&typeof n.message==`string`&&n.message||e instanceof Error&&e.message||String(e||`WaaP request failed`),i=n?.code,o=r.toLowerCase();return new a(o.includes(`cancelled`)||o.includes(`canceled`)?`cancelled`:o.includes(`timed out`)?`timeout`:o.includes(`insufficient balance`)?`insufficient_balance`:o.includes(`policy`)||o.includes(`permission token`)?`policy_rejected`:i===4001||o.includes(`rejected`)?`user_rejected`:o.includes(`not connected`)?`not_connected`:o.includes(`not authenticated`)||o.includes(`log in first`)?`not_authenticated`:o.includes(`unsupported`)||o.includes(`must be base64`)?`unsupported_input`:n?`wallet_error`:`unknown`,r,{cause:e,operation:t})}const s=`waap-wallet`,c=`waap-component-container`,l=typeof window<`u`&&typeof document<`u`&&typeof HTMLElement<`u`;let u;l?(u=class extends HTMLElement{constructor(){super()}connectedCallback(){(!this.style.display||this.style.display===``)&&(this.style.display=`flex`,this.style.alignItems=`center`,this.style.justifyContent=`center`),(!this.style.width||this.style.width===``)&&(this.style.width=`100%`),(!this.style.height||this.style.height===``)&&(this.style.height=`100%`),this.id=c,this.setAttribute(`data-waap-mounted`,`true`)}disconnectedCallback(){this.removeAttribute(`data-waap-mounted`)}},typeof customElements<`u`&&!customElements.get(s)&&customElements.define(s,u)):u=class{};function d(){return l?!!document.getElementById(c)||!!document.querySelector(s):!1}function f(){return l?document.getElementById(c)||document.querySelector(s):null}const p=`https://staging.waap.xyz`,m={development:`http://localhost:3000`,staging:p,production:`https://waap.xyz`},ee=e=>e===`localhost`||e===`127.0.0.1`||e===`[::1]`;function h(e){let t;try{t=new URL(e)}catch{throw Error(`Invalid WaaP wallet origin: ${e}`)}if(t.origin!==e||t.pathname!==`/`||t.search||t.hash||t.username||t.password)throw Error(`WaaP walletOrigin must be an absolute origin without a path, query, or credentials`);if(t.protocol!==`https:`&&!(t.protocol===`http:`&&ee(t.hostname)))throw Error(`WaaP walletOrigin must use HTTPS unless it is a loopback host`);return t.origin}function g(e={}){return e.walletOrigin?h(e.walletOrigin):e.environment?h(m[e.environment]):e.useStaging?h(p):h(m.production)}const _=new WeakMap,v=new WeakMap,y=()=>typeof performance<`u`?performance.now():Date.now(),b=e=>({generation:e.generation,navigationStartedAt:e.navigationStartedAt,loadedAt:e.loadedAt}),x=e=>{let t=e.contentWindow;if(!t)return;let n=v.get(e);if(n&&_.get(t)===n)return;n?.cleanup(),n&&(v.delete(e),_.get(t)===n&&_.delete(t));let r=_.get(t);if(r?.iframe===e)return;r?.cleanup(),r&&v.delete(r.iframe);let i={iframe:e,generation:0,navigationStartedAt:y(),loadedAt:null,listeners:new Set,cleanup:()=>{}},a=()=>{i.generation+=1,i.loadedAt=y();let e=b(i);for(let t of Array.from(i.listeners))t(e)};i.cleanup=()=>{e.removeEventListener(`load`,a),i.listeners.clear()},e.addEventListener(`load`,a),_.set(t,i),v.set(e,i)},te=e=>{let t=v.get(e);if(t){t.cleanup(),v.delete(e);let n=e.contentWindow;n&&_.get(n)===t&&_.delete(n);return}let n=e.contentWindow;if(!n)return;let r=_.get(n);!r||r.iframe!==e||(r.cleanup(),_.delete(n))},S=e=>{let t=_.get(e);return t?b(t):null},ne=(e,t)=>{let n=_.get(e);return n?n.loadedAt===null?new Promise((e,r)=>{let i=window.setTimeout(()=>{n.listeners.delete(a),r(Error(`WaaP iframe navigation timed out after ${Math.round(t/1e3)}s.`))},t),a=t=>{window.clearTimeout(i),n.listeners.delete(a),e(t)};n.listeners.add(a)}):Promise.resolve(b(n)):Promise.resolve(null)},re=(e,t)=>{let n=_.get(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):()=>{}},C=`waap-wallet-loading-styles`,w=`waap-iframe-visual-ready`,T=typeof window<`u`&&typeof document<`u`,ie=()=>{if(!T||document.getElementById(C))return;let e=document.createElement(`style`);e.id=C,e.textContent=`@keyframes waap-loading-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } } @media (prefers-reduced-motion: reduce) { [data-waap-loading-part] { animation: none !important; } }`,document.head.appendChild(e)},ae=(e={})=>g(e),E=()=>T?document.getElementById(`waap-wallet-iframe-container`)||document.getElementById(`silk-wallet-iframe-container`):null,D=()=>T?document.getElementById(`waap-wallet-iframe-wrapper`)||document.getElementById(`silk-wallet-iframe-wrapper`):null,O=()=>T?document.getElementById(`waap-wallet-iframe`)||document.getElementById(`silk-wallet-iframe`):null,k=(e=O())=>{let t=Number(e?.dataset.waapVisualRevision??`0`);return Number.isSafeInteger(t)&&t>=0?t:0},oe=(e=O())=>{let t=e?.dataset.waapVisualReadySupported;return t===`true`||t!==`false`&&null},A=(e,t)=>{if(e){if(t===null){delete e.dataset.waapVisualReadySupported;return}e.dataset.waapVisualReadySupported=String(t)}},se=(e,t)=>{let n=e.__silkCleanup;e.__silkCleanup=()=>{n?.(),t()}},ce=e=>{let t=O();if(!t)throw Error(`WaaP iframe does not exist on page`);let n=t.dataset.waapAccountMode;if(n&&n!==e)throw Error(`WaaP iframe is already bound to ${n}; destroy it before initializing ${e}.`);return t.dataset.waapAccountMode=e,t},le=e=>{if(T)try{if(document.querySelector(`link[data-waap-preconnect="${e}"]`))return;let t=document.createElement(`link`);t.rel=`preconnect`,t.href=e,t.crossOrigin=`anonymous`,t.setAttribute(`data-waap-preconnect`,e),document.head.appendChild(t);let n=document.createElement(`link`);n.rel=`dns-prefetch`,n.href=e,n.setAttribute(`data-waap-preconnect`,e),document.head.appendChild(n)}catch{}},ue=(e,t)=>{e.dataset.waapTheme=t?`dark`:`light`},de=(e,t)=>{let n=e;le(n);let r=document.createElement(`iframe`);return r.id=`waap-wallet-iframe`,r.dataset.waapOrigin=n,ue(r,t),x(r),r.src=`${n}/iframe`,r.allow=`publickey-credentials-get; publickey-credentials-create`,r.style.width=`100%`,r.style.height=`100%`,r.style.border=`none`,r.style.borderRadius=`24px`,r.style.backgroundColor=`transparent`,r.style.background=`transparent`,r.style.padding=`0`,r.style.margin=`0`,r},fe=()=>{let e=document.createElement(`div`);return e.id=`waap-wallet-iframe-wrapper`,e.style.position=`relative`,e.style.display=`flex`,e.style.alignItems=`center`,e.style.justifyContent=`center`,e.style.padding=`0`,e.style.margin=`0`,e.style.height=`600px`,e.style.width=`380px`,e},pe=()=>{let e=document.createElement(`div`);return e.id=`waap-wallet-iframe-container`,e.style.position=`fixed`,e.style.top=`0`,e.style.left=`0`,e.style.right=`0`,e.style.bottom=`0`,e.style.width=`100%`,e.style.height=`100%`,e.style.alignItems=`center`,e.style.justifyContent=`center`,e.style.backgroundColor=`rgba(0, 0, 0, 0.5)`,e.style.zIndex=`9999999999`,e.style.display=`flex`,e.style.visibility=`hidden`,e.style.opacity=`0`,e.style.pointerEvents=`none`,e.style.transition=typeof window<`u`&&window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches?`none`:`opacity 140ms ease`,e},me=(e,t)=>{let n=e,r,i,a,o,s=()=>{if(r=void 0,!o)return;let e=D();e&&e.dataset.waapSizeLocked!==`true`&&(i=o.width,a=o.height,e.style.height=`${o.height}px`,e.style.width=`${o.width}px`,o=void 0)},c=()=>{r===void 0&&(r=window.requestAnimationFrame(s))},l=()=>{!o&&i!==void 0&&a!==void 0&&(o={width:i,height:a}),c()},u=e=>{if(e.origin!==n||e.source!==t.contentWindow||!e.data||typeof e.data!=`object`||e.data.type!==`silk-iframe-size`)return;let r=e.data.height,s=e.data.width,l=2e3;if(typeof r!=`number`||typeof s!=`number`||r<50||r>l||s<50||s>l||!Number.isFinite(r)||!Number.isFinite(s))return;let u=Math.floor(s),d=Math.floor(r);u===i&&d===a||(o={width:u,height:d},c())};window.addEventListener(`message`,u),t.addEventListener(w,l);let d=()=>{r!==void 0&&window.cancelAnimationFrame(r),window.removeEventListener(`message`,u),t.removeEventListener(w,l)};return se(t,d),d},j=(e,t)=>{let n=()=>{delete t.dataset.waapVisualRevision,delete t.dataset.waapVisualReadyAt,A(t,null)},r=n=>{if(n.origin!==e||n.source!==t.contentWindow||!n.data||typeof n.data!=`object`||n.data.type!==`silk-iframe-visual-ready`)return;let r=n.data.revision;!Number.isSafeInteger(r)||r<=0||r<=k(t)||(t.dataset.waapVisualRevision=String(r),t.dataset.waapVisualReadyAt=String(typeof performance<`u`?performance.now():Date.now()),t.dispatchEvent(new CustomEvent(w,{detail:{revision:r}})))};t.addEventListener(`load`,n),window.addEventListener(`message`,r);let i=()=>{t.removeEventListener(`load`,n),window.removeEventListener(`message`,r)};return se(t,i),i},M=()=>{setTimeout(()=>{if(typeof document>`u`)return;let e=D();e&&(e.style.height=`600px`,e.style.width=`380px`)},100)},N=e=>{let t=O();if(!t)return!1;let n=t.dataset.waapOrigin??(()=>{try{return new URL(t.src).origin}catch{return}})();if(n&&n!==e)throw Error(`WaaP wallet iframe already exists for ${n}; destroy it before switching to ${e}`);return!0},he=(e,t)=>{let n=f();if(!n)throw Error(`WaaP component not found in DOM`);if(N(e))return;let r=fe(),i=de(e,t);me(e,i),j(e,i),M(),r.appendChild(i),n.appendChild(r),x(i)},ge=(e,t)=>{if(N(e))return;let n=pe(),r=fe();n.appendChild(r);let i=de(e,t);me(e,i),j(e,i),M(),r.appendChild(i),document.body.appendChild(n),x(i)},_e=(e={})=>{if(!T)return;ie();let t=ae(e),n=e.config?.styles?.darkMode===!0,r=O();r&&ue(r,n),d()?he(t,n):ge(t,n)},ve=()=>{if(!T)return;Ne();let e=O(),t=e?.__silkCleanup;typeof t==`function`&&t(),e&&te(e);let n=D(),r=E();r?r.remove():n?.remove(),document.querySelectorAll(`link[data-waap-preconnect]`).forEach(e=>{e.remove()})};let P=0;async function ye(e){let t=Date.now().toString(),n=new TextEncoder().encode(JSON.stringify(e)+t),r=globalThis.crypto;if(r?.subtle?.digest){let e=await r.subtle.digest(`SHA-256`,new Uint8Array(n));return F(new Uint8Array(e))}return P+=1,F(new TextEncoder().encode(`${t}:${P}:${Math.random()}:${JSON.stringify(e)}`)).padEnd(64,`0`).slice(0,64)}function F(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}const I=new WeakMap,be=(e,t)=>{let n=I.get(e);if(n)return n;let r=t();return I.set(e,r),r.catch(()=>{I.get(e)===r&&I.delete(e)}),r},xe=e=>{I.delete(e)};let L=null;const Se=(e,t)=>{L={platform:e,version:t}},Ce=(e,t={})=>({schemaVersion:1,accountMode:e,sessionProtection:`dpop`,sdkPlatform:L?.platform??`web`,sdkVersion:L?.version??`2.4.2`,relyingPartySource:`browser-origin`,...t.project?.appId?{appId:t.project.appId}:{},...t.chains?.length?{chains:t.chains}:{},parentOrigin:typeof window>`u`?void 0:window.location?.origin,...t.referralCode?{referralCode:t.referralCode}:{},...t.project?{project:t.project}:{},...t.config?{config:t.config}:{}}),R=new Set;let z=!1,B;const V=new WeakMap,we=(e=256)=>{let t=new Set;return{accept(n){if(t.has(n))return!1;if(t.add(n),t.size>e){let e=t.values().next().value;e&&t.delete(e)}return!0},clear(){t.clear()},size(){return t.size}}},H=e=>{let t=V.get(e);if(t)return t;let n={ready:!1,promise:null,reject:null,cleanup:null,navigationGeneration:null,readyPingStartedAt:null,readyAt:null,readyAttempts:0,visualReadySupported:null,lastError:null};return V.set(e,n),n},U=(e,t)=>{let n=V.get(e);if(!n)return;n.ready=!1,n.cleanup?.(),n.cleanup=null;let r=n.reject;n.reject=null,n.promise=null,n.navigationGeneration=null,n.visualReadySupported=null;let i=O();i?.contentWindow===e&&A(i,null),r?.(t)},W=()=>typeof performance<`u`?performance.now():Date.now();let G=null;const K=new Set,Te=()=>{for(let e of K)if(!e.isDisposed())return e.getHandshakeDiagnostics();return G},Ee=(e,n,r)=>{let{handleResponse:a,handleRequest:o,onReceiveConnectNotif:s,onAccountChanged:c,onAsyncTxNotification:l,onSquidLifecycleNotification:u,onAuthComplete:d}=r;if(e.origin===n.walletOrigin&&e.source===n.getIframeWindow()&&e.data?.target===`silk`)if(e.data?.messageType===t.request)o?.(e.data);else if(e.data?.messageType===t.response){if(a){let t=e.data;n.shouldHandleTerminalResponse(t.id)&&a(t)}}else e.data?.messageType===t.notification&&(e.data?.data===i.connect?s?.():e.data?.data?.type===i.account_changed&&c?c(e.data.data.account):(e.data?.data?.type?.startsWith(`waap_sign_`)||e.data?.data?.type?.startsWith(`waap_tx_`))&&l?l({type:e.data.data.type,payload:e.data.data.payload}):(e.data?.data===i.mobile_oauth_success||e.data?.data===i.mobile_oauth_error)&&d?d(e.data.data===i.mobile_oauth_success?`success`:`error`):e.data?.data?.type?.startsWith(`waap_squid_`)&&u&&u({type:e.data.data.type,payload:e.data.data.payload}))},De=()=>{z||typeof window>`u`||(z=!0,B=e=>{for(let{manager:t,config:n}of Array.from(R))Ee(e,t,n)},window.addEventListener(`message`,B))},Oe=()=>{R.size>0||!z||!B||typeof window>`u`||(window.removeEventListener(`message`,B),B=void 0,z=!1)};var ke=class{constructor(e,t){this.iframeWindow=null,this.unregisterListeners=new Set,this.terminalResponseDeduper=we(),this.unsubscribeIframeNavigation=null,this.disposed=!1,this.iframeWindow=e,this.walletOrigin=typeof t==`string`?t:g(t===!0?{useStaging:!0}:{}),e&&this.observeIframeNavigation(e),K.add(this)}observeIframeNavigation(e){this.unsubscribeIframeNavigation?.(),this.unsubscribeIframeNavigation=re(e,()=>{let t=H(e);(t.ready||t.readyPingStartedAt!==null)&&(xe(e),U(e,Error(`WaaP iframe reloaded; readiness must be re-established`)),this.terminalResponseDeduper.clear())})}setIframeWindow(e){this.iframeWindow&&this.iframeWindow!==e&&(U(this.iframeWindow,Error(`Wallet iframe window changed`)),this.terminalResponseDeduper.clear()),this.iframeWindow=e,this.observeIframeNavigation(e)}getIframeWindow(){return this.iframeWindow}isDisposed(){return this.disposed}shouldHandleTerminalResponse(e){return this.terminalResponseDeduper.accept(e)}getHandshakeDiagnostics(){let e=this.iframeWindow,t=e?S(e):null,n=e?H(e):null,r={walletOrigin:this.walletOrigin,iframeNavigationStartedAt:t?.navigationStartedAt??null,iframeLoadedAt:t?.loadedAt??null,readyPingStartedAt:n?.readyPingStartedAt??null,readyAt:n?.readyAt??null,readyAttempts:n?.readyAttempts??0,visualReadySupported:n?.visualReadySupported??null,navigationGeneration:n?.navigationGeneration??null,lastError:n?.lastError??null};return G=r,r}postSilkNotification(e){if(!this.iframeWindow)throw Error(`WaaP iframe is not mounted`);this.iframeWindow.postMessage({target:`silk`,messageType:t.notification,data:e},this.walletOrigin)}postReadyNotification(){this.postSilkNotification(i.ready)}postConnectNotification(){this.postSilkNotification(i.connect)}cancelSilkRequest(e,t){this.postSilkNotification({type:i.request_cancel,requestId:e,method:t})}pingIframe(){if(this.disposed)return Promise.reject(Error(`Wallet message manager is disposed`));let e=this.iframeWindow;if(!e||typeof window>`u`)return Promise.reject(Error(`WaaP iframe is not mounted`));let n=H(e),r=S(e);return n.ready&&(!r||n.navigationGeneration===r.generation)?Promise.resolve():(n.ready&&U(e,Error(`WaaP iframe navigation changed; readiness must be re-established`)),n.promise?n.promise:(n.lastError=null,n.readyPingStartedAt=null,n.readyAt=null,n.readyAttempts=0,n.visualReadySupported=null,n.promise=new Promise((r,a)=>{n.reject=a,ne(e,3e4).then(r=>{if(this.disposed||this.iframeWindow!==e)throw Error(`Wallet message manager is disposed`);return new Promise((a,o)=>{let s=o=>{if(o.origin===this.walletOrigin&&o.source===e&&o.data?.target===`silk`&&o.data.messageType===t.notification&&o.data.data===i.ready){n.ready=!0,n.navigationGeneration=S(e)?.generation??r?.generation??null,n.readyAt=W(),n.visualReadySupported=o.data?.capabilities?.visualReady===1;let t=O();t?.contentWindow===e&&A(t,n.visualReadySupported),p(),a()}},c=()=>{try{n.readyAttempts+=1,this.postReadyNotification()}catch(e){p(),o(e)}};n.readyPingStartedAt=W();let l=250,u,d=()=>{u=window.setTimeout(()=>{c(),l=Math.min(l*2,1e3),d()},l)},f=window.setTimeout(()=>{p(),o(Error(`WaaP wallet ready handshake timed out after 10s.`))},1e4),p=()=>{u!==void 0&&window.clearTimeout(u),window.clearTimeout(f),window.removeEventListener(`message`,s),n.cleanup===p&&(n.cleanup=null,n.reject=null)};n.cleanup=p,n.reject=o,window.addEventListener(`message`,s),c(),d()})}).then(r,a)}),n.promise=n.promise.finally(()=>{n.ready||(n.lastError=n.lastError??`Wallet readiness failed`,n.promise=null)}),n.promise.catch(e=>{n.lastError=e instanceof Error?e.message:String(e)}),n.promise))}async postSilkRequest(e){if(!this.iframeWindow)throw Error(`WaaP iframe is not mounted`);let{silkOptions:n,...r}=e,i={...r,target:`silk`,messageType:t.request,...n&&{silkOptions:n}},a=await ye(i);return this.iframeWindow.postMessage({...i,id:a},this.walletOrigin),a}addListener(e){if(this.disposed)throw Error(`Wallet message manager is disposed`);De();let t={manager:this,config:e};R.add(t);let n=()=>{this.unregisterListeners.delete(n)&&(R.delete(t),Oe())};return this.unregisterListeners.add(n),n}dispose(){this.disposed||(this.disposed=!0,this.iframeWindow&&U(this.iframeWindow,Error(`Wallet message manager was disposed`)),Array.from(this.unregisterListeners).forEach(e=>e()),this.terminalResponseDeduper.clear(),this.unsubscribeIframeNavigation?.(),this.unsubscribeIframeNavigation=null,G=this.getHandshakeDiagnostics(),this.iframeWindow=null,K.delete(this))}};const q=`waap-wallet-iframe-loading`,J=new Set,Y=()=>typeof performance<`u`?performance.now():Date.now(),X=e=>{J.forEach(t=>{try{t(e)}catch{}})},Ae=e=>(J.add(e),()=>J.delete(e));var je=class{constructor(e){this.pendingRevision=null,this.phase=`idle`,this.requestedAt=null,this.visibleAt=null,this.usedVisualFallback=!1,this.onVisualReady=e=>{let t=e.detail?.revision;this.pendingRevision!==null&&typeof t==`number`&&t>=this.pendingRevision&&this.revealIframe(!1)},this.iframe=e,e.addEventListener(w,this.onVisualReady)}show({layout:e=`signing`}={}){if(this.phase===`pending`||this.phase===`visible`)return;let t=D();if(!t)return;this.clearFallbackTimer();let n=this.moveToCurrentMode(t);n===`modal`&&e===`signing`?(t.dataset.waapSizeLocked=`true`,t.style.width=`380px`,t.style.height=`600px`):n===`modal`&&delete t.dataset.waapSizeLocked,this.pendingRevision=k(this.iframe)+1,this.phase=`pending`,this.requestedAt=Y(),this.visibleAt=null,this.usedVisualFallback=!1,X({phase:`modal_requested`,at:this.requestedAt,visualRevision:this.pendingRevision}),this.hideIframeUntilPaint(t),n===`modal`?this.showModalSurface():t.style.display=`flex`;let r=oe(this.iframe);if(r===!1){this.revealIframe(!0);return}this.fallbackTimer=window.setTimeout(()=>{this.revealIframe(!0)},r===!0?3e3:750)}hide(){let e=this.pendingRevision!==null;this.pendingRevision=null,this.clearFallbackTimer(),this.phase=`hidden`;let t=Y();e&&X({phase:`modal_cancelled`,at:t,visualRevision:k(this.iframe)}),X({phase:`modal_hidden`,at:t,visualRevision:k(this.iframe)});let n=D();n&&delete n.dataset.waapSizeLocked;let r=E();if(r&&(r.style.opacity=`0`,r.style.visibility=`hidden`,r.style.pointerEvents=`none`),d()){n&&(n.style.display=`none`);return}for(let e of[n,this.iframe])e&&(e.style.visibility=`hidden`,e.style.pointerEvents=`none`)}dispose(){this.clearFallbackTimer(),this.iframe.removeEventListener(w,this.onVisualReady)}isFor(e){return this.iframe===e}getDiagnostics(){return{modalPhase:this.phase,modalRequestedAt:this.requestedAt,modalVisibleAt:this.visibleAt,usedVisualFallback:this.usedVisualFallback}}moveToCurrentMode(e){if(d()){let t=f();return t&&e.parentElement!==t&&t.appendChild(e),`component`}let t=E();return t||(t=pe(),document.body.appendChild(t)),e.parentElement!==t&&t.appendChild(e),`modal`}showModalSurface(){let e=E();e&&(e.style.display=`flex`,e.style.visibility=`visible`,e.style.opacity=`1`,e.style.pointerEvents=`auto`)}hideIframeUntilPaint(e){e.style.display=`flex`,e.style.visibility=`visible`,e.style.opacity=`1`,e.style.pointerEvents=`auto`,this.iframe.style.visibility=`hidden`,this.iframe.style.opacity=`0`,this.iframe.style.pointerEvents=`none`,this.ensureLoadingIndicator(e).style.display=`flex`}revealIframe(e){if(this.pendingRevision===null)return;let t=k(this.iframe);this.pendingRevision=null,this.clearFallbackTimer(),this.phase=`visible`,this.visibleAt=Y(),this.usedVisualFallback=e,X({phase:`modal_visible`,at:this.visibleAt,visualRevision:t,fallback:e});let n=D();if(!n)return;delete n.dataset.waapSizeLocked;let r=n.querySelector(`#${q}`);r&&(r.style.display=`none`),this.iframe.style.visibility=`visible`,this.iframe.style.opacity=`1`,this.iframe.style.pointerEvents=`auto`,n.style.visibility=`visible`,n.style.opacity=`1`,n.style.pointerEvents=`auto`}ensureLoadingIndicator(e){let t=e.querySelector(`#${q}`);if(t)return this.applyLoadingTheme(t),t;t=document.createElement(`div`),t.id=q,t.setAttribute(`role`,`status`),t.setAttribute(`aria-live`,`polite`),t.setAttribute(`aria-label`,`Loading WaaP wallet`),t.style.position=`absolute`,t.style.inset=`0`,t.style.zIndex=`1`,t.style.display=`none`,t.style.flexDirection=`column`,t.style.borderRadius=`24px`,t.style.fontFamily=`system-ui, sans-serif`,t.style.fontSize=`14px`,t.style.pointerEvents=`none`;let n=document.createElement(`div`);n.style.boxSizing=`border-box`,n.style.display=`flex`,n.style.flexDirection=`column`,n.style.width=`100%`,n.style.height=`100%`,n.style.padding=`24px`;let r=document.createElement(`img`),i=this.iframe.dataset.waapOrigin;i&&(r.src=`${i}/assets/svg/waaplogo.svg`),r.alt=`WaaP`,r.width=66,r.height=25,r.style.alignSelf=`center`,r.style.width=`66px`,r.style.height=`25px`,r.style.marginBottom=`20px`,r.dataset.waapLoadingLogo=`true`;let a=(e,t,n,r)=>{let i=document.createElement(`div`);return i.setAttribute(`aria-hidden`,`true`),i.dataset.waapLoadingPart=e,i.style.width=t,i.style.height=n,i.style.flexShrink=`0`,i.style.borderRadius=r,i.style.backgroundSize=`200% 100%`,i.style.animation=`waap-loading-shimmer 2.4s ease-in-out infinite`,i},o=a(`request-title`,`156px`,`16px`,`999px`);o.style.marginTop=`34px`;let s=a(`request-body`,`100%`,`220px`,`12px`);s.style.flex=`1`,s.style.marginTop=`18px`,s.style.opacity=`.58`;let c=document.createElement(`div`);return c.dataset.waapLoadingPart=`actions`,c.setAttribute(`aria-hidden`,`true`),c.style.display=`flex`,c.style.gap=`10px`,c.append(a(`cancel-action`,`calc(50% - 5px)`,`48px`,`12px`),a(`confirm-action`,`calc(50% - 5px)`,`48px`,`12px`)),n.append(r,o,s,c),t.appendChild(n),e.appendChild(t),this.applyLoadingTheme(t),t}applyLoadingTheme(e){let t=this.iframe.dataset.waapTheme===`dark`;e.dataset.waapTheme=t?`dark`:`light`,e.style.background=t?`#121212`:`#ffffff`,e.style.color=t?`#e6e6e6`:`#000000`;let n=e.querySelector(`[data-waap-loading-logo]`);n&&(n.style.filter=t?`invert(1)`:`none`);let r=t?`linear-gradient(90deg, rgba(255,255,255,.07), rgba(255,255,255,.14), rgba(255,255,255,.07))`:`linear-gradient(90deg, rgba(0,0,0,.05), rgba(0,0,0,.1), rgba(0,0,0,.05))`;e.querySelectorAll(`[data-waap-loading-part]`).forEach(e=>{e.style.background=r})}clearFallbackTimer(){this.fallbackTimer!==void 0&&(window.clearTimeout(this.fallbackTimer),this.fallbackTimer=void 0)}};let Z;const Q=()=>{let e=O();return e?(Z&&!Z.isFor(e)&&(Z.dispose(),Z=void 0),Z??=new je(e),Z):null},Me=e=>{Q()?.show(e)},$=()=>{Q()?.hide()},Ne=()=>{Z?.dispose(),Z=void 0},Pe=()=>{let e=O(),t=e?.contentWindow?S(e.contentWindow):null,n=Z?.getDiagnostics(),r=Number(e?.dataset.waapVisualReadyAt??``);return{walletOrigin:e?.dataset.waapOrigin??null,iframeNavigationStartedAt:t?.navigationStartedAt??null,iframeLoadedAt:t?.loadedAt??null,visualRevision:k(e),visualReadyAt:Number.isFinite(r)?r:null,modalPhase:n?.modalPhase??`idle`,modalRequestedAt:n?.modalRequestedAt??null,modalVisibleAt:n?.modalVisibleAt??null,usedVisualFallback:n?.usedVisualFallback??!1,handshake:Te()}},Fe=new Set([r.eth_sendTransaction,r.eth_signTransaction,r.personal_sign,r.eth_signTypedData_v4]),Ie=e=>Fe.has(e);function Le(e){return new Promise((t,n)=>{let r,i=!1,a=()=>{r!==void 0&&clearTimeout(r),e.eventEmitter.removeListener(e.id,o),e.signal?.removeEventListener(`abort`,c)},o=e=>{i||(i=!0,a(),t(e))},s=t=>{i||(i=!0,a(),e.onCancel?.(),n(Error(t)))},c=()=>s(`WaaP request cancelled: ${e.method}`);if(e.signal?.aborted){c();return}e.interactionRequired||(r=setTimeout(()=>{s(`WaaP request timed out: ${e.method}`)},e.timeoutMs??3e4)),e.eventEmitter.once(e.id,o),e.signal?.addEventListener(`abort`,c,{once:!0})})}function Re(e){if(typeof e!=`object`||!e)return e;try{e.waapCode=o(e).code}catch{}return e}async function ze(e,t,r,i,a){let o=e.method,s=e.params,{timeoutMs:c,signal:l,...u}=a??{};t&&Me({layout:o===n.login?`auth`:`signing`});let d;try{d=await r.postSilkRequest({method:o,params:s,interactionRequired:t,silkOptions:a?u:void 0});let e=await Le({eventEmitter:i,id:d,method:o,interactionRequired:t,timeoutMs:c,signal:l,onCancel:()=>{r.cancelSilkRequest(d,o),t&&$()}});if(t&&$(),e.error)throw Re(e.error);return e.data}catch(e){throw t&&d===void 0&&$(),e}}const Be=(e,t={})=>{if(typeof window>`u`)return()=>void 0;let n=!1,r,i,a=window,o=()=>{n||e.preload().catch(e=>t.onError?.(e))};return typeof a.requestIdleCallback==`function`?r=a.requestIdleCallback(o,{timeout:t.timeoutMs??2e3}):i=window.setTimeout(o,0),()=>{n=!0,r!==void 0&&a.cancelIdleCallback?.(r),i!==void 0&&window.clearTimeout(i)}};var Ve=function(e){return e.show_modal=`show_modal`,e.hide_modal=`hide_modal`,e}(Ve||{}),He=class extends e{constructor(){super()}};export{r as C,o as S,ve as _,Ie as a,u as b,$ as c,ke as d,Ce as f,_e as g,ce as h,ze as i,Me as l,be as m,Ve as n,Le as o,Se as p,Be as r,Pe as s,He as t,Ae as u,g as v,n as w,a as x,h as y};
@@ -0,0 +1 @@
1
+ let e=require("events");var t;(function(e){e.request=`request`,e.response=`response`,e.notification=`notification`})(t||={});var n;(function(e){e.eth_requestAccounts=`eth_requestAccounts`,e.eth_accounts=`eth_accounts`,e.eth_sendTransaction=`eth_sendTransaction`,e.eth_signTransaction=`eth_signTransaction`,e.eth_getBalance=`eth_getBalance`,e.personal_sign=`personal_sign`,e.eth_signTypedData_v4=`eth_signTypedData_v4`,e.eth_chainId=`eth_chainId`,e.net_version=`net_version`,e.wallet_switchEthereumChain=`wallet_switchEthereumChain`,e.wallet_addEthereumChain=`wallet_addEthereumChain`,e.eth_estimateGas=`eth_estimateGas`,e.eth_blockNumber=`eth_blockNumber`,e.eth_getCode=`eth_getCode`,e.eth_call=`eth_call`,e.eth_getTransactionReceipt=`eth_getTransactionReceipt`,e.eth_getTransactionByHash=`eth_getTransactionByHash`,e.eth_accountsChanged=`eth_accountsChanged`,e.sui_connect=`sui_connect`,e.sui_disconnect=`sui_disconnect`,e.sui_getAccounts=`sui_getAccounts`,e.sui_signPersonalMessage=`sui_signPersonalMessage`,e.sui_signTransaction=`sui_signTransaction`,e.sui_signAndExecuteTransaction=`sui_signAndExecuteTransaction`,e.sui_switchChain=`sui_switchChain`,e.show_modal=`show_modal`,e.hide_modal=`hide_modal`,e.login=`login`,e.auto_conn=`auto_conn`,e.logout=`logout`,e.set_points_referral_code=`set_points_referral_code`,e.set_project=`set_project`,e.silk_requestEmail=`silk_requestEmail`,e.silk_requestSbt=`silk_requestSbt`,e.set_custom_config=`set_custom_config`,e.safe=`safe`,e.set_is_mobile=`set_is_mobile`,e.project_init=`project_init`,e.gastank_get_settings=`gastank_get_settings`,e.gastank_update_settings=`gastank_update_settings`,e.gastank_topup=`gastank_topup`,e.customization_get=`customization_get`,e.customization_update=`customization_update`,e.orcid=`orcid`,e.waap_requestPermissionToken=`waap_requestPermissionToken`,e.waap_getAccountStatus=`waap_getAccountStatus`,e.waap_getPermissionTokenStatus=`waap_getPermissionTokenStatus`,e.waap_clearPermissionToken=`waap_clearPermissionToken`,e.waap_getLinkedAddresses=`waap_getLinkedAddresses`,e.waap_linkAddress=`waap_linkAddress`,e.waap_unlinkAddress=`waap_unlinkAddress`,e.waap_getLinkAddressNonce=`waap_getLinkAddressNonce`,e.solana_connect=`solana_connect`,e.solana_disconnect=`solana_disconnect`,e.solana_signMessage=`solana_signMessage`,e.solana_signTransaction=`solana_signTransaction`,e.solana_signAllTransactions=`solana_signAllTransactions`,e.solana_signAndSendTransaction=`solana_signAndSendTransaction`,e.stellar_connect=`stellar_connect`,e.stellar_disconnect=`stellar_disconnect`,e.stellar_signMessage=`stellar_signMessage`,e.stellar_signTransaction=`stellar_signTransaction`,e.stellar_signAndSendTransaction=`stellar_signAndSendTransaction`,e.set_signing_mode=`set_signing_mode`,e.enter_lite_mode=`enter_lite_mode`})(n||={});var r;(function(e){e.eth_requestAccounts=`eth_requestAccounts`,e.eth_accounts=`eth_accounts`,e.eth_sendTransaction=`eth_sendTransaction`,e.eth_signTransaction=`eth_signTransaction`,e.eth_getBalance=`eth_getBalance`,e.personal_sign=`personal_sign`,e.eth_signTypedData_v4=`eth_signTypedData_v4`,e.eth_chainId=`eth_chainId`,e.net_version=`net_version`,e.wallet_switchEthereumChain=`wallet_switchEthereumChain`,e.wallet_addEthereumChain=`wallet_addEthereumChain`,e.eth_estimateGas=`eth_estimateGas`,e.eth_blockNumber=`eth_blockNumber`,e.eth_getCode=`eth_getCode`,e.eth_call=`eth_call`,e.eth_getTransactionReceipt=`eth_getTransactionReceipt`,e.eth_getTransactionByHash=`eth_getTransactionByHash`})(r||={});var i;(function(e){e.ready=`ready`,e.connect=`connect`,e.account_changed=`account_changed`,e.mobile_oauth_success=`mobile_oauth_success`,e.mobile_oauth_error=`mobile_oauth_error`,e.tx_pending=`waap_txPending`,e.tx_2fa_required=`waap_tx2faRequired`,e.tx_signed=`waap_txSigned`,e.tx_confirmed=`waap_txConfirmed`,e.tx_failed=`waap_txFailed`,e.squid_pending=`waap_squid_pending`,e.squid_ready=`waap_squid_ready`,e.squid_failed=`waap_squid_failed`,e.request_cancel=`waap_requestCancel`})(i||={});var a=class extends Error{constructor(e,t,n={}){super(t),this.name=`WaaPError`,this.code=e,this.operation=n.operation,this.cause=n.cause}};function o(e,t){if(e instanceof a)return e;let n=e&&typeof e==`object`?e:void 0,r=n&&typeof n.message==`string`&&n.message||e instanceof Error&&e.message||String(e||`WaaP request failed`),i=n?.code,o=r.toLowerCase();return new a(o.includes(`cancelled`)||o.includes(`canceled`)?`cancelled`:o.includes(`timed out`)?`timeout`:o.includes(`insufficient balance`)?`insufficient_balance`:o.includes(`policy`)||o.includes(`permission token`)?`policy_rejected`:i===4001||o.includes(`rejected`)?`user_rejected`:o.includes(`not connected`)?`not_connected`:o.includes(`not authenticated`)||o.includes(`log in first`)?`not_authenticated`:o.includes(`unsupported`)||o.includes(`must be base64`)?`unsupported_input`:n?`wallet_error`:`unknown`,r,{cause:e,operation:t})}const s=`waap-wallet`,c=`waap-component-container`,l=typeof window<`u`&&typeof document<`u`&&typeof HTMLElement<`u`;let u;l?(u=class extends HTMLElement{constructor(){super()}connectedCallback(){(!this.style.display||this.style.display===``)&&(this.style.display=`flex`,this.style.alignItems=`center`,this.style.justifyContent=`center`),(!this.style.width||this.style.width===``)&&(this.style.width=`100%`),(!this.style.height||this.style.height===``)&&(this.style.height=`100%`),this.id=c,this.setAttribute(`data-waap-mounted`,`true`)}disconnectedCallback(){this.removeAttribute(`data-waap-mounted`)}},typeof customElements<`u`&&!customElements.get(s)&&customElements.define(s,u)):u=class{};function d(){return l?!!document.getElementById(c)||!!document.querySelector(s):!1}function f(){return l?document.getElementById(c)||document.querySelector(s):null}const p=`https://staging.waap.xyz`,m={development:`http://localhost:3000`,staging:p,production:`https://waap.xyz`},ee=e=>e===`localhost`||e===`127.0.0.1`||e===`[::1]`;function h(e){let t;try{t=new URL(e)}catch{throw Error(`Invalid WaaP wallet origin: ${e}`)}if(t.origin!==e||t.pathname!==`/`||t.search||t.hash||t.username||t.password)throw Error(`WaaP walletOrigin must be an absolute origin without a path, query, or credentials`);if(t.protocol!==`https:`&&!(t.protocol===`http:`&&ee(t.hostname)))throw Error(`WaaP walletOrigin must use HTTPS unless it is a loopback host`);return t.origin}function g(e={}){return e.walletOrigin?h(e.walletOrigin):e.environment?h(m[e.environment]):e.useStaging?h(p):h(m.production)}const _=new WeakMap,v=new WeakMap,y=()=>typeof performance<`u`?performance.now():Date.now(),b=e=>({generation:e.generation,navigationStartedAt:e.navigationStartedAt,loadedAt:e.loadedAt}),x=e=>{let t=e.contentWindow;if(!t)return;let n=v.get(e);if(n&&_.get(t)===n)return;n?.cleanup(),n&&(v.delete(e),_.get(t)===n&&_.delete(t));let r=_.get(t);if(r?.iframe===e)return;r?.cleanup(),r&&v.delete(r.iframe);let i={iframe:e,generation:0,navigationStartedAt:y(),loadedAt:null,listeners:new Set,cleanup:()=>{}},a=()=>{i.generation+=1,i.loadedAt=y();let e=b(i);for(let t of Array.from(i.listeners))t(e)};i.cleanup=()=>{e.removeEventListener(`load`,a),i.listeners.clear()},e.addEventListener(`load`,a),_.set(t,i),v.set(e,i)},te=e=>{let t=v.get(e);if(t){t.cleanup(),v.delete(e);let n=e.contentWindow;n&&_.get(n)===t&&_.delete(n);return}let n=e.contentWindow;if(!n)return;let r=_.get(n);!r||r.iframe!==e||(r.cleanup(),_.delete(n))},S=e=>{let t=_.get(e);return t?b(t):null},ne=(e,t)=>{let n=_.get(e);return n?n.loadedAt===null?new Promise((e,r)=>{let i=window.setTimeout(()=>{n.listeners.delete(a),r(Error(`WaaP iframe navigation timed out after ${Math.round(t/1e3)}s.`))},t),a=t=>{window.clearTimeout(i),n.listeners.delete(a),e(t)};n.listeners.add(a)}):Promise.resolve(b(n)):Promise.resolve(null)},re=(e,t)=>{let n=_.get(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):()=>{}},C=`waap-wallet-loading-styles`,w=`waap-iframe-visual-ready`,T=typeof window<`u`&&typeof document<`u`,ie=()=>{if(!T||document.getElementById(C))return;let e=document.createElement(`style`);e.id=C,e.textContent=`@keyframes waap-loading-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } } @media (prefers-reduced-motion: reduce) { [data-waap-loading-part] { animation: none !important; } }`,document.head.appendChild(e)},ae=(e={})=>g(e),E=()=>T?document.getElementById(`waap-wallet-iframe-container`)||document.getElementById(`silk-wallet-iframe-container`):null,D=()=>T?document.getElementById(`waap-wallet-iframe-wrapper`)||document.getElementById(`silk-wallet-iframe-wrapper`):null,O=()=>T?document.getElementById(`waap-wallet-iframe`)||document.getElementById(`silk-wallet-iframe`):null,k=(e=O())=>{let t=Number(e?.dataset.waapVisualRevision??`0`);return Number.isSafeInteger(t)&&t>=0?t:0},oe=(e=O())=>{let t=e?.dataset.waapVisualReadySupported;return t===`true`||t!==`false`&&null},A=(e,t)=>{if(e){if(t===null){delete e.dataset.waapVisualReadySupported;return}e.dataset.waapVisualReadySupported=String(t)}},se=(e,t)=>{let n=e.__silkCleanup;e.__silkCleanup=()=>{n?.(),t()}},ce=e=>{let t=O();if(!t)throw Error(`WaaP iframe does not exist on page`);let n=t.dataset.waapAccountMode;if(n&&n!==e)throw Error(`WaaP iframe is already bound to ${n}; destroy it before initializing ${e}.`);return t.dataset.waapAccountMode=e,t},le=e=>{if(T)try{if(document.querySelector(`link[data-waap-preconnect="${e}"]`))return;let t=document.createElement(`link`);t.rel=`preconnect`,t.href=e,t.crossOrigin=`anonymous`,t.setAttribute(`data-waap-preconnect`,e),document.head.appendChild(t);let n=document.createElement(`link`);n.rel=`dns-prefetch`,n.href=e,n.setAttribute(`data-waap-preconnect`,e),document.head.appendChild(n)}catch{}},ue=(e,t)=>{e.dataset.waapTheme=t?`dark`:`light`},de=(e,t)=>{let n=e;le(n);let r=document.createElement(`iframe`);return r.id=`waap-wallet-iframe`,r.dataset.waapOrigin=n,ue(r,t),x(r),r.src=`${n}/iframe`,r.allow=`publickey-credentials-get; publickey-credentials-create`,r.style.width=`100%`,r.style.height=`100%`,r.style.border=`none`,r.style.borderRadius=`24px`,r.style.backgroundColor=`transparent`,r.style.background=`transparent`,r.style.padding=`0`,r.style.margin=`0`,r},fe=()=>{let e=document.createElement(`div`);return e.id=`waap-wallet-iframe-wrapper`,e.style.position=`relative`,e.style.display=`flex`,e.style.alignItems=`center`,e.style.justifyContent=`center`,e.style.padding=`0`,e.style.margin=`0`,e.style.height=`600px`,e.style.width=`380px`,e},pe=()=>{let e=document.createElement(`div`);return e.id=`waap-wallet-iframe-container`,e.style.position=`fixed`,e.style.top=`0`,e.style.left=`0`,e.style.right=`0`,e.style.bottom=`0`,e.style.width=`100%`,e.style.height=`100%`,e.style.alignItems=`center`,e.style.justifyContent=`center`,e.style.backgroundColor=`rgba(0, 0, 0, 0.5)`,e.style.zIndex=`9999999999`,e.style.display=`flex`,e.style.visibility=`hidden`,e.style.opacity=`0`,e.style.pointerEvents=`none`,e.style.transition=typeof window<`u`&&window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches?`none`:`opacity 140ms ease`,e},me=(e,t)=>{let n=e,r,i,a,o,s=()=>{if(r=void 0,!o)return;let e=D();e&&e.dataset.waapSizeLocked!==`true`&&(i=o.width,a=o.height,e.style.height=`${o.height}px`,e.style.width=`${o.width}px`,o=void 0)},c=()=>{r===void 0&&(r=window.requestAnimationFrame(s))},l=()=>{!o&&i!==void 0&&a!==void 0&&(o={width:i,height:a}),c()},u=e=>{if(e.origin!==n||e.source!==t.contentWindow||!e.data||typeof e.data!=`object`||e.data.type!==`silk-iframe-size`)return;let r=e.data.height,s=e.data.width,l=2e3;if(typeof r!=`number`||typeof s!=`number`||r<50||r>l||s<50||s>l||!Number.isFinite(r)||!Number.isFinite(s))return;let u=Math.floor(s),d=Math.floor(r);u===i&&d===a||(o={width:u,height:d},c())};window.addEventListener(`message`,u),t.addEventListener(w,l);let d=()=>{r!==void 0&&window.cancelAnimationFrame(r),window.removeEventListener(`message`,u),t.removeEventListener(w,l)};return se(t,d),d},j=(e,t)=>{let n=()=>{delete t.dataset.waapVisualRevision,delete t.dataset.waapVisualReadyAt,A(t,null)},r=n=>{if(n.origin!==e||n.source!==t.contentWindow||!n.data||typeof n.data!=`object`||n.data.type!==`silk-iframe-visual-ready`)return;let r=n.data.revision;!Number.isSafeInteger(r)||r<=0||r<=k(t)||(t.dataset.waapVisualRevision=String(r),t.dataset.waapVisualReadyAt=String(typeof performance<`u`?performance.now():Date.now()),t.dispatchEvent(new CustomEvent(w,{detail:{revision:r}})))};t.addEventListener(`load`,n),window.addEventListener(`message`,r);let i=()=>{t.removeEventListener(`load`,n),window.removeEventListener(`message`,r)};return se(t,i),i},M=()=>{setTimeout(()=>{if(typeof document>`u`)return;let e=D();e&&(e.style.height=`600px`,e.style.width=`380px`)},100)},N=e=>{let t=O();if(!t)return!1;let n=t.dataset.waapOrigin??(()=>{try{return new URL(t.src).origin}catch{return}})();if(n&&n!==e)throw Error(`WaaP wallet iframe already exists for ${n}; destroy it before switching to ${e}`);return!0},he=(e,t)=>{let n=f();if(!n)throw Error(`WaaP component not found in DOM`);if(N(e))return;let r=fe(),i=de(e,t);me(e,i),j(e,i),M(),r.appendChild(i),n.appendChild(r),x(i)},ge=(e,t)=>{if(N(e))return;let n=pe(),r=fe();n.appendChild(r);let i=de(e,t);me(e,i),j(e,i),M(),r.appendChild(i),document.body.appendChild(n),x(i)},_e=(e={})=>{if(!T)return;ie();let t=ae(e),n=e.config?.styles?.darkMode===!0,r=O();r&&ue(r,n),d()?he(t,n):ge(t,n)},ve=()=>{if(!T)return;Ne();let e=O(),t=e?.__silkCleanup;typeof t==`function`&&t(),e&&te(e);let n=D(),r=E();r?r.remove():n?.remove(),document.querySelectorAll(`link[data-waap-preconnect]`).forEach(e=>{e.remove()})};let P=0;async function ye(e){let t=Date.now().toString(),n=new TextEncoder().encode(JSON.stringify(e)+t),r=globalThis.crypto;if(r?.subtle?.digest){let e=await r.subtle.digest(`SHA-256`,new Uint8Array(n));return F(new Uint8Array(e))}return P+=1,F(new TextEncoder().encode(`${t}:${P}:${Math.random()}:${JSON.stringify(e)}`)).padEnd(64,`0`).slice(0,64)}function F(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}const I=new WeakMap,be=(e,t)=>{let n=I.get(e);if(n)return n;let r=t();return I.set(e,r),r.catch(()=>{I.get(e)===r&&I.delete(e)}),r},xe=e=>{I.delete(e)};let L=null;const Se=(e,t)=>{L={platform:e,version:t}},Ce=(e,t={})=>({schemaVersion:1,accountMode:e,sessionProtection:`dpop`,sdkPlatform:L?.platform??`web`,sdkVersion:L?.version??`2.4.2`,relyingPartySource:`browser-origin`,...t.project?.appId?{appId:t.project.appId}:{},...t.chains?.length?{chains:t.chains}:{},parentOrigin:typeof window>`u`?void 0:window.location?.origin,...t.referralCode?{referralCode:t.referralCode}:{},...t.project?{project:t.project}:{},...t.config?{config:t.config}:{}}),R=new Set;let z=!1,B;const V=new WeakMap,we=(e=256)=>{let t=new Set;return{accept(n){if(t.has(n))return!1;if(t.add(n),t.size>e){let e=t.values().next().value;e&&t.delete(e)}return!0},clear(){t.clear()},size(){return t.size}}},H=e=>{let t=V.get(e);if(t)return t;let n={ready:!1,promise:null,reject:null,cleanup:null,navigationGeneration:null,readyPingStartedAt:null,readyAt:null,readyAttempts:0,visualReadySupported:null,lastError:null};return V.set(e,n),n},U=(e,t)=>{let n=V.get(e);if(!n)return;n.ready=!1,n.cleanup?.(),n.cleanup=null;let r=n.reject;n.reject=null,n.promise=null,n.navigationGeneration=null,n.visualReadySupported=null;let i=O();i?.contentWindow===e&&A(i,null),r?.(t)},W=()=>typeof performance<`u`?performance.now():Date.now();let G=null;const K=new Set,Te=()=>{for(let e of K)if(!e.isDisposed())return e.getHandshakeDiagnostics();return G},Ee=(e,n,r)=>{let{handleResponse:a,handleRequest:o,onReceiveConnectNotif:s,onAccountChanged:c,onAsyncTxNotification:l,onSquidLifecycleNotification:u,onAuthComplete:d}=r;if(e.origin===n.walletOrigin&&e.source===n.getIframeWindow()&&e.data?.target===`silk`)if(e.data?.messageType===t.request)o?.(e.data);else if(e.data?.messageType===t.response){if(a){let t=e.data;n.shouldHandleTerminalResponse(t.id)&&a(t)}}else e.data?.messageType===t.notification&&(e.data?.data===i.connect?s?.():e.data?.data?.type===i.account_changed&&c?c(e.data.data.account):(e.data?.data?.type?.startsWith(`waap_sign_`)||e.data?.data?.type?.startsWith(`waap_tx_`))&&l?l({type:e.data.data.type,payload:e.data.data.payload}):(e.data?.data===i.mobile_oauth_success||e.data?.data===i.mobile_oauth_error)&&d?d(e.data.data===i.mobile_oauth_success?`success`:`error`):e.data?.data?.type?.startsWith(`waap_squid_`)&&u&&u({type:e.data.data.type,payload:e.data.data.payload}))},De=()=>{z||typeof window>`u`||(z=!0,B=e=>{for(let{manager:t,config:n}of Array.from(R))Ee(e,t,n)},window.addEventListener(`message`,B))},Oe=()=>{R.size>0||!z||!B||typeof window>`u`||(window.removeEventListener(`message`,B),B=void 0,z=!1)};var ke=class{constructor(e,t){this.iframeWindow=null,this.unregisterListeners=new Set,this.terminalResponseDeduper=we(),this.unsubscribeIframeNavigation=null,this.disposed=!1,this.iframeWindow=e,this.walletOrigin=typeof t==`string`?t:g(t===!0?{useStaging:!0}:{}),e&&this.observeIframeNavigation(e),K.add(this)}observeIframeNavigation(e){this.unsubscribeIframeNavigation?.(),this.unsubscribeIframeNavigation=re(e,()=>{let t=H(e);(t.ready||t.readyPingStartedAt!==null)&&(xe(e),U(e,Error(`WaaP iframe reloaded; readiness must be re-established`)),this.terminalResponseDeduper.clear())})}setIframeWindow(e){this.iframeWindow&&this.iframeWindow!==e&&(U(this.iframeWindow,Error(`Wallet iframe window changed`)),this.terminalResponseDeduper.clear()),this.iframeWindow=e,this.observeIframeNavigation(e)}getIframeWindow(){return this.iframeWindow}isDisposed(){return this.disposed}shouldHandleTerminalResponse(e){return this.terminalResponseDeduper.accept(e)}getHandshakeDiagnostics(){let e=this.iframeWindow,t=e?S(e):null,n=e?H(e):null,r={walletOrigin:this.walletOrigin,iframeNavigationStartedAt:t?.navigationStartedAt??null,iframeLoadedAt:t?.loadedAt??null,readyPingStartedAt:n?.readyPingStartedAt??null,readyAt:n?.readyAt??null,readyAttempts:n?.readyAttempts??0,visualReadySupported:n?.visualReadySupported??null,navigationGeneration:n?.navigationGeneration??null,lastError:n?.lastError??null};return G=r,r}postSilkNotification(e){if(!this.iframeWindow)throw Error(`WaaP iframe is not mounted`);this.iframeWindow.postMessage({target:`silk`,messageType:t.notification,data:e},this.walletOrigin)}postReadyNotification(){this.postSilkNotification(i.ready)}postConnectNotification(){this.postSilkNotification(i.connect)}cancelSilkRequest(e,t){this.postSilkNotification({type:i.request_cancel,requestId:e,method:t})}pingIframe(){if(this.disposed)return Promise.reject(Error(`Wallet message manager is disposed`));let e=this.iframeWindow;if(!e||typeof window>`u`)return Promise.reject(Error(`WaaP iframe is not mounted`));let n=H(e),r=S(e);return n.ready&&(!r||n.navigationGeneration===r.generation)?Promise.resolve():(n.ready&&U(e,Error(`WaaP iframe navigation changed; readiness must be re-established`)),n.promise?n.promise:(n.lastError=null,n.readyPingStartedAt=null,n.readyAt=null,n.readyAttempts=0,n.visualReadySupported=null,n.promise=new Promise((r,a)=>{n.reject=a,ne(e,3e4).then(r=>{if(this.disposed||this.iframeWindow!==e)throw Error(`Wallet message manager is disposed`);return new Promise((a,o)=>{let s=o=>{if(o.origin===this.walletOrigin&&o.source===e&&o.data?.target===`silk`&&o.data.messageType===t.notification&&o.data.data===i.ready){n.ready=!0,n.navigationGeneration=S(e)?.generation??r?.generation??null,n.readyAt=W(),n.visualReadySupported=o.data?.capabilities?.visualReady===1;let t=O();t?.contentWindow===e&&A(t,n.visualReadySupported),p(),a()}},c=()=>{try{n.readyAttempts+=1,this.postReadyNotification()}catch(e){p(),o(e)}};n.readyPingStartedAt=W();let l=250,u,d=()=>{u=window.setTimeout(()=>{c(),l=Math.min(l*2,1e3),d()},l)},f=window.setTimeout(()=>{p(),o(Error(`WaaP wallet ready handshake timed out after 10s.`))},1e4),p=()=>{u!==void 0&&window.clearTimeout(u),window.clearTimeout(f),window.removeEventListener(`message`,s),n.cleanup===p&&(n.cleanup=null,n.reject=null)};n.cleanup=p,n.reject=o,window.addEventListener(`message`,s),c(),d()})}).then(r,a)}),n.promise=n.promise.finally(()=>{n.ready||(n.lastError=n.lastError??`Wallet readiness failed`,n.promise=null)}),n.promise.catch(e=>{n.lastError=e instanceof Error?e.message:String(e)}),n.promise))}async postSilkRequest(e){if(!this.iframeWindow)throw Error(`WaaP iframe is not mounted`);let{silkOptions:n,...r}=e,i={...r,target:`silk`,messageType:t.request,...n&&{silkOptions:n}},a=await ye(i);return this.iframeWindow.postMessage({...i,id:a},this.walletOrigin),a}addListener(e){if(this.disposed)throw Error(`Wallet message manager is disposed`);De();let t={manager:this,config:e};R.add(t);let n=()=>{this.unregisterListeners.delete(n)&&(R.delete(t),Oe())};return this.unregisterListeners.add(n),n}dispose(){this.disposed||(this.disposed=!0,this.iframeWindow&&U(this.iframeWindow,Error(`Wallet message manager was disposed`)),Array.from(this.unregisterListeners).forEach(e=>e()),this.terminalResponseDeduper.clear(),this.unsubscribeIframeNavigation?.(),this.unsubscribeIframeNavigation=null,G=this.getHandshakeDiagnostics(),this.iframeWindow=null,K.delete(this))}};const q=`waap-wallet-iframe-loading`,J=new Set,Y=()=>typeof performance<`u`?performance.now():Date.now(),X=e=>{J.forEach(t=>{try{t(e)}catch{}})},Ae=e=>(J.add(e),()=>J.delete(e));var je=class{constructor(e){this.pendingRevision=null,this.phase=`idle`,this.requestedAt=null,this.visibleAt=null,this.usedVisualFallback=!1,this.onVisualReady=e=>{let t=e.detail?.revision;this.pendingRevision!==null&&typeof t==`number`&&t>=this.pendingRevision&&this.revealIframe(!1)},this.iframe=e,e.addEventListener(w,this.onVisualReady)}show({layout:e=`signing`}={}){if(this.phase===`pending`||this.phase===`visible`)return;let t=D();if(!t)return;this.clearFallbackTimer();let n=this.moveToCurrentMode(t);n===`modal`&&e===`signing`?(t.dataset.waapSizeLocked=`true`,t.style.width=`380px`,t.style.height=`600px`):n===`modal`&&delete t.dataset.waapSizeLocked,this.pendingRevision=k(this.iframe)+1,this.phase=`pending`,this.requestedAt=Y(),this.visibleAt=null,this.usedVisualFallback=!1,X({phase:`modal_requested`,at:this.requestedAt,visualRevision:this.pendingRevision}),this.hideIframeUntilPaint(t),n===`modal`?this.showModalSurface():t.style.display=`flex`;let r=oe(this.iframe);if(r===!1){this.revealIframe(!0);return}this.fallbackTimer=window.setTimeout(()=>{this.revealIframe(!0)},r===!0?3e3:750)}hide(){let e=this.pendingRevision!==null;this.pendingRevision=null,this.clearFallbackTimer(),this.phase=`hidden`;let t=Y();e&&X({phase:`modal_cancelled`,at:t,visualRevision:k(this.iframe)}),X({phase:`modal_hidden`,at:t,visualRevision:k(this.iframe)});let n=D();n&&delete n.dataset.waapSizeLocked;let r=E();if(r&&(r.style.opacity=`0`,r.style.visibility=`hidden`,r.style.pointerEvents=`none`),d()){n&&(n.style.display=`none`);return}for(let e of[n,this.iframe])e&&(e.style.visibility=`hidden`,e.style.pointerEvents=`none`)}dispose(){this.clearFallbackTimer(),this.iframe.removeEventListener(w,this.onVisualReady)}isFor(e){return this.iframe===e}getDiagnostics(){return{modalPhase:this.phase,modalRequestedAt:this.requestedAt,modalVisibleAt:this.visibleAt,usedVisualFallback:this.usedVisualFallback}}moveToCurrentMode(e){if(d()){let t=f();return t&&e.parentElement!==t&&t.appendChild(e),`component`}let t=E();return t||(t=pe(),document.body.appendChild(t)),e.parentElement!==t&&t.appendChild(e),`modal`}showModalSurface(){let e=E();e&&(e.style.display=`flex`,e.style.visibility=`visible`,e.style.opacity=`1`,e.style.pointerEvents=`auto`)}hideIframeUntilPaint(e){e.style.display=`flex`,e.style.visibility=`visible`,e.style.opacity=`1`,e.style.pointerEvents=`auto`,this.iframe.style.visibility=`hidden`,this.iframe.style.opacity=`0`,this.iframe.style.pointerEvents=`none`,this.ensureLoadingIndicator(e).style.display=`flex`}revealIframe(e){if(this.pendingRevision===null)return;let t=k(this.iframe);this.pendingRevision=null,this.clearFallbackTimer(),this.phase=`visible`,this.visibleAt=Y(),this.usedVisualFallback=e,X({phase:`modal_visible`,at:this.visibleAt,visualRevision:t,fallback:e});let n=D();if(!n)return;delete n.dataset.waapSizeLocked;let r=n.querySelector(`#${q}`);r&&(r.style.display=`none`),this.iframe.style.visibility=`visible`,this.iframe.style.opacity=`1`,this.iframe.style.pointerEvents=`auto`,n.style.visibility=`visible`,n.style.opacity=`1`,n.style.pointerEvents=`auto`}ensureLoadingIndicator(e){let t=e.querySelector(`#${q}`);if(t)return this.applyLoadingTheme(t),t;t=document.createElement(`div`),t.id=q,t.setAttribute(`role`,`status`),t.setAttribute(`aria-live`,`polite`),t.setAttribute(`aria-label`,`Loading WaaP wallet`),t.style.position=`absolute`,t.style.inset=`0`,t.style.zIndex=`1`,t.style.display=`none`,t.style.flexDirection=`column`,t.style.borderRadius=`24px`,t.style.fontFamily=`system-ui, sans-serif`,t.style.fontSize=`14px`,t.style.pointerEvents=`none`;let n=document.createElement(`div`);n.style.boxSizing=`border-box`,n.style.display=`flex`,n.style.flexDirection=`column`,n.style.width=`100%`,n.style.height=`100%`,n.style.padding=`24px`;let r=document.createElement(`img`),i=this.iframe.dataset.waapOrigin;i&&(r.src=`${i}/assets/svg/waaplogo.svg`),r.alt=`WaaP`,r.width=66,r.height=25,r.style.alignSelf=`center`,r.style.width=`66px`,r.style.height=`25px`,r.style.marginBottom=`20px`,r.dataset.waapLoadingLogo=`true`;let a=(e,t,n,r)=>{let i=document.createElement(`div`);return i.setAttribute(`aria-hidden`,`true`),i.dataset.waapLoadingPart=e,i.style.width=t,i.style.height=n,i.style.flexShrink=`0`,i.style.borderRadius=r,i.style.backgroundSize=`200% 100%`,i.style.animation=`waap-loading-shimmer 2.4s ease-in-out infinite`,i},o=a(`request-title`,`156px`,`16px`,`999px`);o.style.marginTop=`34px`;let s=a(`request-body`,`100%`,`220px`,`12px`);s.style.flex=`1`,s.style.marginTop=`18px`,s.style.opacity=`.58`;let c=document.createElement(`div`);return c.dataset.waapLoadingPart=`actions`,c.setAttribute(`aria-hidden`,`true`),c.style.display=`flex`,c.style.gap=`10px`,c.append(a(`cancel-action`,`calc(50% - 5px)`,`48px`,`12px`),a(`confirm-action`,`calc(50% - 5px)`,`48px`,`12px`)),n.append(r,o,s,c),t.appendChild(n),e.appendChild(t),this.applyLoadingTheme(t),t}applyLoadingTheme(e){let t=this.iframe.dataset.waapTheme===`dark`;e.dataset.waapTheme=t?`dark`:`light`,e.style.background=t?`#121212`:`#ffffff`,e.style.color=t?`#e6e6e6`:`#000000`;let n=e.querySelector(`[data-waap-loading-logo]`);n&&(n.style.filter=t?`invert(1)`:`none`);let r=t?`linear-gradient(90deg, rgba(255,255,255,.07), rgba(255,255,255,.14), rgba(255,255,255,.07))`:`linear-gradient(90deg, rgba(0,0,0,.05), rgba(0,0,0,.1), rgba(0,0,0,.05))`;e.querySelectorAll(`[data-waap-loading-part]`).forEach(e=>{e.style.background=r})}clearFallbackTimer(){this.fallbackTimer!==void 0&&(window.clearTimeout(this.fallbackTimer),this.fallbackTimer=void 0)}};let Z;const Q=()=>{let e=O();return e?(Z&&!Z.isFor(e)&&(Z.dispose(),Z=void 0),Z??=new je(e),Z):null},Me=e=>{Q()?.show(e)},$=()=>{Q()?.hide()},Ne=()=>{Z?.dispose(),Z=void 0},Pe=()=>{let e=O(),t=e?.contentWindow?S(e.contentWindow):null,n=Z?.getDiagnostics(),r=Number(e?.dataset.waapVisualReadyAt??``);return{walletOrigin:e?.dataset.waapOrigin??null,iframeNavigationStartedAt:t?.navigationStartedAt??null,iframeLoadedAt:t?.loadedAt??null,visualRevision:k(e),visualReadyAt:Number.isFinite(r)?r:null,modalPhase:n?.modalPhase??`idle`,modalRequestedAt:n?.modalRequestedAt??null,modalVisibleAt:n?.modalVisibleAt??null,usedVisualFallback:n?.usedVisualFallback??!1,handshake:Te()}},Fe=new Set([r.eth_sendTransaction,r.eth_signTransaction,r.personal_sign,r.eth_signTypedData_v4]),Ie=e=>Fe.has(e);function Le(e){return new Promise((t,n)=>{let r,i=!1,a=()=>{r!==void 0&&clearTimeout(r),e.eventEmitter.removeListener(e.id,o),e.signal?.removeEventListener(`abort`,c)},o=e=>{i||(i=!0,a(),t(e))},s=t=>{i||(i=!0,a(),e.onCancel?.(),n(Error(t)))},c=()=>s(`WaaP request cancelled: ${e.method}`);if(e.signal?.aborted){c();return}e.interactionRequired||(r=setTimeout(()=>{s(`WaaP request timed out: ${e.method}`)},e.timeoutMs??3e4)),e.eventEmitter.once(e.id,o),e.signal?.addEventListener(`abort`,c,{once:!0})})}function Re(e){if(typeof e!=`object`||!e)return e;try{e.waapCode=o(e).code}catch{}return e}async function ze(e,t,r,i,a){let o=e.method,s=e.params,{timeoutMs:c,signal:l,...u}=a??{};t&&Me({layout:o===n.login?`auth`:`signing`});let d;try{d=await r.postSilkRequest({method:o,params:s,interactionRequired:t,silkOptions:a?u:void 0});let e=await Le({eventEmitter:i,id:d,method:o,interactionRequired:t,timeoutMs:c,signal:l,onCancel:()=>{r.cancelSilkRequest(d,o),t&&$()}});if(t&&$(),e.error)throw Re(e.error);return e.data}catch(e){throw t&&d===void 0&&$(),e}}const Be=(e,t={})=>{if(typeof window>`u`)return()=>void 0;let n=!1,r,i,a=window,o=()=>{n||e.preload().catch(e=>t.onError?.(e))};return typeof a.requestIdleCallback==`function`?r=a.requestIdleCallback(o,{timeout:t.timeoutMs??2e3}):i=window.setTimeout(o,0),()=>{n=!0,r!==void 0&&a.cancelIdleCallback?.(r),i!==void 0&&window.clearTimeout(i)}};var Ve=function(e){return e.show_modal=`show_modal`,e.hide_modal=`hide_modal`,e}(Ve||{}),He=class extends e.EventEmitter{constructor(){super()}};Object.defineProperty(exports,"C",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return ve}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return Ie}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return ke}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return Ce}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return _e}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return ce}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return ze}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return Me}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return be}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return Ve}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return Le}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return Se}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return Be}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return He}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return Ae}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,"w",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return h}});
package/dist/bridge.js CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./UIMessageManager-CPw6PggC.js"),t=require("./asyncSigning-B0KrmKk7.js"),n=require("./SolanaProvider-Uv3q1b0H.js"),r=require("./evm-_ReyhrCP.js"),i=[e.w.eth_requestAccounts,e.w.eth_accounts,e.w.eth_sendTransaction,e.w.eth_signTransaction,e.w.eth_getBalance,e.w.personal_sign,e.w.eth_signTypedData_v4,e.w.eth_chainId,e.w.net_version,e.w.wallet_switchEthereumChain,e.w.wallet_addEthereumChain,e.w.eth_estimateGas,e.w.eth_blockNumber,e.w.eth_getCode,e.w.eth_call,e.w.eth_getTransactionReceipt,e.w.eth_getTransactionByHash],a=new Set(i),o=e=>typeof e==`string`&&a.has(e),s=[`session.login`,`session.logout`,`session.status`,`evm.connect`,`evm.request`,`solana.connect`,`solana.disconnect`,`solana.accounts`,`solana.signMessage`,`solana.signTransaction`,`solana.signAndSendTransaction`,`sdk.preload`,`sdk.destroy`],c=e=>typeof e==`string`&&s.includes(e),l=(e,t,n=`protocolError`)=>({ok:!1,id:e,error:{code:n,message:t}}),u=e=>typeof e==`object`&&!!e&&!Array.isArray(e),d=e=>u(e)&&typeof e.id==`string`&&e.id.length>0?e.id:null,f=e=>{let t=e;if(typeof e==`string`)try{t=JSON.parse(e)}catch{return l(null,`Message is not valid JSON`)}if(!u(t))return l(null,`Message must be a JSON object`);let n=d(t);return t.version===1?t.kind===`request`?n?c(t.method)?{ok:!0,request:{version:1,kind:`request`,id:n,method:t.method,params:t.params}}:{ok:!1,id:n,error:{code:`unsupportedMethod`,message:`Unsupported bridge method: ${String(t.method)}`,method:typeof t.method==`string`?t.method:void 0}}:l(null,`Request id must be a non-empty string`):l(n,`Unsupported message kind: ${String(t.kind)}`):l(n,`Unsupported protocol version: ${String(t.version)}`)},p=(e,t)=>({version:1,kind:`response`,id:e,result:t}),m=(e,t)=>({version:1,kind:`response`,id:e,error:t}),h=(e,t)=>({version:1,kind:`event`,event:e,data:t}),g=e=>JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t),_={cancelled:`cancelled`,timeout:`timeout`,user_rejected:`userRejected`,policy_rejected:`policyRejected`,insufficient_balance:`insufficientBalance`,not_authenticated:`notAuthenticated`,not_connected:`notConnected`,unsupported_input:`unsupportedInput`,wallet_error:`walletError`,maintenance:`maintenance`,unknown:`unknown`},v=[`connect`,`disconnect`,`accountsChanged`,`chainChanged`,...Object.values(t.t)],y=e=>{if(typeof e!=`object`||!e)return;let t=e.code;return typeof t==`number`?t:void 0},b=(t,n)=>{let r=e.S(t),i=y(r.cause??t);return{code:_[r.code]??`unknown`,message:r.message,...i===void 0?{}:{eip1193Code:i},...n?{method:n}:{}}},x=e=>{let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)},S=(e,t)=>{if(typeof e!=`string`)throw{bridgeError:{code:`unsupportedInput`,message:`${t} must be a base64 string`}};let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r},C=e=>({address:e.address,publicKey:x(e.publicKey),chains:[...e.chains]}),w=[`solana:mainnet`,`solana:devnet`,`solana:testnet`,`solana:localnet`],T=e=>{if(e!=null){if(typeof e==`string`&&w.includes(e))return e;throw{bridgeError:{code:`unsupportedInput`,message:`Not a supported Solana chain: ${String(e)}`}}}},E=t=>{let{post:n,createProvider:r,createSolanaProvider:i,token:a}=t,s=null,c=!1,l=new Set,u=[],d=e=>{try{n(e)}catch{}},_=e=>a?{...e,token:a}:e,y=e=>{let t;try{t=g(_(e))}catch(n){let r=n instanceof Error?n.message:String(n);t=g(_(e.kind===`response`?m(e.id,{code:`serializationFailed`,message:`Result could not be serialized for the host: ${r}`}):h(`bridgeSerializationError`,{event:e.event,message:r})))}d(t)},w=e=>{for(let t of v){let n=(...e)=>y(h(t,e.length<=1?e[0]:e));e.on(t,n),u.push([t,n])}},E=e=>{let t=e.uiMessageManager;typeof t?.on==`function`&&(t.on(`show_modal`,()=>y(h(`walletVisibilityChanged`,{visible:!0}))),t.on(`hide_modal`,()=>y(h(`walletVisibilityChanged`,{visible:!1}))))},D=null,O=null,k=null,A=t=>{let n=t.walletMessageManager;if(!n)return;if(typeof n.pingIframe!=`function`||typeof n.postSilkRequest!=`function`){y(h(`bridgeProtocolError`,{code:`walletError`,message:`Cannot announce mobile: the wallet message manager is missing pingIframe or postSilkRequest`})),O=Promise.resolve(!1);return}let r=n.pingIframe.bind(n),i=n.postSilkRequest.bind(n);k=()=>r().then(()=>i({method:e.w.set_is_mobile,params:[!0],interactionRequired:!1})).then(()=>!0).catch(e=>(y(h(`bridgeProtocolError`,{code:`walletError`,message:`Could not tell the wallet it is on mobile: ${String(e)}`})),!1)),O=k()},j=e=>{let t=e.walletMessageManager;typeof t?.addListener==`function`&&t.addListener({onAuthComplete:async e=>{let t=D;if(t){if(D=null,e===`success`){try{await I().request({method:`eth_requestAccounts`})}catch(e){y(h(`bridgeProtocolError`,{code:`walletError`,message:`Login completed but accounts could not be read: ${String(e)}`}))}N(`waap`)}t(e===`success`?`waap`:null)}}})},M=null,N=e=>{M?.setLoginMethod(e)},P=()=>{if(!i)throw{bridgeError:{code:`unsupportedMethod`,message:`This bridge was built without a Solana facade`}};if(!M){let e=I();M=i(),N(e.getLoginMethod())}return M},F=e=>{let t=P().accounts;if(t.length===0)throw{bridgeError:{code:`notConnected`,message:`Connect the Solana facade before signing`}};if(typeof e!=`string`||e.length===0)return t[0];let n=t.find(t=>t.address===e);if(!n)throw{bridgeError:{code:`unsupportedInput`,message:`Not a connected Solana account: ${e}`}};return n},I=()=>(s||(s=r(),w(s),E(s),j(s),A(s)),s),L=async e=>{let t=typeof e.params==`object`&&e.params!==null?e.params:{};switch(e.method){case`sdk.preload`:return await I().preload(),null;case`sdk.destroy`:return z(e.id),null;case`session.login`:{if(I(),await O===!1&&k&&(O=k()),await O===!1)throw{bridgeError:{code:`bridgeUnavailable`,message:`The wallet did not confirm it is running on a phone, so social login cannot open. Try again once the wallet has loaded.`,method:`session.login`}};let e=I(),n=e.loginWithNativeHandoff;if(typeof n!=`function`)throw{bridgeError:{code:`walletError`,message:`This provider cannot report a native auth hand-off; social login would silently do nothing`,method:`session.login`}};let r=await n.call(e,{force:t.force===!0});if(typeof r==`object`&&r&&r.isComplete===!1&&typeof r.authUrl==`string`)return y(h(`nativeAuthRequested`,{authUrl:r.authUrl})),await new Promise((e,t)=>{D?.(null);let n=setTimeout(()=>{D=null,t({bridgeError:{code:`timeout`,message:`The social login was not completed. The browser may have been dismissed before it finished.`,method:`session.login`}})},18e4);D=t=>{clearTimeout(n),e(t)}});let i=typeof r==`object`&&r?r.loginMethod??null:r;return N(i),i}case`session.logout`:return await I().logout(),N(null),null;case`session.status`:return I().session.getAccountStatus();case`evm.connect`:return I().request({method:`eth_requestAccounts`});case`solana.connect`:return{accounts:(await P().connect(t.silent===!0?{silent:!0}:void 0)).accounts.map(C)};case`solana.disconnect`:return await P().disconnect(),null;case`solana.accounts`:return{accounts:P().accounts.map(C)};case`solana.signMessage`:{let e=F(t.address),n=await P().signMessage({message:S(t.message,`message`),account:e});return{signedMessage:x(n.signedMessage),signature:x(n.signature)}}case`solana.signTransaction`:{let e=F(t.address),n=T(t.chain),r=await P().signTransaction({transaction:S(t.transaction,`transaction`),account:e,...n===void 0?{}:{chain:n}});return{signedTransaction:x(r.signedTransaction),signature:x(r.signature)}}case`solana.signAndSendTransaction`:{let e=F(t.address),n=T(t.chain);return{signature:(await P().signAndSendTransaction({transaction:S(t.transaction,`transaction`),account:e,...n===void 0?{}:{chain:n}})).signature}}case`evm.request`:if(!o(t.method))throw{bridgeError:{code:`unsupportedMethod`,message:`Method is not available to native callers: ${String(t.method)}`,method:typeof t.method==`string`?t.method:void 0}};return I().request({method:t.method,params:t.params})}},R=(e,t)=>{l.delete(e)&&y(t)},z=e=>{D?.(null),D=null;for(let t of[...l])t!==e&&R(t,m(t,{code:`bridgeUnavailable`,message:`Bridge was destroyed while this request was in flight`}));if(s){for(let[e,t]of u)s.removeListener(e,t);u.length=0;let e=s.destroy;typeof e==`function`&&e.call(s),s=null}M&&=(M.destroy(),null),c=!0};return{handleMessage:e=>{let t=f(e);if(!t.ok){t.id?y(m(t.id,t.error)):y(h(`bridgeProtocolError`,t.error));return}let{request:n}=t;if(c){y(m(n.id,{code:`bridgeUnavailable`,message:`Bridge has been destroyed`}));return}if(l.has(n.id)){y(h(`bridgeProtocolError`,{code:`protocolError`,message:`Request id is already in flight: ${n.id}`,id:n.id,method:n.method}));return}l.add(n.id),(async()=>{try{R(n.id,p(n.id,await L(n)))}catch(e){let t=e?.bridgeError;R(n.id,m(n.id,t??b(e,n.method)))}})()},dispose:()=>z()}},D=(e=`WaaPBridge`,t=window)=>{let n=t[e];if(typeof n?.postMessage==`function`)return e=>n.postMessage(e);let r=t.webkit?.messageHandlers?.[e];return typeof r?.postMessage==`function`?e=>r.postMessage(e):typeof t.ReactNativeWebView?.postMessage==`function`?e=>t.ReactNativeWebView.postMessage(e):null},O=(t={})=>{t.sdkPlatform&&e.p(t.sdkPlatform,t.sdkVersion??`unknown`);let i=t.post??D(t.channel);if(!i)throw Error(`[WaaP bridge] No native host channel found. The WebView must install one before loading the bridge page.`);let a={...t.init??{},deferIframe:!1},o=()=>(e.g(a),e.h(`tap`).contentWindow),s=null,c=E({post:i,token:t.token,createProvider:()=>r.n(a,`tap`,!0,[`evm`,`solana`],!1),createSolanaProvider:()=>(s??=new n.t(o(),a,o,{...a,chains:[`solana`]},!1),s.setAccountMode?.(`tap`),s)});return window.__waapBridgeReceive=e=>c.handleMessage(e),c};exports.BRIDGE_EVM_METHODS=i,exports.BRIDGE_PROTOCOL_VERSION=1,exports.createMobileBridge=E,exports.getWaaPIframeDiagnostics=e.s,exports.parseHostMessage=f,exports.resolveNativeHostPost=D,exports.startMobileBridge=O;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./UIMessageManager-Bzrjl7s7.js"),t=require("./asyncSigning-B0KrmKk7.js"),n=require("./SolanaProvider-DqkLbM2y.js"),r=require("./evm-xQ1FQAuX.js"),i=[e.w.eth_requestAccounts,e.w.eth_accounts,e.w.eth_sendTransaction,e.w.eth_signTransaction,e.w.eth_getBalance,e.w.personal_sign,e.w.eth_signTypedData_v4,e.w.eth_chainId,e.w.net_version,e.w.wallet_switchEthereumChain,e.w.wallet_addEthereumChain,e.w.eth_estimateGas,e.w.eth_blockNumber,e.w.eth_getCode,e.w.eth_call,e.w.eth_getTransactionReceipt,e.w.eth_getTransactionByHash],a=new Set(i),o=e=>typeof e==`string`&&a.has(e),s=[`session.login`,`session.logout`,`session.status`,`evm.connect`,`evm.request`,`solana.connect`,`solana.disconnect`,`solana.accounts`,`solana.signMessage`,`solana.signTransaction`,`solana.signAndSendTransaction`,`sdk.preload`,`sdk.destroy`],c=e=>typeof e==`string`&&s.includes(e),l=(e,t,n=`protocolError`)=>({ok:!1,id:e,error:{code:n,message:t}}),u=e=>typeof e==`object`&&!!e&&!Array.isArray(e),d=e=>u(e)&&typeof e.id==`string`&&e.id.length>0?e.id:null,f=e=>{let t=e;if(typeof e==`string`)try{t=JSON.parse(e)}catch{return l(null,`Message is not valid JSON`)}if(!u(t))return l(null,`Message must be a JSON object`);let n=d(t);return t.version===1?t.kind===`request`?n?c(t.method)?{ok:!0,request:{version:1,kind:`request`,id:n,method:t.method,params:t.params}}:{ok:!1,id:n,error:{code:`unsupportedMethod`,message:`Unsupported bridge method: ${String(t.method)}`,method:typeof t.method==`string`?t.method:void 0}}:l(null,`Request id must be a non-empty string`):l(n,`Unsupported message kind: ${String(t.kind)}`):l(n,`Unsupported protocol version: ${String(t.version)}`)},p=(e,t)=>({version:1,kind:`response`,id:e,result:t}),m=(e,t)=>({version:1,kind:`response`,id:e,error:t}),h=(e,t)=>({version:1,kind:`event`,event:e,data:t}),g=e=>JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t),_={cancelled:`cancelled`,timeout:`timeout`,user_rejected:`userRejected`,policy_rejected:`policyRejected`,insufficient_balance:`insufficientBalance`,not_authenticated:`notAuthenticated`,not_connected:`notConnected`,unsupported_input:`unsupportedInput`,wallet_error:`walletError`,maintenance:`maintenance`,unknown:`unknown`},v=[`connect`,`disconnect`,`accountsChanged`,`chainChanged`,...Object.values(t.t)],y=e=>{if(typeof e!=`object`||!e)return;let t=e.code;return typeof t==`number`?t:void 0},b=(t,n)=>{let r=e.S(t),i=y(r.cause??t);return{code:_[r.code]??`unknown`,message:r.message,...i===void 0?{}:{eip1193Code:i},...n?{method:n}:{}}},x=e=>{let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)},S=(e,t)=>{if(typeof e!=`string`)throw{bridgeError:{code:`unsupportedInput`,message:`${t} must be a base64 string`}};let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r},C=e=>({address:e.address,publicKey:x(e.publicKey),chains:[...e.chains]}),w=[`solana:mainnet`,`solana:devnet`,`solana:testnet`,`solana:localnet`],T=e=>{if(e!=null){if(typeof e==`string`&&w.includes(e))return e;throw{bridgeError:{code:`unsupportedInput`,message:`Not a supported Solana chain: ${String(e)}`}}}},E=t=>{let{post:n,createProvider:r,createSolanaProvider:i,token:a}=t,s=null,c=!1,l=new Set,u=[],d=e=>{try{n(e)}catch{}},_=e=>a?{...e,token:a}:e,y=e=>{let t;try{t=g(_(e))}catch(n){let r=n instanceof Error?n.message:String(n);t=g(_(e.kind===`response`?m(e.id,{code:`serializationFailed`,message:`Result could not be serialized for the host: ${r}`}):h(`bridgeSerializationError`,{event:e.event,message:r})))}d(t)},w=e=>{for(let t of v){let n=(...e)=>y(h(t,e.length<=1?e[0]:e));e.on(t,n),u.push([t,n])}},E=e=>{let t=e.uiMessageManager;typeof t?.on==`function`&&(t.on(`show_modal`,()=>y(h(`walletVisibilityChanged`,{visible:!0}))),t.on(`hide_modal`,()=>y(h(`walletVisibilityChanged`,{visible:!1}))))},D=null,O=null,k=null,A=t=>{let n=t.walletMessageManager;if(!n)return;if(typeof n.pingIframe!=`function`||typeof n.postSilkRequest!=`function`){y(h(`bridgeProtocolError`,{code:`walletError`,message:`Cannot announce mobile: the wallet message manager is missing pingIframe or postSilkRequest`})),O=Promise.resolve(!1);return}let r=n.pingIframe.bind(n),i=n.postSilkRequest.bind(n);k=()=>r().then(()=>i({method:e.w.set_is_mobile,params:[!0],interactionRequired:!1})).then(()=>!0).catch(e=>(y(h(`bridgeProtocolError`,{code:`walletError`,message:`Could not tell the wallet it is on mobile: ${String(e)}`})),!1)),O=k()},j=e=>{let t=e.walletMessageManager;typeof t?.addListener==`function`&&t.addListener({onAuthComplete:async e=>{let t=D;if(t){if(D=null,e===`success`){try{await I().request({method:`eth_requestAccounts`})}catch(e){y(h(`bridgeProtocolError`,{code:`walletError`,message:`Login completed but accounts could not be read: ${String(e)}`}))}N(`waap`)}t(e===`success`?`waap`:null)}}})},M=null,N=e=>{M?.setLoginMethod(e)},P=()=>{if(!i)throw{bridgeError:{code:`unsupportedMethod`,message:`This bridge was built without a Solana facade`}};if(!M){let e=I();M=i(),N(e.getLoginMethod())}return M},F=e=>{let t=P().accounts;if(t.length===0)throw{bridgeError:{code:`notConnected`,message:`Connect the Solana facade before signing`}};if(typeof e!=`string`||e.length===0)return t[0];let n=t.find(t=>t.address===e);if(!n)throw{bridgeError:{code:`unsupportedInput`,message:`Not a connected Solana account: ${e}`}};return n},I=()=>(s||(s=r(),w(s),E(s),j(s),A(s)),s),L=async e=>{let t=typeof e.params==`object`&&e.params!==null?e.params:{};switch(e.method){case`sdk.preload`:return await I().preload(),null;case`sdk.destroy`:return z(e.id),null;case`session.login`:{if(I(),await O===!1&&k&&(O=k()),await O===!1)throw{bridgeError:{code:`bridgeUnavailable`,message:`The wallet did not confirm it is running on a phone, so social login cannot open. Try again once the wallet has loaded.`,method:`session.login`}};let e=I(),n=e.loginWithNativeHandoff;if(typeof n!=`function`)throw{bridgeError:{code:`walletError`,message:`This provider cannot report a native auth hand-off; social login would silently do nothing`,method:`session.login`}};let r=await n.call(e,{force:t.force===!0});if(typeof r==`object`&&r&&r.isComplete===!1&&typeof r.authUrl==`string`)return y(h(`nativeAuthRequested`,{authUrl:r.authUrl})),await new Promise((e,t)=>{D?.(null);let n=setTimeout(()=>{D=null,t({bridgeError:{code:`timeout`,message:`The social login was not completed. The browser may have been dismissed before it finished.`,method:`session.login`}})},18e4);D=t=>{clearTimeout(n),e(t)}});let i=typeof r==`object`&&r?r.loginMethod??null:r;return N(i),i}case`session.logout`:return await I().logout(),N(null),null;case`session.status`:return I().session.getAccountStatus();case`evm.connect`:return I().request({method:`eth_requestAccounts`});case`solana.connect`:return{accounts:(await P().connect(t.silent===!0?{silent:!0}:void 0)).accounts.map(C)};case`solana.disconnect`:return await P().disconnect(),null;case`solana.accounts`:return{accounts:P().accounts.map(C)};case`solana.signMessage`:{let e=F(t.address),n=await P().signMessage({message:S(t.message,`message`),account:e});return{signedMessage:x(n.signedMessage),signature:x(n.signature)}}case`solana.signTransaction`:{let e=F(t.address),n=T(t.chain),r=await P().signTransaction({transaction:S(t.transaction,`transaction`),account:e,...n===void 0?{}:{chain:n}});return{signedTransaction:x(r.signedTransaction),signature:x(r.signature)}}case`solana.signAndSendTransaction`:{let e=F(t.address),n=T(t.chain);return{signature:(await P().signAndSendTransaction({transaction:S(t.transaction,`transaction`),account:e,...n===void 0?{}:{chain:n}})).signature}}case`evm.request`:if(!o(t.method))throw{bridgeError:{code:`unsupportedMethod`,message:`Method is not available to native callers: ${String(t.method)}`,method:typeof t.method==`string`?t.method:void 0}};return I().request({method:t.method,params:t.params})}},R=(e,t)=>{l.delete(e)&&y(t)},z=e=>{D?.(null),D=null;for(let t of[...l])t!==e&&R(t,m(t,{code:`bridgeUnavailable`,message:`Bridge was destroyed while this request was in flight`}));if(s){for(let[e,t]of u)s.removeListener(e,t);u.length=0;let e=s.destroy;typeof e==`function`&&e.call(s),s=null}M&&=(M.destroy(),null),c=!0};return{handleMessage:e=>{let t=f(e);if(!t.ok){t.id?y(m(t.id,t.error)):y(h(`bridgeProtocolError`,t.error));return}let{request:n}=t;if(c){y(m(n.id,{code:`bridgeUnavailable`,message:`Bridge has been destroyed`}));return}if(l.has(n.id)){y(h(`bridgeProtocolError`,{code:`protocolError`,message:`Request id is already in flight: ${n.id}`,id:n.id,method:n.method}));return}l.add(n.id),(async()=>{try{R(n.id,p(n.id,await L(n)))}catch(e){let t=e?.bridgeError;R(n.id,m(n.id,t??b(e,n.method)))}})()},dispose:()=>z()}},D=(e=`WaaPBridge`,t=window)=>{let n=t[e];if(typeof n?.postMessage==`function`)return e=>n.postMessage(e);let r=t.webkit?.messageHandlers?.[e];return typeof r?.postMessage==`function`?e=>r.postMessage(e):typeof t.ReactNativeWebView?.postMessage==`function`?e=>t.ReactNativeWebView.postMessage(e):null},O=(t={})=>{t.sdkPlatform&&e.p(t.sdkPlatform,t.sdkVersion??`unknown`);let i=t.post??D(t.channel);if(!i)throw Error(`[WaaP bridge] No native host channel found. The WebView must install one before loading the bridge page.`);let a={...t.init??{},deferIframe:!1},o=()=>(e.g(a),e.h(`tap`).contentWindow),s=null,c=E({post:i,token:t.token,createProvider:()=>r.n(a,`tap`,!0,[`evm`,`solana`],!1),createSolanaProvider:()=>(s??=new n.t(o(),a,o,{...a,chains:[`solana`]},!1),s.setAccountMode?.(`tap`),s)});return window.__waapBridgeReceive=e=>c.handleMessage(e),c};exports.BRIDGE_EVM_METHODS=i,exports.BRIDGE_PROTOCOL_VERSION=1,exports.createMobileBridge=E,exports.getWaaPIframeDiagnostics=e.s,exports.parseHostMessage=f,exports.resolveNativeHostPost=D,exports.startMobileBridge=O;
package/dist/bridge.mjs CHANGED
@@ -1 +1 @@
1
- import{S as e,g as t,h as n,p as r,s as i,w as a}from"./UIMessageManager-D3VN9vM8.mjs";import{t as o}from"./asyncSigning-CzqBbYDP.mjs";import{t as s}from"./SolanaProvider-BKWKXTWh.mjs";import{n as c}from"./evm-BbSgL_Hv.mjs";const l=[a.eth_requestAccounts,a.eth_accounts,a.eth_sendTransaction,a.eth_signTransaction,a.eth_getBalance,a.personal_sign,a.eth_signTypedData_v4,a.eth_chainId,a.net_version,a.wallet_switchEthereumChain,a.wallet_addEthereumChain,a.eth_estimateGas,a.eth_blockNumber,a.eth_getCode,a.eth_call,a.eth_getTransactionReceipt,a.eth_getTransactionByHash],u=new Set(l),d=e=>typeof e==`string`&&u.has(e),f=1,p=[`session.login`,`session.logout`,`session.status`,`evm.connect`,`evm.request`,`solana.connect`,`solana.disconnect`,`solana.accounts`,`solana.signMessage`,`solana.signTransaction`,`solana.signAndSendTransaction`,`sdk.preload`,`sdk.destroy`],m=e=>typeof e==`string`&&p.includes(e),h=(e,t,n=`protocolError`)=>({ok:!1,id:e,error:{code:n,message:t}}),g=e=>typeof e==`object`&&!!e&&!Array.isArray(e),_=e=>g(e)&&typeof e.id==`string`&&e.id.length>0?e.id:null,v=e=>{let t=e;if(typeof e==`string`)try{t=JSON.parse(e)}catch{return h(null,`Message is not valid JSON`)}if(!g(t))return h(null,`Message must be a JSON object`);let n=_(t);return t.version===1?t.kind===`request`?n?m(t.method)?{ok:!0,request:{version:1,kind:`request`,id:n,method:t.method,params:t.params}}:{ok:!1,id:n,error:{code:`unsupportedMethod`,message:`Unsupported bridge method: ${String(t.method)}`,method:typeof t.method==`string`?t.method:void 0}}:h(null,`Request id must be a non-empty string`):h(n,`Unsupported message kind: ${String(t.kind)}`):h(n,`Unsupported protocol version: ${String(t.version)}`)},y=(e,t)=>({version:1,kind:`response`,id:e,result:t}),b=(e,t)=>({version:1,kind:`response`,id:e,error:t}),x=(e,t)=>({version:1,kind:`event`,event:e,data:t}),S=e=>JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t),C={cancelled:`cancelled`,timeout:`timeout`,user_rejected:`userRejected`,policy_rejected:`policyRejected`,insufficient_balance:`insufficientBalance`,not_authenticated:`notAuthenticated`,not_connected:`notConnected`,unsupported_input:`unsupportedInput`,wallet_error:`walletError`,maintenance:`maintenance`,unknown:`unknown`},w=[`connect`,`disconnect`,`accountsChanged`,`chainChanged`,...Object.values(o)],T=e=>{if(typeof e!=`object`||!e)return;let t=e.code;return typeof t==`number`?t:void 0},E=(t,n)=>{let r=e(t),i=T(r.cause??t);return{code:C[r.code]??`unknown`,message:r.message,...i===void 0?{}:{eip1193Code:i},...n?{method:n}:{}}},D=e=>{let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)},O=(e,t)=>{if(typeof e!=`string`)throw{bridgeError:{code:`unsupportedInput`,message:`${t} must be a base64 string`}};let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r},k=e=>({address:e.address,publicKey:D(e.publicKey),chains:[...e.chains]}),A=[`solana:mainnet`,`solana:devnet`,`solana:testnet`,`solana:localnet`],j=e=>{if(e!=null){if(typeof e==`string`&&A.includes(e))return e;throw{bridgeError:{code:`unsupportedInput`,message:`Not a supported Solana chain: ${String(e)}`}}}},M=e=>{let{post:t,createProvider:n,createSolanaProvider:r,token:i}=e,o=null,s=!1,c=new Set,l=[],u=e=>{try{t(e)}catch{}},f=e=>i?{...e,token:i}:e,p=e=>{let t;try{t=S(f(e))}catch(n){let r=n instanceof Error?n.message:String(n);t=S(f(e.kind===`response`?b(e.id,{code:`serializationFailed`,message:`Result could not be serialized for the host: ${r}`}):x(`bridgeSerializationError`,{event:e.event,message:r})))}u(t)},m=e=>{for(let t of w){let n=(...e)=>p(x(t,e.length<=1?e[0]:e));e.on(t,n),l.push([t,n])}},h=e=>{let t=e.uiMessageManager;typeof t?.on==`function`&&(t.on(`show_modal`,()=>p(x(`walletVisibilityChanged`,{visible:!0}))),t.on(`hide_modal`,()=>p(x(`walletVisibilityChanged`,{visible:!1}))))},g=null,_=null,C=null,T=e=>{let t=e.walletMessageManager;if(!t)return;if(typeof t.pingIframe!=`function`||typeof t.postSilkRequest!=`function`){p(x(`bridgeProtocolError`,{code:`walletError`,message:`Cannot announce mobile: the wallet message manager is missing pingIframe or postSilkRequest`})),_=Promise.resolve(!1);return}let n=t.pingIframe.bind(t),r=t.postSilkRequest.bind(t);C=()=>n().then(()=>r({method:a.set_is_mobile,params:[!0],interactionRequired:!1})).then(()=>!0).catch(e=>(p(x(`bridgeProtocolError`,{code:`walletError`,message:`Could not tell the wallet it is on mobile: ${String(e)}`})),!1)),_=C()},A=e=>{let t=e.walletMessageManager;typeof t?.addListener==`function`&&t.addListener({onAuthComplete:async e=>{let t=g;if(t){if(g=null,e===`success`){try{await I().request({method:`eth_requestAccounts`})}catch(e){p(x(`bridgeProtocolError`,{code:`walletError`,message:`Login completed but accounts could not be read: ${String(e)}`}))}N(`waap`)}t(e===`success`?`waap`:null)}}})},M=null,N=e=>{M?.setLoginMethod(e)},P=()=>{if(!r)throw{bridgeError:{code:`unsupportedMethod`,message:`This bridge was built without a Solana facade`}};if(!M){let e=I();M=r(),N(e.getLoginMethod())}return M},F=e=>{let t=P().accounts;if(t.length===0)throw{bridgeError:{code:`notConnected`,message:`Connect the Solana facade before signing`}};if(typeof e!=`string`||e.length===0)return t[0];let n=t.find(t=>t.address===e);if(!n)throw{bridgeError:{code:`unsupportedInput`,message:`Not a connected Solana account: ${e}`}};return n},I=()=>(o||(o=n(),m(o),h(o),A(o),T(o)),o),L=async e=>{let t=typeof e.params==`object`&&e.params!==null?e.params:{};switch(e.method){case`sdk.preload`:return await I().preload(),null;case`sdk.destroy`:return z(e.id),null;case`session.login`:{if(I(),await _===!1&&C&&(_=C()),await _===!1)throw{bridgeError:{code:`bridgeUnavailable`,message:`The wallet did not confirm it is running on a phone, so social login cannot open. Try again once the wallet has loaded.`,method:`session.login`}};let e=I(),n=e.loginWithNativeHandoff;if(typeof n!=`function`)throw{bridgeError:{code:`walletError`,message:`This provider cannot report a native auth hand-off; social login would silently do nothing`,method:`session.login`}};let r=await n.call(e,{force:t.force===!0});if(typeof r==`object`&&r&&r.isComplete===!1&&typeof r.authUrl==`string`)return p(x(`nativeAuthRequested`,{authUrl:r.authUrl})),await new Promise((e,t)=>{g?.(null);let n=setTimeout(()=>{g=null,t({bridgeError:{code:`timeout`,message:`The social login was not completed. The browser may have been dismissed before it finished.`,method:`session.login`}})},18e4);g=t=>{clearTimeout(n),e(t)}});let i=typeof r==`object`&&r?r.loginMethod??null:r;return N(i),i}case`session.logout`:return await I().logout(),N(null),null;case`session.status`:return I().session.getAccountStatus();case`evm.connect`:return I().request({method:`eth_requestAccounts`});case`solana.connect`:return{accounts:(await P().connect(t.silent===!0?{silent:!0}:void 0)).accounts.map(k)};case`solana.disconnect`:return await P().disconnect(),null;case`solana.accounts`:return{accounts:P().accounts.map(k)};case`solana.signMessage`:{let e=F(t.address),n=await P().signMessage({message:O(t.message,`message`),account:e});return{signedMessage:D(n.signedMessage),signature:D(n.signature)}}case`solana.signTransaction`:{let e=F(t.address),n=j(t.chain),r=await P().signTransaction({transaction:O(t.transaction,`transaction`),account:e,...n===void 0?{}:{chain:n}});return{signedTransaction:D(r.signedTransaction),signature:D(r.signature)}}case`solana.signAndSendTransaction`:{let e=F(t.address),n=j(t.chain);return{signature:(await P().signAndSendTransaction({transaction:O(t.transaction,`transaction`),account:e,...n===void 0?{}:{chain:n}})).signature}}case`evm.request`:if(!d(t.method))throw{bridgeError:{code:`unsupportedMethod`,message:`Method is not available to native callers: ${String(t.method)}`,method:typeof t.method==`string`?t.method:void 0}};return I().request({method:t.method,params:t.params})}},R=(e,t)=>{c.delete(e)&&p(t)},z=e=>{g?.(null),g=null;for(let t of[...c])t!==e&&R(t,b(t,{code:`bridgeUnavailable`,message:`Bridge was destroyed while this request was in flight`}));if(o){for(let[e,t]of l)o.removeListener(e,t);l.length=0;let e=o.destroy;typeof e==`function`&&e.call(o),o=null}M&&=(M.destroy(),null),s=!0};return{handleMessage:e=>{let t=v(e);if(!t.ok){t.id?p(b(t.id,t.error)):p(x(`bridgeProtocolError`,t.error));return}let{request:n}=t;if(s){p(b(n.id,{code:`bridgeUnavailable`,message:`Bridge has been destroyed`}));return}if(c.has(n.id)){p(x(`bridgeProtocolError`,{code:`protocolError`,message:`Request id is already in flight: ${n.id}`,id:n.id,method:n.method}));return}c.add(n.id),(async()=>{try{R(n.id,y(n.id,await L(n)))}catch(e){let t=e?.bridgeError;R(n.id,b(n.id,t??E(e,n.method)))}})()},dispose:()=>z()}},N=(e=`WaaPBridge`,t=window)=>{let n=t[e];if(typeof n?.postMessage==`function`)return e=>n.postMessage(e);let r=t.webkit?.messageHandlers?.[e];return typeof r?.postMessage==`function`?e=>r.postMessage(e):typeof t.ReactNativeWebView?.postMessage==`function`?e=>t.ReactNativeWebView.postMessage(e):null},P=(e={})=>{e.sdkPlatform&&r(e.sdkPlatform,e.sdkVersion??`unknown`);let i=e.post??N(e.channel);if(!i)throw Error(`[WaaP bridge] No native host channel found. The WebView must install one before loading the bridge page.`);let a={...e.init??{},deferIframe:!1},o=()=>(t(a),n(`tap`).contentWindow),l=null,u=M({post:i,token:e.token,createProvider:()=>c(a,`tap`,!0,[`evm`,`solana`],!1),createSolanaProvider:()=>(l??=new s(o(),a,o,{...a,chains:[`solana`]},!1),l.setAccountMode?.(`tap`),l)});return window.__waapBridgeReceive=e=>u.handleMessage(e),u};export{l as BRIDGE_EVM_METHODS,f as BRIDGE_PROTOCOL_VERSION,M as createMobileBridge,i as getWaaPIframeDiagnostics,v as parseHostMessage,N as resolveNativeHostPost,P as startMobileBridge};
1
+ import{S as e,g as t,h as n,p as r,s as i,w as a}from"./UIMessageManager-BSJdvCEF.mjs";import{t as o}from"./asyncSigning-CzqBbYDP.mjs";import{t as s}from"./SolanaProvider-BcOLwJrt.mjs";import{n as c}from"./evm-dDrPUbNZ.mjs";const l=[a.eth_requestAccounts,a.eth_accounts,a.eth_sendTransaction,a.eth_signTransaction,a.eth_getBalance,a.personal_sign,a.eth_signTypedData_v4,a.eth_chainId,a.net_version,a.wallet_switchEthereumChain,a.wallet_addEthereumChain,a.eth_estimateGas,a.eth_blockNumber,a.eth_getCode,a.eth_call,a.eth_getTransactionReceipt,a.eth_getTransactionByHash],u=new Set(l),d=e=>typeof e==`string`&&u.has(e),f=1,p=[`session.login`,`session.logout`,`session.status`,`evm.connect`,`evm.request`,`solana.connect`,`solana.disconnect`,`solana.accounts`,`solana.signMessage`,`solana.signTransaction`,`solana.signAndSendTransaction`,`sdk.preload`,`sdk.destroy`],m=e=>typeof e==`string`&&p.includes(e),h=(e,t,n=`protocolError`)=>({ok:!1,id:e,error:{code:n,message:t}}),g=e=>typeof e==`object`&&!!e&&!Array.isArray(e),_=e=>g(e)&&typeof e.id==`string`&&e.id.length>0?e.id:null,v=e=>{let t=e;if(typeof e==`string`)try{t=JSON.parse(e)}catch{return h(null,`Message is not valid JSON`)}if(!g(t))return h(null,`Message must be a JSON object`);let n=_(t);return t.version===1?t.kind===`request`?n?m(t.method)?{ok:!0,request:{version:1,kind:`request`,id:n,method:t.method,params:t.params}}:{ok:!1,id:n,error:{code:`unsupportedMethod`,message:`Unsupported bridge method: ${String(t.method)}`,method:typeof t.method==`string`?t.method:void 0}}:h(null,`Request id must be a non-empty string`):h(n,`Unsupported message kind: ${String(t.kind)}`):h(n,`Unsupported protocol version: ${String(t.version)}`)},y=(e,t)=>({version:1,kind:`response`,id:e,result:t}),b=(e,t)=>({version:1,kind:`response`,id:e,error:t}),x=(e,t)=>({version:1,kind:`event`,event:e,data:t}),S=e=>JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t),C={cancelled:`cancelled`,timeout:`timeout`,user_rejected:`userRejected`,policy_rejected:`policyRejected`,insufficient_balance:`insufficientBalance`,not_authenticated:`notAuthenticated`,not_connected:`notConnected`,unsupported_input:`unsupportedInput`,wallet_error:`walletError`,maintenance:`maintenance`,unknown:`unknown`},w=[`connect`,`disconnect`,`accountsChanged`,`chainChanged`,...Object.values(o)],T=e=>{if(typeof e!=`object`||!e)return;let t=e.code;return typeof t==`number`?t:void 0},E=(t,n)=>{let r=e(t),i=T(r.cause??t);return{code:C[r.code]??`unknown`,message:r.message,...i===void 0?{}:{eip1193Code:i},...n?{method:n}:{}}},D=e=>{let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)},O=(e,t)=>{if(typeof e!=`string`)throw{bridgeError:{code:`unsupportedInput`,message:`${t} must be a base64 string`}};let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r},k=e=>({address:e.address,publicKey:D(e.publicKey),chains:[...e.chains]}),A=[`solana:mainnet`,`solana:devnet`,`solana:testnet`,`solana:localnet`],j=e=>{if(e!=null){if(typeof e==`string`&&A.includes(e))return e;throw{bridgeError:{code:`unsupportedInput`,message:`Not a supported Solana chain: ${String(e)}`}}}},M=e=>{let{post:t,createProvider:n,createSolanaProvider:r,token:i}=e,o=null,s=!1,c=new Set,l=[],u=e=>{try{t(e)}catch{}},f=e=>i?{...e,token:i}:e,p=e=>{let t;try{t=S(f(e))}catch(n){let r=n instanceof Error?n.message:String(n);t=S(f(e.kind===`response`?b(e.id,{code:`serializationFailed`,message:`Result could not be serialized for the host: ${r}`}):x(`bridgeSerializationError`,{event:e.event,message:r})))}u(t)},m=e=>{for(let t of w){let n=(...e)=>p(x(t,e.length<=1?e[0]:e));e.on(t,n),l.push([t,n])}},h=e=>{let t=e.uiMessageManager;typeof t?.on==`function`&&(t.on(`show_modal`,()=>p(x(`walletVisibilityChanged`,{visible:!0}))),t.on(`hide_modal`,()=>p(x(`walletVisibilityChanged`,{visible:!1}))))},g=null,_=null,C=null,T=e=>{let t=e.walletMessageManager;if(!t)return;if(typeof t.pingIframe!=`function`||typeof t.postSilkRequest!=`function`){p(x(`bridgeProtocolError`,{code:`walletError`,message:`Cannot announce mobile: the wallet message manager is missing pingIframe or postSilkRequest`})),_=Promise.resolve(!1);return}let n=t.pingIframe.bind(t),r=t.postSilkRequest.bind(t);C=()=>n().then(()=>r({method:a.set_is_mobile,params:[!0],interactionRequired:!1})).then(()=>!0).catch(e=>(p(x(`bridgeProtocolError`,{code:`walletError`,message:`Could not tell the wallet it is on mobile: ${String(e)}`})),!1)),_=C()},A=e=>{let t=e.walletMessageManager;typeof t?.addListener==`function`&&t.addListener({onAuthComplete:async e=>{let t=g;if(t){if(g=null,e===`success`){try{await I().request({method:`eth_requestAccounts`})}catch(e){p(x(`bridgeProtocolError`,{code:`walletError`,message:`Login completed but accounts could not be read: ${String(e)}`}))}N(`waap`)}t(e===`success`?`waap`:null)}}})},M=null,N=e=>{M?.setLoginMethod(e)},P=()=>{if(!r)throw{bridgeError:{code:`unsupportedMethod`,message:`This bridge was built without a Solana facade`}};if(!M){let e=I();M=r(),N(e.getLoginMethod())}return M},F=e=>{let t=P().accounts;if(t.length===0)throw{bridgeError:{code:`notConnected`,message:`Connect the Solana facade before signing`}};if(typeof e!=`string`||e.length===0)return t[0];let n=t.find(t=>t.address===e);if(!n)throw{bridgeError:{code:`unsupportedInput`,message:`Not a connected Solana account: ${e}`}};return n},I=()=>(o||(o=n(),m(o),h(o),A(o),T(o)),o),L=async e=>{let t=typeof e.params==`object`&&e.params!==null?e.params:{};switch(e.method){case`sdk.preload`:return await I().preload(),null;case`sdk.destroy`:return z(e.id),null;case`session.login`:{if(I(),await _===!1&&C&&(_=C()),await _===!1)throw{bridgeError:{code:`bridgeUnavailable`,message:`The wallet did not confirm it is running on a phone, so social login cannot open. Try again once the wallet has loaded.`,method:`session.login`}};let e=I(),n=e.loginWithNativeHandoff;if(typeof n!=`function`)throw{bridgeError:{code:`walletError`,message:`This provider cannot report a native auth hand-off; social login would silently do nothing`,method:`session.login`}};let r=await n.call(e,{force:t.force===!0});if(typeof r==`object`&&r&&r.isComplete===!1&&typeof r.authUrl==`string`)return p(x(`nativeAuthRequested`,{authUrl:r.authUrl})),await new Promise((e,t)=>{g?.(null);let n=setTimeout(()=>{g=null,t({bridgeError:{code:`timeout`,message:`The social login was not completed. The browser may have been dismissed before it finished.`,method:`session.login`}})},18e4);g=t=>{clearTimeout(n),e(t)}});let i=typeof r==`object`&&r?r.loginMethod??null:r;return N(i),i}case`session.logout`:return await I().logout(),N(null),null;case`session.status`:return I().session.getAccountStatus();case`evm.connect`:return I().request({method:`eth_requestAccounts`});case`solana.connect`:return{accounts:(await P().connect(t.silent===!0?{silent:!0}:void 0)).accounts.map(k)};case`solana.disconnect`:return await P().disconnect(),null;case`solana.accounts`:return{accounts:P().accounts.map(k)};case`solana.signMessage`:{let e=F(t.address),n=await P().signMessage({message:O(t.message,`message`),account:e});return{signedMessage:D(n.signedMessage),signature:D(n.signature)}}case`solana.signTransaction`:{let e=F(t.address),n=j(t.chain),r=await P().signTransaction({transaction:O(t.transaction,`transaction`),account:e,...n===void 0?{}:{chain:n}});return{signedTransaction:D(r.signedTransaction),signature:D(r.signature)}}case`solana.signAndSendTransaction`:{let e=F(t.address),n=j(t.chain);return{signature:(await P().signAndSendTransaction({transaction:O(t.transaction,`transaction`),account:e,...n===void 0?{}:{chain:n}})).signature}}case`evm.request`:if(!d(t.method))throw{bridgeError:{code:`unsupportedMethod`,message:`Method is not available to native callers: ${String(t.method)}`,method:typeof t.method==`string`?t.method:void 0}};return I().request({method:t.method,params:t.params})}},R=(e,t)=>{c.delete(e)&&p(t)},z=e=>{g?.(null),g=null;for(let t of[...c])t!==e&&R(t,b(t,{code:`bridgeUnavailable`,message:`Bridge was destroyed while this request was in flight`}));if(o){for(let[e,t]of l)o.removeListener(e,t);l.length=0;let e=o.destroy;typeof e==`function`&&e.call(o),o=null}M&&=(M.destroy(),null),s=!0};return{handleMessage:e=>{let t=v(e);if(!t.ok){t.id?p(b(t.id,t.error)):p(x(`bridgeProtocolError`,t.error));return}let{request:n}=t;if(s){p(b(n.id,{code:`bridgeUnavailable`,message:`Bridge has been destroyed`}));return}if(c.has(n.id)){p(x(`bridgeProtocolError`,{code:`protocolError`,message:`Request id is already in flight: ${n.id}`,id:n.id,method:n.method}));return}c.add(n.id),(async()=>{try{R(n.id,y(n.id,await L(n)))}catch(e){let t=e?.bridgeError;R(n.id,b(n.id,t??E(e,n.method)))}})()},dispose:()=>z()}},N=(e=`WaaPBridge`,t=window)=>{let n=t[e];if(typeof n?.postMessage==`function`)return e=>n.postMessage(e);let r=t.webkit?.messageHandlers?.[e];return typeof r?.postMessage==`function`?e=>r.postMessage(e):typeof t.ReactNativeWebView?.postMessage==`function`?e=>t.ReactNativeWebView.postMessage(e):null},P=(e={})=>{e.sdkPlatform&&r(e.sdkPlatform,e.sdkVersion??`unknown`);let i=e.post??N(e.channel);if(!i)throw Error(`[WaaP bridge] No native host channel found. The WebView must install one before loading the bridge page.`);let a={...e.init??{},deferIframe:!1},o=()=>(t(a),n(`tap`).contentWindow),l=null,u=M({post:i,token:e.token,createProvider:()=>c(a,`tap`,!0,[`evm`,`solana`],!1),createSolanaProvider:()=>(l??=new s(o(),a,o,{...a,chains:[`solana`]},!1),l.setAccountMode?.(`tap`),l)});return window.__waapBridgeReceive=e=>u.handleMessage(e),u};export{l as BRIDGE_EVM_METHODS,f as BRIDGE_PROTOCOL_VERSION,M as createMobileBridge,i as getWaaPIframeDiagnostics,v as parseHostMessage,N as resolveNativeHostPost,P as startMobileBridge};
@@ -1,2 +1,2 @@
1
- import{C as e,_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,r as d,t as f,v as p,w as m,x as h}from"./UIMessageManager-D3VN9vM8.mjs";import{t as g}from"./WalletConnect-DXiTxC-F.mjs";import{EventEmitter as _}from"events";import{getAddress as v}from"ethers";const y=e=>typeof e==`object`&&!!e&&e.isComplete===!1&&typeof e.authUrl==`string`;function b(e){return!(!e?.isMetaMask||e.isApexWallet||e.isAvalanche||e.isBitKeep||e.isBlockWallet||e.isMathWallet||e.isOkxWallet||e.isOKExWallet||e.isOneInchIOSWallet||e.isOneInchAndroidWallet||e.isOpera||e.isPortal||e.isRabby||e.isDefiant||e.isTokenPocket||e.isTokenary||e.isZerion)}function x(e){try{if(!e||!Array.isArray(e))return!1;let t=JSON.parse(typeof e[1]==`string`?e[1]:JSON.stringify(e[1]));return t.primaryType===`SafeTx`&&t.domain?.verifyingContract!==void 0&&t.message&&`to`in t.message&&`value`in t.message&&`safeTxGas`in t.message&&`baseGas`in t.message&&`gasPrice`in t.message&&`nonce`in t.message}catch{return!1}}const S={styles:{darkMode:!1}},C=[`waap`,`human`,`injected`,`walletconnect`],w=[e.eth_sendTransaction,e.eth_signTransaction,e.eth_signTypedData_v4,e.personal_sign];function T(e){if(e==null)return null;if(typeof e==`string`){if(C.includes(e))return e;throw Error(`[EthereumProvider] Unexpected login method: "${e}". Expected one of: ${C.join(`, `)}`)}if(typeof e==`object`&&`loginMethod`in e&&typeof e.loginMethod==`string`){let t=e.loginMethod;if(console.warn(`[EthereumProvider] Received object login response. Normalizing "${t}" to string. This is unexpected for the web SDK.`),C.includes(t))return t;throw Error(`[EthereumProvider] Unknown loginMethod in object: "${t}". Expected one of: ${C.join(`, `)}`)}throw Error(`[EthereumProvider] Unexpected login response: ${JSON.stringify(e)} (type: ${typeof e})`)}var E=class extends _{setExposeOnWindow(e){this.exposeOnWindow=e}constructor(e,t,n,r,a,o=!1,s=!1,c,l=[`evm`]){super(),this.lastKnownConversion=`pending`,this.isSilk=!0,this.isWaaP=!0,this.connected=!1,this.exposeOnWindow=!0,this.currentAccount=null,this.accountMode=`tap`,this.walletConnectProvider=null,this.asyncTxs=!1,this.legacyAsyncSigning=!1,this.internalEventEmitter=new _,this.iframeMounted=!0,this.initializerPromise=null,this.sessionProbe=null,this.initializedIframeWindow=null,this.waapRestoreRetryAt=0,this.asyncTxs=o,this.legacyAsyncSigning=s,this.ensureIframe=c,this.iframeMounted=!c,this.referralCode=t,this.project=r,this.customConfig=n,this.initializerChains=l,this.uiMessageManager=new f,this.walletMessageManager=new i(e,a),this.config={...S,...n||{}},this.persistedMethods={login:this.login.bind(this),logout:this.logout.bind(this),getLoginMethod:this.getLoginMethod.bind(this),walletMessageManager:this.walletMessageManager,internalEventEmitter:this.internalEventEmitter,uiMessageManager:this.uiMessageManager,portal:this.portal.bind(this),requestEmail:this.requestEmail.bind(this),requestSBT:this.requestSBT.bind(this),requestPermissionToken:this.requestPermissionToken.bind(this),getLinkedAddresses:this.getLinkedAddresses.bind(this),linkAddress:this.linkAddress.bind(this),unlinkAddress:this.unlinkAddress.bind(this),orcid:this.orcid.bind(this),enable:this.enable.bind(this),isConnected:this.isConnected.bind(this),toggleDarkMode:this.toggleDarkMode.bind(this),destroy:this.destroy.bind(this),silkRequest:this.request.bind(this),waaPRequest:this.request.bind(this)},this.walletMessageManager.addListener({onReceiveConnectNotif:()=>{this.connected=!0,this.emit(`connect`)},handleResponse:e=>this.internalEventEmitter.emit(e.id,e),handleRequest:e=>{e.method===m.show_modal?this.uiMessageManager.emit(`show_modal`):e.method===m.hide_modal&&this.uiMessageManager.emit(`hide_modal`)},onAccountChanged:e=>{this.currentAccount!==e&&(this.currentAccount=e,this.emit(`accountsChanged`,e?[e]:[]))},onAsyncTxNotification:e=>{this.emit(e.type,e.payload)},onSquidLifecycleNotification:e=>{this.emit(e.type,e.payload)}})}async initializeWalletConnect(){try{this.walletConnectProvider=await g.getInstance()}catch(e){console.error(`Failed to initialize WalletConnect provider:`,e),this.walletConnectProvider=null}}async initializeIframeContext(){let e=this.walletMessageManager.getIframeWindow();if(!e)throw Error(`WaaP iframe is not mounted`);if(this.initializedIframeWindow===e&&this.initializerPromise)return this.initializerPromise;this.initializedIframeWindow=e,this.initializerPromise=u(e,async()=>{await this.walletMessageManager.pingIframe(),await c({method:m.set_signing_mode,params:[a(this.accountMode,{referralCode:this.referralCode,project:this.project,config:this.customConfig,chains:this.initializerChains})]},!1,this.walletMessageManager,this.internalEventEmitter)});try{await this.initializerPromise}catch(e){throw this.initializerPromise=null,this.initializedIframeWindow=null,e}}async reassertIframeAccountMode(){this.ensureIframeMounted(),await this.walletMessageManager.pingIframe(),await c({method:m.set_signing_mode,params:[a(this.accountMode,{referralCode:this.referralCode,project:this.project,config:this.customConfig,chains:this.initializerChains})]},!1,this.walletMessageManager,this.internalEventEmitter)}ensureIframeMounted(){if(this.iframeMounted||!this.ensureIframe)return;let e=this.ensureIframe();e&&(this.iframeMounted=!0,this.walletMessageManager.setIframeWindow(e))}async ensureInitialized(){this.ensureIframeMounted(),await this.initializeIframeContext()}async preload(){await this.ensureInitialized()}async enable(){return this.request({method:`eth_requestAccounts`})}isConnected(){return this.connected}getAccountStatus(){let e=this.getLoginMethod();return{authenticated:e!==null,loginMethod:e,activeMode:e?this.accountMode:null,mode:this.accountMode,conversion:e?this.lastKnownConversion:`not_required`,tap:null,squid:null,accounts:this.currentAccount?{evm:this.currentAccount}:{}}}get session(){return{login:e=>this.login(e),logout:async()=>{await this.logout()},getLoginMethod:()=>this.getLoginMethod(),getAccountStatus:()=>this.getCanonicalAccountStatus()}}async getCanonicalAccountStatus(){await this.ensureInitialized();let e=await c({method:m.waap_getAccountStatus,params:[]},!1,this.walletMessageManager,this.internalEventEmitter);return e?.conversion&&(this.lastKnownConversion=e.conversion),e}setAccountMode(e){this.accountMode=e,this.initializerPromise=null,this.initializedIframeWindow=null}async request(t){if(!Object.keys(e).includes(t.method))return Promise.reject({error:`Not implemented (${t.method})`});let r=await this.attemptAutoConnect(t.method);if(r!==null)return r;if(w.includes(t.method)&&!(this.getLoginMethod()!==null||await this.restorePersistedWaaPSession()!==null))return Promise.reject(new h(`not_authenticated`,`Not authenticated: call login() before signing.`,{operation:{chain:`evm`,method:t.method}}));if(x(t.params)&&t.method!==e.eth_signTypedData_v4)return Promise.reject({error:`Safe transactions must be signed using eth_signTypedData_v4`});await this.ensureInitialized();let i=(t.method===e.eth_sendTransaction||t.method===e.eth_signTransaction||t.method===e.eth_signTypedData_v4||t.method===e.personal_sign)&&this.asyncTxs||t.async,a=i||t.withPT||t.timeoutMs!==void 0||t.signal?this.legacyAsyncSigning?{asyncSigning:i||void 0,withPT:t.withPT,timeoutMs:t.timeoutMs,signal:t.signal}:{async:i,withPT:t.withPT,timeoutMs:t.timeoutMs,signal:t.signal}:void 0,o=await c(t,n(t.method),this.walletMessageManager,this.internalEventEmitter,a);if((t.method===e.wallet_switchEthereumChain||t.method===e.wallet_addEthereumChain)&&o===null){this.emit(`chainChanged`,t.params?.[0]?.chainId);try{let e=await this.request({method:`eth_accounts`});e&&e.length>0&&(this.currentAccount=e[0],this.emit(`accountsChanged`,e),this.emit(`connect`,{chainId:t.params?.[0]?.chainId}))}catch(e){console.warn(`[EthereumProvider] Failed to get accounts after chain switch:`,e),this.currentAccount&&(this.emit(`accountsChanged`,[this.currentAccount]),this.emit(`connect`,{chainId:t.params?.[0]?.chainId}))}}return t.method===e.eth_requestAccounts&&Array.isArray(o)&&typeof o[0]==`string`&&(this.currentAccount=o[0],this.connected=!0,typeof window<`u`&&typeof localStorage<`u`&&localStorage.setItem(`${window.location.origin}-connected`,`waap`),this.emit(`accountsChanged`,o),this.emit(`connect`)),o}async login(e){let t=await this.loginWithNativeHandoff(e);if(y(t))throw Error(`[WaaP SDK] The wallet returned a native auth hand-off. Use loginWithNativeHandoff() from a native host.`);return t}async loginWithNativeHandoff(e){if(this.waapRestoreRetryAt=0,typeof window>`u`||typeof document>`u`)return null;let t=e&&!(`request`in e)?e:void 0,n=t?t.customProvider:e;if(await this.ensureInitialized(),!t?.force&&await this.restorePersistedWaaPSession())return this.getLoginMethod()??`waap`;let r=n||window.ethereum,i=r&&b(r)?`MetaMask`:`Browser Wallet`,a=await c({method:m.login,params:[i]},!0,this.walletMessageManager,this.internalEventEmitter);if(y(a))return a;let o=T(a);if(o===null)return null;switch(o){case`waap`:case`human`:localStorage.setItem(`${window.location.origin}-connected`,`waap`),this.setupWaaP();break;case`injected`:r&&(localStorage.setItem(`${window.location.origin}-connected`,`injected`),this.setupInjectedWallet(r));break;case`walletconnect`:{localStorage.setItem(`${window.location.origin}-connected`,`walletconnect`),this.walletConnectProvider||await this.initializeWalletConnect(),g.isConnected()||(await this.walletConnectProvider.open({view:`Connect`}),await g.listenToAccountChangeEvent());let e=g.getWalletProvider();this.setupWalletConnect(e);break}}return o}async logout(){await this.ensureInitialized(),this.cleanupInvalidLoginState(),this.waapRestoreRetryAt=0,this.lastKnownConversion=`pending`,this.currentAccount=null,this.connected=!1,this.emit(`accountsChanged`,[]),this.emit(`disconnect`);try{this.walletConnectProvider&&await this.walletConnectProvider.disconnect()}catch(e){console.error(`Error disconnecting from WalletConnect:`,e)}return c({method:m.logout},!1,this.walletMessageManager,this.internalEventEmitter)}destroy(){if(this.walletMessageManager.dispose(),this.internalEventEmitter.removeAllListeners(),this.uiMessageManager.removeAllListeners(),this.removeAllListeners(),this.connected=!1,this.walletConnectProvider&&=(this.walletConnectProvider.disconnect().catch(()=>void 0),null),typeof window<`u`){let e=window;(e.silk===this||e.silk?.walletMessageManager===this.walletMessageManager)&&delete e.silk,(e.waap===this||e.waap?.walletMessageManager===this.walletMessageManager)&&delete e.waap}t()}cleanupInvalidLoginState(){try{localStorage.removeItem(`${window.location.origin}-connected`)}catch(e){console.warn(`Could not clean up login state:`,e)}}setupWaaP(){if(!this.exposeOnWindow)return;let e={...this.persistedMethods,isWaaP:!0,on:this.on.bind(this),removeListener:this.removeListener.bind(this),request:this.request.bind(this)};window.silk=e,window.waap=e}setupInjectedWallet(e){if(!this.exposeOnWindow)return;let t={...this.persistedMethods,...e,isSilk:!0,connected:e.connected??!1,on:e.on?.bind(e)??(()=>{}),removeListener:e.removeListener?.bind(e)??(()=>{}),request:e.request.bind(e)};window.silk=t,window.waap=t}setupWalletConnect(e){if(!this.exposeOnWindow)return;let t={...this.persistedMethods,...e,isSilk:!0,connected:!0,on:e.on?.bind(e)??(()=>{}),removeListener:e.removeListener?.bind(e)??(()=>{}),request:e.request.bind(e)};window.silk=t,window.waap=t}setupAutoConnectInjected(e){if(!this.exposeOnWindow)return;let t={...this.persistedMethods,...e,isSilk:!1,connected:e.isConnected?.()??!1,on:e.on?.bind(e)??(()=>{}),removeListener:e.removeListener?.bind(e)??(()=>{}),request:e.request.bind(e)};window.silk=t,window.waap=t}setupAutoConnectWalletConnect(e){if(!this.exposeOnWindow)return;let t={...this.persistedMethods,...e,isSilk:!1,connected:!0,on:e.on?.bind(e)??(()=>{}),removeListener:e.removeListener?.bind(e)??(()=>{}),request:e.request.bind(e)};window.silk=t,window.waap=t}async attemptAutoConnect(e){if(e!==`eth_requestAccounts`&&e!==`eth_accounts`)return null;let t=this.getLoginMethod();if(t===`waap`||t===`human`||t===null&&e===`eth_accounts`&&Date.now()>=this.waapRestoreRetryAt){let e=await this.restorePersistedWaaPSession();if(e)return e;t===null&&(this.waapRestoreRetryAt=Date.now()+5e3)}if(t===`injected`&&window.ethereum)try{return this.setupAutoConnectInjected(window.ethereum),window.ethereum.request({method:`eth_requestAccounts`})}catch(e){return console.warn(`Injected wallet auto-connect failed:`,e),this.cleanupInvalidLoginState(),null}else if(t===`walletconnect`)try{if(this.walletConnectProvider||=await g.getInstance(),await g.waitForReadyAndCheckConnection()){let e=g.getWalletProvider();return this.setupAutoConnectWalletConnect(e),e.request({method:`eth_requestAccounts`})}else return this.cleanupInvalidLoginState(),null}catch(e){return console.warn(`WalletConnect auto-connect failed:`,e),this.cleanupInvalidLoginState(),null}return null}restorePersistedWaaPSession(){return this.sessionProbe??=this.probeWaaPSession().finally(()=>{this.sessionProbe=null}),this.sessionProbe}async probeWaaPSession(){try{if(await this.ensureInitialized(),!(await this.getCanonicalAccountStatus()).authenticated)return this.cleanupInvalidLoginState(),null;let e=await c({method:m.auto_conn,params:[window.location.origin]},!1,this.walletMessageManager,this.internalEventEmitter);if(Array.isArray(e)&&e.length>0)return this.currentAccount=e[0],this.connected=!0,localStorage.setItem(`${window.location.origin}-connected`,`waap`),this.setupWaaP(),e}catch(e){console.warn(`WaaP session probe failed:`,e)}return this.cleanupInvalidLoginState(),null}getLoginMethod(){if(typeof window>`u`||typeof localStorage>`u`)return null;try{let e=localStorage.getItem(`${window.location.origin}-connected`);if(!e)return null;if(![`waap`,`human`,`injected`,`walletconnect`].includes(e))return this.cleanupInvalidLoginState(),null;switch(e){case`injected`:return window.ethereum?`injected`:(this.cleanupInvalidLoginState(),null);case`walletconnect`:try{return g.isConnected()?`walletconnect`:(this.cleanupInvalidLoginState(),null)}catch{return this.cleanupInvalidLoginState(),null}case`waap`:return`waap`;case`human`:return`human`;default:return this.cleanupInvalidLoginState(),null}}catch(e){return console.warn(`Error checking login method:`,e),this.cleanupInvalidLoginState(),null}}async toggleDarkMode(){this.config.styles.darkMode=!this.config.styles.darkMode,await this.ensureInitialized();try{await c({method:m.set_custom_config,params:[this.config]},!1,this.walletMessageManager,this.internalEventEmitter)}catch(e){console.error(`Error setting custom config in Silk iframe:`,e)}}async safe(){await this.ensureInitialized(),await c({method:m.safe},!0,this.walletMessageManager,this.internalEventEmitter)}async orcid(){await this.ensureInitialized(),await c({method:m.orcid},!0,this.walletMessageManager,this.internalEventEmitter)}async portal(e,t,n){await this.ensureInitialized();let r;switch(t){case`get`:r=e===`gastank`?m.gastank_get_settings:m.customization_get;break;case`update`:r=e===`gastank`?m.gastank_update_settings:m.customization_update;break;case`topup`:r=m.gastank_topup;break;case`init`:r=m.project_init;break}let i=t!==`get`&&e!==`customization`;return c({method:r,params:[n,window.location.origin]},i,this.walletMessageManager,this.internalEventEmitter)}async requestEmail(){return await this.ensureInitialized(),c({method:m.silk_requestEmail},!0,this.walletMessageManager,this.internalEventEmitter)}async requestPermissionToken(e){await this.ensureInitialized();let t={...e,walletMode:this.accountMode};return c({method:m.waap_requestPermissionToken,params:[t]},!0,this.walletMessageManager,this.internalEventEmitter)}async getPermissionTokenStatus(e){return await this.ensureInitialized(),await c({method:m.waap_getPermissionTokenStatus,params:[e]},!1,this.walletMessageManager,this.internalEventEmitter)}async clearPermissionToken(e){return await this.ensureInitialized(),await c({method:m.waap_clearPermissionToken,params:[e]},!1,this.walletMessageManager,this.internalEventEmitter)}async requestSBT(e){return await this.ensureInitialized(),c({method:m.silk_requestSbt,params:[e]},!0,this.walletMessageManager,this.internalEventEmitter)}async getLinkedAddresses(){return await this.walletMessageManager.pingIframe(),(await c({method:m.waap_getLinkedAddresses,params:[]},!1,this.walletMessageManager,this.internalEventEmitter,D)).addresses}async linkAddress(e){if(typeof window>`u`)throw Error(`linkAddress requires a browser environment`);this.walletConnectProvider||await this.initializeWalletConnect(),g.isConnected()||(await this.walletConnectProvider.open({view:`Connect`}),await g.listenToAccountChangeEvent());let t=g.getWalletProvider();if(!t)throw Error(`No wallet provider available after connection`);let n=(await t.request({method:`eth_accounts`}))[0];if(!n||n.toLowerCase()!==e.toLowerCase())throw Error(`Connected wallet account ${n??`(none)`} does not match requested address ${e}`);await this.walletMessageManager.pingIframe();let r=await c({method:m.waap_getLinkAddressNonce,params:[]},!1,this.walletMessageManager,this.internalEventEmitter,D),i=O({domain:window.location.host,address:e,uri:window.location.origin,nonce:r.nonce,issuedAt:new Date().toISOString()}),a=await t.request({method:`personal_sign`,params:[i,e]});return(await c({method:m.waap_linkAddress,params:[{message:i,signature:a}]},!1,this.walletMessageManager,this.internalEventEmitter,D)).addresses}async unlinkAddress(e){return await this.walletMessageManager.pingIframe(),(await c({method:m.waap_unlinkAddress,params:[{address:e}]},!1,this.walletMessageManager,this.internalEventEmitter,D)).addresses}};const D={timeoutMs:10*6e4};function O(e){let t=v(e.address);return`${`${e.domain} wants you to sign in with your Ethereum account:\n${t}`}\n\nLink this wallet to your Human Wallet account.\n\n${[`URI: ${e.uri}`,`Version: 1`,`Chain ID: 1`,`Nonce: ${e.nonce}`,`Issued At: ${e.issuedAt}`].join(`
1
+ import{C as e,_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,r as d,t as f,v as p,w as m,x as h}from"./UIMessageManager-BSJdvCEF.mjs";import{t as g}from"./WalletConnect-DXiTxC-F.mjs";import{EventEmitter as _}from"events";import{getAddress as v}from"ethers";const y=e=>typeof e==`object`&&!!e&&e.isComplete===!1&&typeof e.authUrl==`string`;function b(e){return!(!e?.isMetaMask||e.isApexWallet||e.isAvalanche||e.isBitKeep||e.isBlockWallet||e.isMathWallet||e.isOkxWallet||e.isOKExWallet||e.isOneInchIOSWallet||e.isOneInchAndroidWallet||e.isOpera||e.isPortal||e.isRabby||e.isDefiant||e.isTokenPocket||e.isTokenary||e.isZerion)}function x(e){try{if(!e||!Array.isArray(e))return!1;let t=JSON.parse(typeof e[1]==`string`?e[1]:JSON.stringify(e[1]));return t.primaryType===`SafeTx`&&t.domain?.verifyingContract!==void 0&&t.message&&`to`in t.message&&`value`in t.message&&`safeTxGas`in t.message&&`baseGas`in t.message&&`gasPrice`in t.message&&`nonce`in t.message}catch{return!1}}const S={styles:{darkMode:!1}},C=[`waap`,`human`,`injected`,`walletconnect`],w=[e.eth_sendTransaction,e.eth_signTransaction,e.eth_signTypedData_v4,e.personal_sign];function T(e){if(e==null)return null;if(typeof e==`string`){if(C.includes(e))return e;throw Error(`[EthereumProvider] Unexpected login method: "${e}". Expected one of: ${C.join(`, `)}`)}if(typeof e==`object`&&`loginMethod`in e&&typeof e.loginMethod==`string`){let t=e.loginMethod;if(console.warn(`[EthereumProvider] Received object login response. Normalizing "${t}" to string. This is unexpected for the web SDK.`),C.includes(t))return t;throw Error(`[EthereumProvider] Unknown loginMethod in object: "${t}". Expected one of: ${C.join(`, `)}`)}throw Error(`[EthereumProvider] Unexpected login response: ${JSON.stringify(e)} (type: ${typeof e})`)}var E=class extends _{setExposeOnWindow(e){this.exposeOnWindow=e}constructor(e,t,n,r,a,o=!1,s=!1,c,l=[`evm`]){super(),this.lastKnownConversion=`pending`,this.isSilk=!0,this.isWaaP=!0,this.connected=!1,this.exposeOnWindow=!0,this.currentAccount=null,this.accountMode=`tap`,this.walletConnectProvider=null,this.asyncTxs=!1,this.legacyAsyncSigning=!1,this.internalEventEmitter=new _,this.iframeMounted=!0,this.initializerPromise=null,this.sessionProbe=null,this.initializedIframeWindow=null,this.waapRestoreRetryAt=0,this.asyncTxs=o,this.legacyAsyncSigning=s,this.ensureIframe=c,this.iframeMounted=!c,this.referralCode=t,this.project=r,this.customConfig=n,this.initializerChains=l,this.uiMessageManager=new f,this.walletMessageManager=new i(e,a),this.config={...S,...n||{}},this.persistedMethods={login:this.login.bind(this),logout:this.logout.bind(this),getLoginMethod:this.getLoginMethod.bind(this),walletMessageManager:this.walletMessageManager,internalEventEmitter:this.internalEventEmitter,uiMessageManager:this.uiMessageManager,portal:this.portal.bind(this),requestEmail:this.requestEmail.bind(this),requestSBT:this.requestSBT.bind(this),requestPermissionToken:this.requestPermissionToken.bind(this),getLinkedAddresses:this.getLinkedAddresses.bind(this),linkAddress:this.linkAddress.bind(this),unlinkAddress:this.unlinkAddress.bind(this),orcid:this.orcid.bind(this),enable:this.enable.bind(this),isConnected:this.isConnected.bind(this),toggleDarkMode:this.toggleDarkMode.bind(this),destroy:this.destroy.bind(this),silkRequest:this.request.bind(this),waaPRequest:this.request.bind(this)},this.walletMessageManager.addListener({onReceiveConnectNotif:()=>{this.connected=!0,this.emit(`connect`)},handleResponse:e=>this.internalEventEmitter.emit(e.id,e),handleRequest:e=>{e.method===m.show_modal?this.uiMessageManager.emit(`show_modal`):e.method===m.hide_modal&&this.uiMessageManager.emit(`hide_modal`)},onAccountChanged:e=>{this.currentAccount!==e&&(this.currentAccount=e,this.emit(`accountsChanged`,e?[e]:[]))},onAsyncTxNotification:e=>{this.emit(e.type,e.payload)},onSquidLifecycleNotification:e=>{this.emit(e.type,e.payload)}})}async initializeWalletConnect(){try{this.walletConnectProvider=await g.getInstance()}catch(e){console.error(`Failed to initialize WalletConnect provider:`,e),this.walletConnectProvider=null}}async initializeIframeContext(){let e=this.walletMessageManager.getIframeWindow();if(!e)throw Error(`WaaP iframe is not mounted`);if(this.initializedIframeWindow===e&&this.initializerPromise)return this.initializerPromise;this.initializedIframeWindow=e,this.initializerPromise=u(e,async()=>{await this.walletMessageManager.pingIframe(),await c({method:m.set_signing_mode,params:[a(this.accountMode,{referralCode:this.referralCode,project:this.project,config:this.customConfig,chains:this.initializerChains})]},!1,this.walletMessageManager,this.internalEventEmitter)});try{await this.initializerPromise}catch(e){throw this.initializerPromise=null,this.initializedIframeWindow=null,e}}async reassertIframeAccountMode(){this.ensureIframeMounted(),await this.walletMessageManager.pingIframe(),await c({method:m.set_signing_mode,params:[a(this.accountMode,{referralCode:this.referralCode,project:this.project,config:this.customConfig,chains:this.initializerChains})]},!1,this.walletMessageManager,this.internalEventEmitter)}ensureIframeMounted(){if(this.iframeMounted||!this.ensureIframe)return;let e=this.ensureIframe();e&&(this.iframeMounted=!0,this.walletMessageManager.setIframeWindow(e))}async ensureInitialized(){this.ensureIframeMounted(),await this.initializeIframeContext()}async preload(){await this.ensureInitialized()}async enable(){return this.request({method:`eth_requestAccounts`})}isConnected(){return this.connected}getAccountStatus(){let e=this.getLoginMethod();return{authenticated:e!==null,loginMethod:e,activeMode:e?this.accountMode:null,mode:this.accountMode,conversion:e?this.lastKnownConversion:`not_required`,tap:null,squid:null,accounts:this.currentAccount?{evm:this.currentAccount}:{}}}get session(){return{login:e=>this.login(e),logout:async()=>{await this.logout()},getLoginMethod:()=>this.getLoginMethod(),getAccountStatus:()=>this.getCanonicalAccountStatus()}}async getCanonicalAccountStatus(){await this.ensureInitialized();let e=await c({method:m.waap_getAccountStatus,params:[]},!1,this.walletMessageManager,this.internalEventEmitter);return e?.conversion&&(this.lastKnownConversion=e.conversion),e}setAccountMode(e){this.accountMode=e,this.initializerPromise=null,this.initializedIframeWindow=null}async request(t){if(!Object.keys(e).includes(t.method))return Promise.reject({error:`Not implemented (${t.method})`});let r=await this.attemptAutoConnect(t.method);if(r!==null)return r;if(w.includes(t.method)&&!(this.getLoginMethod()!==null||await this.restorePersistedWaaPSession()!==null))return Promise.reject(new h(`not_authenticated`,`Not authenticated: call login() before signing.`,{operation:{chain:`evm`,method:t.method}}));if(x(t.params)&&t.method!==e.eth_signTypedData_v4)return Promise.reject({error:`Safe transactions must be signed using eth_signTypedData_v4`});await this.ensureInitialized();let i=(t.method===e.eth_sendTransaction||t.method===e.eth_signTransaction||t.method===e.eth_signTypedData_v4||t.method===e.personal_sign)&&this.asyncTxs||t.async,a=i||t.withPT||t.timeoutMs!==void 0||t.signal?this.legacyAsyncSigning?{asyncSigning:i||void 0,withPT:t.withPT,timeoutMs:t.timeoutMs,signal:t.signal}:{async:i,withPT:t.withPT,timeoutMs:t.timeoutMs,signal:t.signal}:void 0,o=await c(t,n(t.method),this.walletMessageManager,this.internalEventEmitter,a);if((t.method===e.wallet_switchEthereumChain||t.method===e.wallet_addEthereumChain)&&o===null){this.emit(`chainChanged`,t.params?.[0]?.chainId);try{let e=await this.request({method:`eth_accounts`});e&&e.length>0&&(this.currentAccount=e[0],this.emit(`accountsChanged`,e),this.emit(`connect`,{chainId:t.params?.[0]?.chainId}))}catch(e){console.warn(`[EthereumProvider] Failed to get accounts after chain switch:`,e),this.currentAccount&&(this.emit(`accountsChanged`,[this.currentAccount]),this.emit(`connect`,{chainId:t.params?.[0]?.chainId}))}}return t.method===e.eth_requestAccounts&&Array.isArray(o)&&typeof o[0]==`string`&&(this.currentAccount=o[0],this.connected=!0,typeof window<`u`&&typeof localStorage<`u`&&localStorage.setItem(`${window.location.origin}-connected`,`waap`),this.emit(`accountsChanged`,o),this.emit(`connect`)),o}async login(e){let t=await this.loginWithNativeHandoff(e);if(y(t))throw Error(`[WaaP SDK] The wallet returned a native auth hand-off. Use loginWithNativeHandoff() from a native host.`);return t}async loginWithNativeHandoff(e){if(this.waapRestoreRetryAt=0,typeof window>`u`||typeof document>`u`)return null;let t=e&&!(`request`in e)?e:void 0,n=t?t.customProvider:e;if(await this.ensureInitialized(),!t?.force&&await this.restorePersistedWaaPSession())return this.getLoginMethod()??`waap`;let r=n||window.ethereum,i=r&&b(r)?`MetaMask`:`Browser Wallet`,a=await c({method:m.login,params:[i]},!0,this.walletMessageManager,this.internalEventEmitter);if(y(a))return a;let o=T(a);if(o===null)return null;switch(o){case`waap`:case`human`:localStorage.setItem(`${window.location.origin}-connected`,`waap`),this.setupWaaP();break;case`injected`:r&&(localStorage.setItem(`${window.location.origin}-connected`,`injected`),this.setupInjectedWallet(r));break;case`walletconnect`:{localStorage.setItem(`${window.location.origin}-connected`,`walletconnect`),this.walletConnectProvider||await this.initializeWalletConnect(),g.isConnected()||(await this.walletConnectProvider.open({view:`Connect`}),await g.listenToAccountChangeEvent());let e=g.getWalletProvider();this.setupWalletConnect(e);break}}return o}async logout(){await this.ensureInitialized(),this.cleanupInvalidLoginState(),this.waapRestoreRetryAt=0,this.lastKnownConversion=`pending`,this.currentAccount=null,this.connected=!1,this.emit(`accountsChanged`,[]),this.emit(`disconnect`);try{this.walletConnectProvider&&await this.walletConnectProvider.disconnect()}catch(e){console.error(`Error disconnecting from WalletConnect:`,e)}return c({method:m.logout},!1,this.walletMessageManager,this.internalEventEmitter)}destroy(){if(this.walletMessageManager.dispose(),this.internalEventEmitter.removeAllListeners(),this.uiMessageManager.removeAllListeners(),this.removeAllListeners(),this.connected=!1,this.walletConnectProvider&&=(this.walletConnectProvider.disconnect().catch(()=>void 0),null),typeof window<`u`){let e=window;(e.silk===this||e.silk?.walletMessageManager===this.walletMessageManager)&&delete e.silk,(e.waap===this||e.waap?.walletMessageManager===this.walletMessageManager)&&delete e.waap}t()}cleanupInvalidLoginState(){try{localStorage.removeItem(`${window.location.origin}-connected`)}catch(e){console.warn(`Could not clean up login state:`,e)}}setupWaaP(){if(!this.exposeOnWindow)return;let e={...this.persistedMethods,isWaaP:!0,on:this.on.bind(this),removeListener:this.removeListener.bind(this),request:this.request.bind(this)};window.silk=e,window.waap=e}setupInjectedWallet(e){if(!this.exposeOnWindow)return;let t={...this.persistedMethods,...e,isSilk:!0,connected:e.connected??!1,on:e.on?.bind(e)??(()=>{}),removeListener:e.removeListener?.bind(e)??(()=>{}),request:e.request.bind(e)};window.silk=t,window.waap=t}setupWalletConnect(e){if(!this.exposeOnWindow)return;let t={...this.persistedMethods,...e,isSilk:!0,connected:!0,on:e.on?.bind(e)??(()=>{}),removeListener:e.removeListener?.bind(e)??(()=>{}),request:e.request.bind(e)};window.silk=t,window.waap=t}setupAutoConnectInjected(e){if(!this.exposeOnWindow)return;let t={...this.persistedMethods,...e,isSilk:!1,connected:e.isConnected?.()??!1,on:e.on?.bind(e)??(()=>{}),removeListener:e.removeListener?.bind(e)??(()=>{}),request:e.request.bind(e)};window.silk=t,window.waap=t}setupAutoConnectWalletConnect(e){if(!this.exposeOnWindow)return;let t={...this.persistedMethods,...e,isSilk:!1,connected:!0,on:e.on?.bind(e)??(()=>{}),removeListener:e.removeListener?.bind(e)??(()=>{}),request:e.request.bind(e)};window.silk=t,window.waap=t}async attemptAutoConnect(e){if(e!==`eth_requestAccounts`&&e!==`eth_accounts`)return null;let t=this.getLoginMethod();if(t===`waap`||t===`human`||t===null&&e===`eth_accounts`&&Date.now()>=this.waapRestoreRetryAt){let e=await this.restorePersistedWaaPSession();if(e)return e;t===null&&(this.waapRestoreRetryAt=Date.now()+5e3)}if(t===`injected`&&window.ethereum)try{return this.setupAutoConnectInjected(window.ethereum),window.ethereum.request({method:`eth_requestAccounts`})}catch(e){return console.warn(`Injected wallet auto-connect failed:`,e),this.cleanupInvalidLoginState(),null}else if(t===`walletconnect`)try{if(this.walletConnectProvider||=await g.getInstance(),await g.waitForReadyAndCheckConnection()){let e=g.getWalletProvider();return this.setupAutoConnectWalletConnect(e),e.request({method:`eth_requestAccounts`})}else return this.cleanupInvalidLoginState(),null}catch(e){return console.warn(`WalletConnect auto-connect failed:`,e),this.cleanupInvalidLoginState(),null}return null}restorePersistedWaaPSession(){return this.sessionProbe??=this.probeWaaPSession().finally(()=>{this.sessionProbe=null}),this.sessionProbe}async probeWaaPSession(){try{if(await this.ensureInitialized(),!(await this.getCanonicalAccountStatus()).authenticated)return this.cleanupInvalidLoginState(),null;let e=await c({method:m.auto_conn,params:[window.location.origin]},!1,this.walletMessageManager,this.internalEventEmitter);if(Array.isArray(e)&&e.length>0)return this.currentAccount=e[0],this.connected=!0,localStorage.setItem(`${window.location.origin}-connected`,`waap`),this.setupWaaP(),e}catch(e){console.warn(`WaaP session probe failed:`,e)}return this.cleanupInvalidLoginState(),null}getLoginMethod(){if(typeof window>`u`||typeof localStorage>`u`)return null;try{let e=localStorage.getItem(`${window.location.origin}-connected`);if(!e)return null;if(![`waap`,`human`,`injected`,`walletconnect`].includes(e))return this.cleanupInvalidLoginState(),null;switch(e){case`injected`:return window.ethereum?`injected`:(this.cleanupInvalidLoginState(),null);case`walletconnect`:try{return g.isConnected()?`walletconnect`:(this.cleanupInvalidLoginState(),null)}catch{return this.cleanupInvalidLoginState(),null}case`waap`:return`waap`;case`human`:return`human`;default:return this.cleanupInvalidLoginState(),null}}catch(e){return console.warn(`Error checking login method:`,e),this.cleanupInvalidLoginState(),null}}async toggleDarkMode(){this.config.styles.darkMode=!this.config.styles.darkMode,await this.ensureInitialized();try{await c({method:m.set_custom_config,params:[this.config]},!1,this.walletMessageManager,this.internalEventEmitter)}catch(e){console.error(`Error setting custom config in Silk iframe:`,e)}}async safe(){await this.ensureInitialized(),await c({method:m.safe},!0,this.walletMessageManager,this.internalEventEmitter)}async orcid(){await this.ensureInitialized(),await c({method:m.orcid},!0,this.walletMessageManager,this.internalEventEmitter)}async portal(e,t,n){await this.ensureInitialized();let r;switch(t){case`get`:r=e===`gastank`?m.gastank_get_settings:m.customization_get;break;case`update`:r=e===`gastank`?m.gastank_update_settings:m.customization_update;break;case`topup`:r=m.gastank_topup;break;case`init`:r=m.project_init;break}let i=t!==`get`&&e!==`customization`;return c({method:r,params:[n,window.location.origin]},i,this.walletMessageManager,this.internalEventEmitter)}async requestEmail(){return await this.ensureInitialized(),c({method:m.silk_requestEmail},!0,this.walletMessageManager,this.internalEventEmitter)}async requestPermissionToken(e){await this.ensureInitialized();let t={...e,walletMode:this.accountMode};return c({method:m.waap_requestPermissionToken,params:[t]},!0,this.walletMessageManager,this.internalEventEmitter)}async getPermissionTokenStatus(e){return await this.ensureInitialized(),await c({method:m.waap_getPermissionTokenStatus,params:[e]},!1,this.walletMessageManager,this.internalEventEmitter)}async clearPermissionToken(e){return await this.ensureInitialized(),await c({method:m.waap_clearPermissionToken,params:[e]},!1,this.walletMessageManager,this.internalEventEmitter)}async requestSBT(e){return await this.ensureInitialized(),c({method:m.silk_requestSbt,params:[e]},!0,this.walletMessageManager,this.internalEventEmitter)}async getLinkedAddresses(){return await this.walletMessageManager.pingIframe(),(await c({method:m.waap_getLinkedAddresses,params:[]},!1,this.walletMessageManager,this.internalEventEmitter,D)).addresses}async linkAddress(e){if(typeof window>`u`)throw Error(`linkAddress requires a browser environment`);this.walletConnectProvider||await this.initializeWalletConnect(),g.isConnected()||(await this.walletConnectProvider.open({view:`Connect`}),await g.listenToAccountChangeEvent());let t=g.getWalletProvider();if(!t)throw Error(`No wallet provider available after connection`);let n=(await t.request({method:`eth_accounts`}))[0];if(!n||n.toLowerCase()!==e.toLowerCase())throw Error(`Connected wallet account ${n??`(none)`} does not match requested address ${e}`);await this.walletMessageManager.pingIframe();let r=await c({method:m.waap_getLinkAddressNonce,params:[]},!1,this.walletMessageManager,this.internalEventEmitter,D),i=O({domain:window.location.host,address:e,uri:window.location.origin,nonce:r.nonce,issuedAt:new Date().toISOString()}),a=await t.request({method:`personal_sign`,params:[i,e]});return(await c({method:m.waap_linkAddress,params:[{message:i,signature:a}]},!1,this.walletMessageManager,this.internalEventEmitter,D)).addresses}async unlinkAddress(e){return await this.walletMessageManager.pingIframe(),(await c({method:m.waap_unlinkAddress,params:[{address:e}]},!1,this.walletMessageManager,this.internalEventEmitter,D)).addresses}};const D={timeoutMs:10*6e4};function O(e){let t=v(e.address);return`${`${e.domain} wants you to sign in with your Ethereum account:\n${t}`}\n\nLink this wallet to your Human Wallet account.\n\n${[`URI: ${e.uri}`,`Version: 1`,`Chain ID: 1`,`Nonce: ${e.nonce}`,`Issued At: ${e.issuedAt}`].join(`
2
2
  `)}`}const k=(e,t,n=!0,i=[`evm`],a=!0)=>{let{referralCode:c,config:u,project:f,asyncTxs:m,asyncSigning:h,deferIframe:_}=e,v=p(e),y=!!h&&!m;e.walletConnectProjectId&&g.setProjectId(e.walletConnectProjectId),h&&!m&&console.warn("[WaaP SDK] `asyncSigning` is deprecated. Use `asyncTxs` instead.");let b=typeof window>`u`||typeof document>`u`,x=()=>typeof window>`u`||typeof document>`u`?null:(o(e),s(t).contentWindow),S=_===!1&&!b,C=_===void 0&&!b,w=S?x():null;if(S&&!w)throw Error(`WaaP iframe does not exist on page`);let T=new E(w,c,u||{},f||{},v,m||h||!1,y,S?void 0:x,i);if(T.setAccountMode(t),T.setExposeOnWindow(a),!b&&n&&S&&T.initializeIframeContext().catch(()=>void 0),T.uiMessageManager.on(`show_modal`,()=>{l()}),T.uiMessageManager.on(`hide_modal`,()=>{r()}),!b&&a&&(window.silk=T,window.waap=T),n&&C){let e=d(T),t=T.destroy.bind(T);T.destroy=()=>{e(),t()}}return T},A=(e={})=>k(e,`tap`);export{S as i,k as n,E as r,A as t};
@@ -1,2 +1,2 @@
1
- const e=require("./UIMessageManager-CPw6PggC.js"),t=require("./WalletConnect-B21f4Vvh.js");let n=require("events"),r=require("ethers");const i=e=>typeof e==`object`&&!!e&&e.isComplete===!1&&typeof e.authUrl==`string`;function a(e){return!(!e?.isMetaMask||e.isApexWallet||e.isAvalanche||e.isBitKeep||e.isBlockWallet||e.isMathWallet||e.isOkxWallet||e.isOKExWallet||e.isOneInchIOSWallet||e.isOneInchAndroidWallet||e.isOpera||e.isPortal||e.isRabby||e.isDefiant||e.isTokenPocket||e.isTokenary||e.isZerion)}function o(e){try{if(!e||!Array.isArray(e))return!1;let t=JSON.parse(typeof e[1]==`string`?e[1]:JSON.stringify(e[1]));return t.primaryType===`SafeTx`&&t.domain?.verifyingContract!==void 0&&t.message&&`to`in t.message&&`value`in t.message&&`safeTxGas`in t.message&&`baseGas`in t.message&&`gasPrice`in t.message&&`nonce`in t.message}catch{return!1}}const s={styles:{darkMode:!1}},c=[`waap`,`human`,`injected`,`walletconnect`],l=[e.C.eth_sendTransaction,e.C.eth_signTransaction,e.C.eth_signTypedData_v4,e.C.personal_sign];function u(e){if(e==null)return null;if(typeof e==`string`){if(c.includes(e))return e;throw Error(`[EthereumProvider] Unexpected login method: "${e}". Expected one of: ${c.join(`, `)}`)}if(typeof e==`object`&&`loginMethod`in e&&typeof e.loginMethod==`string`){let t=e.loginMethod;if(console.warn(`[EthereumProvider] Received object login response. Normalizing "${t}" to string. This is unexpected for the web SDK.`),c.includes(t))return t;throw Error(`[EthereumProvider] Unknown loginMethod in object: "${t}". Expected one of: ${c.join(`, `)}`)}throw Error(`[EthereumProvider] Unexpected login response: ${JSON.stringify(e)} (type: ${typeof e})`)}var d=class extends n.EventEmitter{setExposeOnWindow(e){this.exposeOnWindow=e}constructor(t,r,i,a,o,c=!1,l=!1,u,d=[`evm`]){super(),this.lastKnownConversion=`pending`,this.isSilk=!0,this.isWaaP=!0,this.connected=!1,this.exposeOnWindow=!0,this.currentAccount=null,this.accountMode=`tap`,this.walletConnectProvider=null,this.asyncTxs=!1,this.legacyAsyncSigning=!1,this.internalEventEmitter=new n.EventEmitter,this.iframeMounted=!0,this.initializerPromise=null,this.sessionProbe=null,this.initializedIframeWindow=null,this.waapRestoreRetryAt=0,this.asyncTxs=c,this.legacyAsyncSigning=l,this.ensureIframe=u,this.iframeMounted=!u,this.referralCode=r,this.project=a,this.customConfig=i,this.initializerChains=d,this.uiMessageManager=new e.t,this.walletMessageManager=new e.d(t,o),this.config={...s,...i||{}},this.persistedMethods={login:this.login.bind(this),logout:this.logout.bind(this),getLoginMethod:this.getLoginMethod.bind(this),walletMessageManager:this.walletMessageManager,internalEventEmitter:this.internalEventEmitter,uiMessageManager:this.uiMessageManager,portal:this.portal.bind(this),requestEmail:this.requestEmail.bind(this),requestSBT:this.requestSBT.bind(this),requestPermissionToken:this.requestPermissionToken.bind(this),getLinkedAddresses:this.getLinkedAddresses.bind(this),linkAddress:this.linkAddress.bind(this),unlinkAddress:this.unlinkAddress.bind(this),orcid:this.orcid.bind(this),enable:this.enable.bind(this),isConnected:this.isConnected.bind(this),toggleDarkMode:this.toggleDarkMode.bind(this),destroy:this.destroy.bind(this),silkRequest:this.request.bind(this),waaPRequest:this.request.bind(this)},this.walletMessageManager.addListener({onReceiveConnectNotif:()=>{this.connected=!0,this.emit(`connect`)},handleResponse:e=>this.internalEventEmitter.emit(e.id,e),handleRequest:t=>{t.method===e.w.show_modal?this.uiMessageManager.emit(`show_modal`):t.method===e.w.hide_modal&&this.uiMessageManager.emit(`hide_modal`)},onAccountChanged:e=>{this.currentAccount!==e&&(this.currentAccount=e,this.emit(`accountsChanged`,e?[e]:[]))},onAsyncTxNotification:e=>{this.emit(e.type,e.payload)},onSquidLifecycleNotification:e=>{this.emit(e.type,e.payload)}})}async initializeWalletConnect(){try{this.walletConnectProvider=await t.t.getInstance()}catch(e){console.error(`Failed to initialize WalletConnect provider:`,e),this.walletConnectProvider=null}}async initializeIframeContext(){let t=this.walletMessageManager.getIframeWindow();if(!t)throw Error(`WaaP iframe is not mounted`);if(this.initializedIframeWindow===t&&this.initializerPromise)return this.initializerPromise;this.initializedIframeWindow=t,this.initializerPromise=e.m(t,async()=>{await this.walletMessageManager.pingIframe(),await e.i({method:e.w.set_signing_mode,params:[e.f(this.accountMode,{referralCode:this.referralCode,project:this.project,config:this.customConfig,chains:this.initializerChains})]},!1,this.walletMessageManager,this.internalEventEmitter)});try{await this.initializerPromise}catch(e){throw this.initializerPromise=null,this.initializedIframeWindow=null,e}}async reassertIframeAccountMode(){this.ensureIframeMounted(),await this.walletMessageManager.pingIframe(),await e.i({method:e.w.set_signing_mode,params:[e.f(this.accountMode,{referralCode:this.referralCode,project:this.project,config:this.customConfig,chains:this.initializerChains})]},!1,this.walletMessageManager,this.internalEventEmitter)}ensureIframeMounted(){if(this.iframeMounted||!this.ensureIframe)return;let e=this.ensureIframe();e&&(this.iframeMounted=!0,this.walletMessageManager.setIframeWindow(e))}async ensureInitialized(){this.ensureIframeMounted(),await this.initializeIframeContext()}async preload(){await this.ensureInitialized()}async enable(){return this.request({method:`eth_requestAccounts`})}isConnected(){return this.connected}getAccountStatus(){let e=this.getLoginMethod();return{authenticated:e!==null,loginMethod:e,activeMode:e?this.accountMode:null,mode:this.accountMode,conversion:e?this.lastKnownConversion:`not_required`,tap:null,squid:null,accounts:this.currentAccount?{evm:this.currentAccount}:{}}}get session(){return{login:e=>this.login(e),logout:async()=>{await this.logout()},getLoginMethod:()=>this.getLoginMethod(),getAccountStatus:()=>this.getCanonicalAccountStatus()}}async getCanonicalAccountStatus(){await this.ensureInitialized();let t=await e.i({method:e.w.waap_getAccountStatus,params:[]},!1,this.walletMessageManager,this.internalEventEmitter);return t?.conversion&&(this.lastKnownConversion=t.conversion),t}setAccountMode(e){this.accountMode=e,this.initializerPromise=null,this.initializedIframeWindow=null}async request(t){if(!Object.keys(e.C).includes(t.method))return Promise.reject({error:`Not implemented (${t.method})`});let n=await this.attemptAutoConnect(t.method);if(n!==null)return n;if(l.includes(t.method)&&!(this.getLoginMethod()!==null||await this.restorePersistedWaaPSession()!==null))return Promise.reject(new e.x(`not_authenticated`,`Not authenticated: call login() before signing.`,{operation:{chain:`evm`,method:t.method}}));if(o(t.params)&&t.method!==e.C.eth_signTypedData_v4)return Promise.reject({error:`Safe transactions must be signed using eth_signTypedData_v4`});await this.ensureInitialized();let r=(t.method===e.C.eth_sendTransaction||t.method===e.C.eth_signTransaction||t.method===e.C.eth_signTypedData_v4||t.method===e.C.personal_sign)&&this.asyncTxs||t.async,i=r||t.withPT||t.timeoutMs!==void 0||t.signal?this.legacyAsyncSigning?{asyncSigning:r||void 0,withPT:t.withPT,timeoutMs:t.timeoutMs,signal:t.signal}:{async:r,withPT:t.withPT,timeoutMs:t.timeoutMs,signal:t.signal}:void 0,a=await e.i(t,e.a(t.method),this.walletMessageManager,this.internalEventEmitter,i);if((t.method===e.C.wallet_switchEthereumChain||t.method===e.C.wallet_addEthereumChain)&&a===null){this.emit(`chainChanged`,t.params?.[0]?.chainId);try{let e=await this.request({method:`eth_accounts`});e&&e.length>0&&(this.currentAccount=e[0],this.emit(`accountsChanged`,e),this.emit(`connect`,{chainId:t.params?.[0]?.chainId}))}catch(e){console.warn(`[EthereumProvider] Failed to get accounts after chain switch:`,e),this.currentAccount&&(this.emit(`accountsChanged`,[this.currentAccount]),this.emit(`connect`,{chainId:t.params?.[0]?.chainId}))}}return t.method===e.C.eth_requestAccounts&&Array.isArray(a)&&typeof a[0]==`string`&&(this.currentAccount=a[0],this.connected=!0,typeof window<`u`&&typeof localStorage<`u`&&localStorage.setItem(`${window.location.origin}-connected`,`waap`),this.emit(`accountsChanged`,a),this.emit(`connect`)),a}async login(e){let t=await this.loginWithNativeHandoff(e);if(i(t))throw Error(`[WaaP SDK] The wallet returned a native auth hand-off. Use loginWithNativeHandoff() from a native host.`);return t}async loginWithNativeHandoff(n){if(this.waapRestoreRetryAt=0,typeof window>`u`||typeof document>`u`)return null;let r=n&&!(`request`in n)?n:void 0,o=r?r.customProvider:n;if(await this.ensureInitialized(),!r?.force&&await this.restorePersistedWaaPSession())return this.getLoginMethod()??`waap`;let s=o||window.ethereum,c=s&&a(s)?`MetaMask`:`Browser Wallet`,l=await e.i({method:e.w.login,params:[c]},!0,this.walletMessageManager,this.internalEventEmitter);if(i(l))return l;let d=u(l);if(d===null)return null;switch(d){case`waap`:case`human`:localStorage.setItem(`${window.location.origin}-connected`,`waap`),this.setupWaaP();break;case`injected`:s&&(localStorage.setItem(`${window.location.origin}-connected`,`injected`),this.setupInjectedWallet(s));break;case`walletconnect`:{localStorage.setItem(`${window.location.origin}-connected`,`walletconnect`),this.walletConnectProvider||await this.initializeWalletConnect(),t.t.isConnected()||(await this.walletConnectProvider.open({view:`Connect`}),await t.t.listenToAccountChangeEvent());let e=t.t.getWalletProvider();this.setupWalletConnect(e);break}}return d}async logout(){await this.ensureInitialized(),this.cleanupInvalidLoginState(),this.waapRestoreRetryAt=0,this.lastKnownConversion=`pending`,this.currentAccount=null,this.connected=!1,this.emit(`accountsChanged`,[]),this.emit(`disconnect`);try{this.walletConnectProvider&&await this.walletConnectProvider.disconnect()}catch(e){console.error(`Error disconnecting from WalletConnect:`,e)}return e.i({method:e.w.logout},!1,this.walletMessageManager,this.internalEventEmitter)}destroy(){if(this.walletMessageManager.dispose(),this.internalEventEmitter.removeAllListeners(),this.uiMessageManager.removeAllListeners(),this.removeAllListeners(),this.connected=!1,this.walletConnectProvider&&=(this.walletConnectProvider.disconnect().catch(()=>void 0),null),typeof window<`u`){let e=window;(e.silk===this||e.silk?.walletMessageManager===this.walletMessageManager)&&delete e.silk,(e.waap===this||e.waap?.walletMessageManager===this.walletMessageManager)&&delete e.waap}e._()}cleanupInvalidLoginState(){try{localStorage.removeItem(`${window.location.origin}-connected`)}catch(e){console.warn(`Could not clean up login state:`,e)}}setupWaaP(){if(!this.exposeOnWindow)return;let e={...this.persistedMethods,isWaaP:!0,on:this.on.bind(this),removeListener:this.removeListener.bind(this),request:this.request.bind(this)};window.silk=e,window.waap=e}setupInjectedWallet(e){if(!this.exposeOnWindow)return;let t={...this.persistedMethods,...e,isSilk:!0,connected:e.connected??!1,on:e.on?.bind(e)??(()=>{}),removeListener:e.removeListener?.bind(e)??(()=>{}),request:e.request.bind(e)};window.silk=t,window.waap=t}setupWalletConnect(e){if(!this.exposeOnWindow)return;let t={...this.persistedMethods,...e,isSilk:!0,connected:!0,on:e.on?.bind(e)??(()=>{}),removeListener:e.removeListener?.bind(e)??(()=>{}),request:e.request.bind(e)};window.silk=t,window.waap=t}setupAutoConnectInjected(e){if(!this.exposeOnWindow)return;let t={...this.persistedMethods,...e,isSilk:!1,connected:e.isConnected?.()??!1,on:e.on?.bind(e)??(()=>{}),removeListener:e.removeListener?.bind(e)??(()=>{}),request:e.request.bind(e)};window.silk=t,window.waap=t}setupAutoConnectWalletConnect(e){if(!this.exposeOnWindow)return;let t={...this.persistedMethods,...e,isSilk:!1,connected:!0,on:e.on?.bind(e)??(()=>{}),removeListener:e.removeListener?.bind(e)??(()=>{}),request:e.request.bind(e)};window.silk=t,window.waap=t}async attemptAutoConnect(e){if(e!==`eth_requestAccounts`&&e!==`eth_accounts`)return null;let n=this.getLoginMethod();if(n===`waap`||n===`human`||n===null&&e===`eth_accounts`&&Date.now()>=this.waapRestoreRetryAt){let e=await this.restorePersistedWaaPSession();if(e)return e;n===null&&(this.waapRestoreRetryAt=Date.now()+5e3)}if(n===`injected`&&window.ethereum)try{return this.setupAutoConnectInjected(window.ethereum),window.ethereum.request({method:`eth_requestAccounts`})}catch(e){return console.warn(`Injected wallet auto-connect failed:`,e),this.cleanupInvalidLoginState(),null}else if(n===`walletconnect`)try{if(this.walletConnectProvider||=await t.t.getInstance(),await t.t.waitForReadyAndCheckConnection()){let e=t.t.getWalletProvider();return this.setupAutoConnectWalletConnect(e),e.request({method:`eth_requestAccounts`})}else return this.cleanupInvalidLoginState(),null}catch(e){return console.warn(`WalletConnect auto-connect failed:`,e),this.cleanupInvalidLoginState(),null}return null}restorePersistedWaaPSession(){return this.sessionProbe??=this.probeWaaPSession().finally(()=>{this.sessionProbe=null}),this.sessionProbe}async probeWaaPSession(){try{if(await this.ensureInitialized(),!(await this.getCanonicalAccountStatus()).authenticated)return this.cleanupInvalidLoginState(),null;let t=await e.i({method:e.w.auto_conn,params:[window.location.origin]},!1,this.walletMessageManager,this.internalEventEmitter);if(Array.isArray(t)&&t.length>0)return this.currentAccount=t[0],this.connected=!0,localStorage.setItem(`${window.location.origin}-connected`,`waap`),this.setupWaaP(),t}catch(e){console.warn(`WaaP session probe failed:`,e)}return this.cleanupInvalidLoginState(),null}getLoginMethod(){if(typeof window>`u`||typeof localStorage>`u`)return null;try{let e=localStorage.getItem(`${window.location.origin}-connected`);if(!e)return null;if(![`waap`,`human`,`injected`,`walletconnect`].includes(e))return this.cleanupInvalidLoginState(),null;switch(e){case`injected`:return window.ethereum?`injected`:(this.cleanupInvalidLoginState(),null);case`walletconnect`:try{return t.t.isConnected()?`walletconnect`:(this.cleanupInvalidLoginState(),null)}catch{return this.cleanupInvalidLoginState(),null}case`waap`:return`waap`;case`human`:return`human`;default:return this.cleanupInvalidLoginState(),null}}catch(e){return console.warn(`Error checking login method:`,e),this.cleanupInvalidLoginState(),null}}async toggleDarkMode(){this.config.styles.darkMode=!this.config.styles.darkMode,await this.ensureInitialized();try{await e.i({method:e.w.set_custom_config,params:[this.config]},!1,this.walletMessageManager,this.internalEventEmitter)}catch(e){console.error(`Error setting custom config in Silk iframe:`,e)}}async safe(){await this.ensureInitialized(),await e.i({method:e.w.safe},!0,this.walletMessageManager,this.internalEventEmitter)}async orcid(){await this.ensureInitialized(),await e.i({method:e.w.orcid},!0,this.walletMessageManager,this.internalEventEmitter)}async portal(t,n,r){await this.ensureInitialized();let i;switch(n){case`get`:i=t===`gastank`?e.w.gastank_get_settings:e.w.customization_get;break;case`update`:i=t===`gastank`?e.w.gastank_update_settings:e.w.customization_update;break;case`topup`:i=e.w.gastank_topup;break;case`init`:i=e.w.project_init;break}let a=n!==`get`&&t!==`customization`;return e.i({method:i,params:[r,window.location.origin]},a,this.walletMessageManager,this.internalEventEmitter)}async requestEmail(){return await this.ensureInitialized(),e.i({method:e.w.silk_requestEmail},!0,this.walletMessageManager,this.internalEventEmitter)}async requestPermissionToken(t){await this.ensureInitialized();let n={...t,walletMode:this.accountMode};return e.i({method:e.w.waap_requestPermissionToken,params:[n]},!0,this.walletMessageManager,this.internalEventEmitter)}async getPermissionTokenStatus(t){return await this.ensureInitialized(),await e.i({method:e.w.waap_getPermissionTokenStatus,params:[t]},!1,this.walletMessageManager,this.internalEventEmitter)}async clearPermissionToken(t){return await this.ensureInitialized(),await e.i({method:e.w.waap_clearPermissionToken,params:[t]},!1,this.walletMessageManager,this.internalEventEmitter)}async requestSBT(t){return await this.ensureInitialized(),e.i({method:e.w.silk_requestSbt,params:[t]},!0,this.walletMessageManager,this.internalEventEmitter)}async getLinkedAddresses(){return await this.walletMessageManager.pingIframe(),(await e.i({method:e.w.waap_getLinkedAddresses,params:[]},!1,this.walletMessageManager,this.internalEventEmitter,f)).addresses}async linkAddress(n){if(typeof window>`u`)throw Error(`linkAddress requires a browser environment`);this.walletConnectProvider||await this.initializeWalletConnect(),t.t.isConnected()||(await this.walletConnectProvider.open({view:`Connect`}),await t.t.listenToAccountChangeEvent());let r=t.t.getWalletProvider();if(!r)throw Error(`No wallet provider available after connection`);let i=(await r.request({method:`eth_accounts`}))[0];if(!i||i.toLowerCase()!==n.toLowerCase())throw Error(`Connected wallet account ${i??`(none)`} does not match requested address ${n}`);await this.walletMessageManager.pingIframe();let a=await e.i({method:e.w.waap_getLinkAddressNonce,params:[]},!1,this.walletMessageManager,this.internalEventEmitter,f),o=p({domain:window.location.host,address:n,uri:window.location.origin,nonce:a.nonce,issuedAt:new Date().toISOString()}),s=await r.request({method:`personal_sign`,params:[o,n]});return(await e.i({method:e.w.waap_linkAddress,params:[{message:o,signature:s}]},!1,this.walletMessageManager,this.internalEventEmitter,f)).addresses}async unlinkAddress(t){return await this.walletMessageManager.pingIframe(),(await e.i({method:e.w.waap_unlinkAddress,params:[{address:t}]},!1,this.walletMessageManager,this.internalEventEmitter,f)).addresses}};const f={timeoutMs:10*6e4};function p(e){let t=(0,r.getAddress)(e.address);return`${`${e.domain} wants you to sign in with your Ethereum account:\n${t}`}\n\nLink this wallet to your Human Wallet account.\n\n${[`URI: ${e.uri}`,`Version: 1`,`Chain ID: 1`,`Nonce: ${e.nonce}`,`Issued At: ${e.issuedAt}`].join(`
1
+ const e=require("./UIMessageManager-Bzrjl7s7.js"),t=require("./WalletConnect-B21f4Vvh.js");let n=require("events"),r=require("ethers");const i=e=>typeof e==`object`&&!!e&&e.isComplete===!1&&typeof e.authUrl==`string`;function a(e){return!(!e?.isMetaMask||e.isApexWallet||e.isAvalanche||e.isBitKeep||e.isBlockWallet||e.isMathWallet||e.isOkxWallet||e.isOKExWallet||e.isOneInchIOSWallet||e.isOneInchAndroidWallet||e.isOpera||e.isPortal||e.isRabby||e.isDefiant||e.isTokenPocket||e.isTokenary||e.isZerion)}function o(e){try{if(!e||!Array.isArray(e))return!1;let t=JSON.parse(typeof e[1]==`string`?e[1]:JSON.stringify(e[1]));return t.primaryType===`SafeTx`&&t.domain?.verifyingContract!==void 0&&t.message&&`to`in t.message&&`value`in t.message&&`safeTxGas`in t.message&&`baseGas`in t.message&&`gasPrice`in t.message&&`nonce`in t.message}catch{return!1}}const s={styles:{darkMode:!1}},c=[`waap`,`human`,`injected`,`walletconnect`],l=[e.C.eth_sendTransaction,e.C.eth_signTransaction,e.C.eth_signTypedData_v4,e.C.personal_sign];function u(e){if(e==null)return null;if(typeof e==`string`){if(c.includes(e))return e;throw Error(`[EthereumProvider] Unexpected login method: "${e}". Expected one of: ${c.join(`, `)}`)}if(typeof e==`object`&&`loginMethod`in e&&typeof e.loginMethod==`string`){let t=e.loginMethod;if(console.warn(`[EthereumProvider] Received object login response. Normalizing "${t}" to string. This is unexpected for the web SDK.`),c.includes(t))return t;throw Error(`[EthereumProvider] Unknown loginMethod in object: "${t}". Expected one of: ${c.join(`, `)}`)}throw Error(`[EthereumProvider] Unexpected login response: ${JSON.stringify(e)} (type: ${typeof e})`)}var d=class extends n.EventEmitter{setExposeOnWindow(e){this.exposeOnWindow=e}constructor(t,r,i,a,o,c=!1,l=!1,u,d=[`evm`]){super(),this.lastKnownConversion=`pending`,this.isSilk=!0,this.isWaaP=!0,this.connected=!1,this.exposeOnWindow=!0,this.currentAccount=null,this.accountMode=`tap`,this.walletConnectProvider=null,this.asyncTxs=!1,this.legacyAsyncSigning=!1,this.internalEventEmitter=new n.EventEmitter,this.iframeMounted=!0,this.initializerPromise=null,this.sessionProbe=null,this.initializedIframeWindow=null,this.waapRestoreRetryAt=0,this.asyncTxs=c,this.legacyAsyncSigning=l,this.ensureIframe=u,this.iframeMounted=!u,this.referralCode=r,this.project=a,this.customConfig=i,this.initializerChains=d,this.uiMessageManager=new e.t,this.walletMessageManager=new e.d(t,o),this.config={...s,...i||{}},this.persistedMethods={login:this.login.bind(this),logout:this.logout.bind(this),getLoginMethod:this.getLoginMethod.bind(this),walletMessageManager:this.walletMessageManager,internalEventEmitter:this.internalEventEmitter,uiMessageManager:this.uiMessageManager,portal:this.portal.bind(this),requestEmail:this.requestEmail.bind(this),requestSBT:this.requestSBT.bind(this),requestPermissionToken:this.requestPermissionToken.bind(this),getLinkedAddresses:this.getLinkedAddresses.bind(this),linkAddress:this.linkAddress.bind(this),unlinkAddress:this.unlinkAddress.bind(this),orcid:this.orcid.bind(this),enable:this.enable.bind(this),isConnected:this.isConnected.bind(this),toggleDarkMode:this.toggleDarkMode.bind(this),destroy:this.destroy.bind(this),silkRequest:this.request.bind(this),waaPRequest:this.request.bind(this)},this.walletMessageManager.addListener({onReceiveConnectNotif:()=>{this.connected=!0,this.emit(`connect`)},handleResponse:e=>this.internalEventEmitter.emit(e.id,e),handleRequest:t=>{t.method===e.w.show_modal?this.uiMessageManager.emit(`show_modal`):t.method===e.w.hide_modal&&this.uiMessageManager.emit(`hide_modal`)},onAccountChanged:e=>{this.currentAccount!==e&&(this.currentAccount=e,this.emit(`accountsChanged`,e?[e]:[]))},onAsyncTxNotification:e=>{this.emit(e.type,e.payload)},onSquidLifecycleNotification:e=>{this.emit(e.type,e.payload)}})}async initializeWalletConnect(){try{this.walletConnectProvider=await t.t.getInstance()}catch(e){console.error(`Failed to initialize WalletConnect provider:`,e),this.walletConnectProvider=null}}async initializeIframeContext(){let t=this.walletMessageManager.getIframeWindow();if(!t)throw Error(`WaaP iframe is not mounted`);if(this.initializedIframeWindow===t&&this.initializerPromise)return this.initializerPromise;this.initializedIframeWindow=t,this.initializerPromise=e.m(t,async()=>{await this.walletMessageManager.pingIframe(),await e.i({method:e.w.set_signing_mode,params:[e.f(this.accountMode,{referralCode:this.referralCode,project:this.project,config:this.customConfig,chains:this.initializerChains})]},!1,this.walletMessageManager,this.internalEventEmitter)});try{await this.initializerPromise}catch(e){throw this.initializerPromise=null,this.initializedIframeWindow=null,e}}async reassertIframeAccountMode(){this.ensureIframeMounted(),await this.walletMessageManager.pingIframe(),await e.i({method:e.w.set_signing_mode,params:[e.f(this.accountMode,{referralCode:this.referralCode,project:this.project,config:this.customConfig,chains:this.initializerChains})]},!1,this.walletMessageManager,this.internalEventEmitter)}ensureIframeMounted(){if(this.iframeMounted||!this.ensureIframe)return;let e=this.ensureIframe();e&&(this.iframeMounted=!0,this.walletMessageManager.setIframeWindow(e))}async ensureInitialized(){this.ensureIframeMounted(),await this.initializeIframeContext()}async preload(){await this.ensureInitialized()}async enable(){return this.request({method:`eth_requestAccounts`})}isConnected(){return this.connected}getAccountStatus(){let e=this.getLoginMethod();return{authenticated:e!==null,loginMethod:e,activeMode:e?this.accountMode:null,mode:this.accountMode,conversion:e?this.lastKnownConversion:`not_required`,tap:null,squid:null,accounts:this.currentAccount?{evm:this.currentAccount}:{}}}get session(){return{login:e=>this.login(e),logout:async()=>{await this.logout()},getLoginMethod:()=>this.getLoginMethod(),getAccountStatus:()=>this.getCanonicalAccountStatus()}}async getCanonicalAccountStatus(){await this.ensureInitialized();let t=await e.i({method:e.w.waap_getAccountStatus,params:[]},!1,this.walletMessageManager,this.internalEventEmitter);return t?.conversion&&(this.lastKnownConversion=t.conversion),t}setAccountMode(e){this.accountMode=e,this.initializerPromise=null,this.initializedIframeWindow=null}async request(t){if(!Object.keys(e.C).includes(t.method))return Promise.reject({error:`Not implemented (${t.method})`});let n=await this.attemptAutoConnect(t.method);if(n!==null)return n;if(l.includes(t.method)&&!(this.getLoginMethod()!==null||await this.restorePersistedWaaPSession()!==null))return Promise.reject(new e.x(`not_authenticated`,`Not authenticated: call login() before signing.`,{operation:{chain:`evm`,method:t.method}}));if(o(t.params)&&t.method!==e.C.eth_signTypedData_v4)return Promise.reject({error:`Safe transactions must be signed using eth_signTypedData_v4`});await this.ensureInitialized();let r=(t.method===e.C.eth_sendTransaction||t.method===e.C.eth_signTransaction||t.method===e.C.eth_signTypedData_v4||t.method===e.C.personal_sign)&&this.asyncTxs||t.async,i=r||t.withPT||t.timeoutMs!==void 0||t.signal?this.legacyAsyncSigning?{asyncSigning:r||void 0,withPT:t.withPT,timeoutMs:t.timeoutMs,signal:t.signal}:{async:r,withPT:t.withPT,timeoutMs:t.timeoutMs,signal:t.signal}:void 0,a=await e.i(t,e.a(t.method),this.walletMessageManager,this.internalEventEmitter,i);if((t.method===e.C.wallet_switchEthereumChain||t.method===e.C.wallet_addEthereumChain)&&a===null){this.emit(`chainChanged`,t.params?.[0]?.chainId);try{let e=await this.request({method:`eth_accounts`});e&&e.length>0&&(this.currentAccount=e[0],this.emit(`accountsChanged`,e),this.emit(`connect`,{chainId:t.params?.[0]?.chainId}))}catch(e){console.warn(`[EthereumProvider] Failed to get accounts after chain switch:`,e),this.currentAccount&&(this.emit(`accountsChanged`,[this.currentAccount]),this.emit(`connect`,{chainId:t.params?.[0]?.chainId}))}}return t.method===e.C.eth_requestAccounts&&Array.isArray(a)&&typeof a[0]==`string`&&(this.currentAccount=a[0],this.connected=!0,typeof window<`u`&&typeof localStorage<`u`&&localStorage.setItem(`${window.location.origin}-connected`,`waap`),this.emit(`accountsChanged`,a),this.emit(`connect`)),a}async login(e){let t=await this.loginWithNativeHandoff(e);if(i(t))throw Error(`[WaaP SDK] The wallet returned a native auth hand-off. Use loginWithNativeHandoff() from a native host.`);return t}async loginWithNativeHandoff(n){if(this.waapRestoreRetryAt=0,typeof window>`u`||typeof document>`u`)return null;let r=n&&!(`request`in n)?n:void 0,o=r?r.customProvider:n;if(await this.ensureInitialized(),!r?.force&&await this.restorePersistedWaaPSession())return this.getLoginMethod()??`waap`;let s=o||window.ethereum,c=s&&a(s)?`MetaMask`:`Browser Wallet`,l=await e.i({method:e.w.login,params:[c]},!0,this.walletMessageManager,this.internalEventEmitter);if(i(l))return l;let d=u(l);if(d===null)return null;switch(d){case`waap`:case`human`:localStorage.setItem(`${window.location.origin}-connected`,`waap`),this.setupWaaP();break;case`injected`:s&&(localStorage.setItem(`${window.location.origin}-connected`,`injected`),this.setupInjectedWallet(s));break;case`walletconnect`:{localStorage.setItem(`${window.location.origin}-connected`,`walletconnect`),this.walletConnectProvider||await this.initializeWalletConnect(),t.t.isConnected()||(await this.walletConnectProvider.open({view:`Connect`}),await t.t.listenToAccountChangeEvent());let e=t.t.getWalletProvider();this.setupWalletConnect(e);break}}return d}async logout(){await this.ensureInitialized(),this.cleanupInvalidLoginState(),this.waapRestoreRetryAt=0,this.lastKnownConversion=`pending`,this.currentAccount=null,this.connected=!1,this.emit(`accountsChanged`,[]),this.emit(`disconnect`);try{this.walletConnectProvider&&await this.walletConnectProvider.disconnect()}catch(e){console.error(`Error disconnecting from WalletConnect:`,e)}return e.i({method:e.w.logout},!1,this.walletMessageManager,this.internalEventEmitter)}destroy(){if(this.walletMessageManager.dispose(),this.internalEventEmitter.removeAllListeners(),this.uiMessageManager.removeAllListeners(),this.removeAllListeners(),this.connected=!1,this.walletConnectProvider&&=(this.walletConnectProvider.disconnect().catch(()=>void 0),null),typeof window<`u`){let e=window;(e.silk===this||e.silk?.walletMessageManager===this.walletMessageManager)&&delete e.silk,(e.waap===this||e.waap?.walletMessageManager===this.walletMessageManager)&&delete e.waap}e._()}cleanupInvalidLoginState(){try{localStorage.removeItem(`${window.location.origin}-connected`)}catch(e){console.warn(`Could not clean up login state:`,e)}}setupWaaP(){if(!this.exposeOnWindow)return;let e={...this.persistedMethods,isWaaP:!0,on:this.on.bind(this),removeListener:this.removeListener.bind(this),request:this.request.bind(this)};window.silk=e,window.waap=e}setupInjectedWallet(e){if(!this.exposeOnWindow)return;let t={...this.persistedMethods,...e,isSilk:!0,connected:e.connected??!1,on:e.on?.bind(e)??(()=>{}),removeListener:e.removeListener?.bind(e)??(()=>{}),request:e.request.bind(e)};window.silk=t,window.waap=t}setupWalletConnect(e){if(!this.exposeOnWindow)return;let t={...this.persistedMethods,...e,isSilk:!0,connected:!0,on:e.on?.bind(e)??(()=>{}),removeListener:e.removeListener?.bind(e)??(()=>{}),request:e.request.bind(e)};window.silk=t,window.waap=t}setupAutoConnectInjected(e){if(!this.exposeOnWindow)return;let t={...this.persistedMethods,...e,isSilk:!1,connected:e.isConnected?.()??!1,on:e.on?.bind(e)??(()=>{}),removeListener:e.removeListener?.bind(e)??(()=>{}),request:e.request.bind(e)};window.silk=t,window.waap=t}setupAutoConnectWalletConnect(e){if(!this.exposeOnWindow)return;let t={...this.persistedMethods,...e,isSilk:!1,connected:!0,on:e.on?.bind(e)??(()=>{}),removeListener:e.removeListener?.bind(e)??(()=>{}),request:e.request.bind(e)};window.silk=t,window.waap=t}async attemptAutoConnect(e){if(e!==`eth_requestAccounts`&&e!==`eth_accounts`)return null;let n=this.getLoginMethod();if(n===`waap`||n===`human`||n===null&&e===`eth_accounts`&&Date.now()>=this.waapRestoreRetryAt){let e=await this.restorePersistedWaaPSession();if(e)return e;n===null&&(this.waapRestoreRetryAt=Date.now()+5e3)}if(n===`injected`&&window.ethereum)try{return this.setupAutoConnectInjected(window.ethereum),window.ethereum.request({method:`eth_requestAccounts`})}catch(e){return console.warn(`Injected wallet auto-connect failed:`,e),this.cleanupInvalidLoginState(),null}else if(n===`walletconnect`)try{if(this.walletConnectProvider||=await t.t.getInstance(),await t.t.waitForReadyAndCheckConnection()){let e=t.t.getWalletProvider();return this.setupAutoConnectWalletConnect(e),e.request({method:`eth_requestAccounts`})}else return this.cleanupInvalidLoginState(),null}catch(e){return console.warn(`WalletConnect auto-connect failed:`,e),this.cleanupInvalidLoginState(),null}return null}restorePersistedWaaPSession(){return this.sessionProbe??=this.probeWaaPSession().finally(()=>{this.sessionProbe=null}),this.sessionProbe}async probeWaaPSession(){try{if(await this.ensureInitialized(),!(await this.getCanonicalAccountStatus()).authenticated)return this.cleanupInvalidLoginState(),null;let t=await e.i({method:e.w.auto_conn,params:[window.location.origin]},!1,this.walletMessageManager,this.internalEventEmitter);if(Array.isArray(t)&&t.length>0)return this.currentAccount=t[0],this.connected=!0,localStorage.setItem(`${window.location.origin}-connected`,`waap`),this.setupWaaP(),t}catch(e){console.warn(`WaaP session probe failed:`,e)}return this.cleanupInvalidLoginState(),null}getLoginMethod(){if(typeof window>`u`||typeof localStorage>`u`)return null;try{let e=localStorage.getItem(`${window.location.origin}-connected`);if(!e)return null;if(![`waap`,`human`,`injected`,`walletconnect`].includes(e))return this.cleanupInvalidLoginState(),null;switch(e){case`injected`:return window.ethereum?`injected`:(this.cleanupInvalidLoginState(),null);case`walletconnect`:try{return t.t.isConnected()?`walletconnect`:(this.cleanupInvalidLoginState(),null)}catch{return this.cleanupInvalidLoginState(),null}case`waap`:return`waap`;case`human`:return`human`;default:return this.cleanupInvalidLoginState(),null}}catch(e){return console.warn(`Error checking login method:`,e),this.cleanupInvalidLoginState(),null}}async toggleDarkMode(){this.config.styles.darkMode=!this.config.styles.darkMode,await this.ensureInitialized();try{await e.i({method:e.w.set_custom_config,params:[this.config]},!1,this.walletMessageManager,this.internalEventEmitter)}catch(e){console.error(`Error setting custom config in Silk iframe:`,e)}}async safe(){await this.ensureInitialized(),await e.i({method:e.w.safe},!0,this.walletMessageManager,this.internalEventEmitter)}async orcid(){await this.ensureInitialized(),await e.i({method:e.w.orcid},!0,this.walletMessageManager,this.internalEventEmitter)}async portal(t,n,r){await this.ensureInitialized();let i;switch(n){case`get`:i=t===`gastank`?e.w.gastank_get_settings:e.w.customization_get;break;case`update`:i=t===`gastank`?e.w.gastank_update_settings:e.w.customization_update;break;case`topup`:i=e.w.gastank_topup;break;case`init`:i=e.w.project_init;break}let a=n!==`get`&&t!==`customization`;return e.i({method:i,params:[r,window.location.origin]},a,this.walletMessageManager,this.internalEventEmitter)}async requestEmail(){return await this.ensureInitialized(),e.i({method:e.w.silk_requestEmail},!0,this.walletMessageManager,this.internalEventEmitter)}async requestPermissionToken(t){await this.ensureInitialized();let n={...t,walletMode:this.accountMode};return e.i({method:e.w.waap_requestPermissionToken,params:[n]},!0,this.walletMessageManager,this.internalEventEmitter)}async getPermissionTokenStatus(t){return await this.ensureInitialized(),await e.i({method:e.w.waap_getPermissionTokenStatus,params:[t]},!1,this.walletMessageManager,this.internalEventEmitter)}async clearPermissionToken(t){return await this.ensureInitialized(),await e.i({method:e.w.waap_clearPermissionToken,params:[t]},!1,this.walletMessageManager,this.internalEventEmitter)}async requestSBT(t){return await this.ensureInitialized(),e.i({method:e.w.silk_requestSbt,params:[t]},!0,this.walletMessageManager,this.internalEventEmitter)}async getLinkedAddresses(){return await this.walletMessageManager.pingIframe(),(await e.i({method:e.w.waap_getLinkedAddresses,params:[]},!1,this.walletMessageManager,this.internalEventEmitter,f)).addresses}async linkAddress(n){if(typeof window>`u`)throw Error(`linkAddress requires a browser environment`);this.walletConnectProvider||await this.initializeWalletConnect(),t.t.isConnected()||(await this.walletConnectProvider.open({view:`Connect`}),await t.t.listenToAccountChangeEvent());let r=t.t.getWalletProvider();if(!r)throw Error(`No wallet provider available after connection`);let i=(await r.request({method:`eth_accounts`}))[0];if(!i||i.toLowerCase()!==n.toLowerCase())throw Error(`Connected wallet account ${i??`(none)`} does not match requested address ${n}`);await this.walletMessageManager.pingIframe();let a=await e.i({method:e.w.waap_getLinkAddressNonce,params:[]},!1,this.walletMessageManager,this.internalEventEmitter,f),o=p({domain:window.location.host,address:n,uri:window.location.origin,nonce:a.nonce,issuedAt:new Date().toISOString()}),s=await r.request({method:`personal_sign`,params:[o,n]});return(await e.i({method:e.w.waap_linkAddress,params:[{message:o,signature:s}]},!1,this.walletMessageManager,this.internalEventEmitter,f)).addresses}async unlinkAddress(t){return await this.walletMessageManager.pingIframe(),(await e.i({method:e.w.waap_unlinkAddress,params:[{address:t}]},!1,this.walletMessageManager,this.internalEventEmitter,f)).addresses}};const f={timeoutMs:10*6e4};function p(e){let t=(0,r.getAddress)(e.address);return`${`${e.domain} wants you to sign in with your Ethereum account:\n${t}`}\n\nLink this wallet to your Human Wallet account.\n\n${[`URI: ${e.uri}`,`Version: 1`,`Chain ID: 1`,`Nonce: ${e.nonce}`,`Issued At: ${e.issuedAt}`].join(`
2
2
  `)}`}const m=(n,r,i=!0,a=[`evm`],o=!0)=>{let{referralCode:s,config:c,project:l,asyncTxs:u,asyncSigning:f,deferIframe:p}=n,m=e.v(n),h=!!f&&!u;n.walletConnectProjectId&&t.t.setProjectId(n.walletConnectProjectId),f&&!u&&console.warn("[WaaP SDK] `asyncSigning` is deprecated. Use `asyncTxs` instead.");let g=typeof window>`u`||typeof document>`u`,_=()=>typeof window>`u`||typeof document>`u`?null:(e.g(n),e.h(r).contentWindow),v=p===!1&&!g,y=p===void 0&&!g,b=v?_():null;if(v&&!b)throw Error(`WaaP iframe does not exist on page`);let x=new d(b,s,c||{},l||{},m,u||f||!1,h,v?void 0:_,a);if(x.setAccountMode(r),x.setExposeOnWindow(o),!g&&i&&v&&x.initializeIframeContext().catch(()=>void 0),x.uiMessageManager.on(`show_modal`,()=>{e.l()}),x.uiMessageManager.on(`hide_modal`,()=>{e.c()}),!g&&o&&(window.silk=x,window.waap=x),i&&y){let t=e.r(x),n=x.destroy.bind(x);x.destroy=()=>{t(),n()}}return x},h=(e={})=>m(e,`tap`);Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return h}});
package/dist/evm.js CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./UIMessageManager-CPw6PggC.js"),t=require("./evm-_ReyhrCP.js");exports.WaaPError=e.x,exports.getWaaPIframeDiagnostics=e.s,exports.initWaaP=t.t,exports.normalizeWaaPError=e.S,exports.preloadWaaPOnIdle=e.r,exports.resolveWalletOrigin=e.v,exports.subscribeWaaPIframeLifecycle=e.u,exports.validateWalletOrigin=e.y;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./UIMessageManager-Bzrjl7s7.js"),t=require("./evm-xQ1FQAuX.js");exports.WaaPError=e.x,exports.getWaaPIframeDiagnostics=e.s,exports.initWaaP=t.t,exports.normalizeWaaPError=e.S,exports.preloadWaaPOnIdle=e.r,exports.resolveWalletOrigin=e.v,exports.subscribeWaaPIframeLifecycle=e.u,exports.validateWalletOrigin=e.y;
package/dist/evm.mjs CHANGED
@@ -1 +1 @@
1
- import{S as e,r as t,s as n,u as r,v as i,x as a,y as o}from"./UIMessageManager-D3VN9vM8.mjs";import{t as s}from"./evm-BbSgL_Hv.mjs";export{a as WaaPError,n as getWaaPIframeDiagnostics,s as initWaaP,e as normalizeWaaPError,t as preloadWaaPOnIdle,i as resolveWalletOrigin,r as subscribeWaaPIframeLifecycle,o as validateWalletOrigin};
1
+ import{S as e,r as t,s as n,u as r,v as i,x as a,y as o}from"./UIMessageManager-BSJdvCEF.mjs";import{t as s}from"./evm-dDrPUbNZ.mjs";export{a as WaaPError,n as getWaaPIframeDiagnostics,s as initWaaP,e as normalizeWaaPError,t as preloadWaaPOnIdle,i as resolveWalletOrigin,r as subscribeWaaPIframeLifecycle,o as validateWalletOrigin};