@human.tech/waap-sdk 1.2.1 → 1.2.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.
@@ -1,2 +1,2 @@
1
- import{silkWalletAppOrigin2Staging as e,silkWalletAppOrigin2 as t,rpcMethodRequiresUI as n}from"@human.tech/waap-constants";export{rpcMethodRequiresUI}from"@human.tech/waap-constants";import{EventEmitter as i}from"events";import{SILK_MESSAGE_TYPE as a,SILK_NOTIFICATION as s,generateMessageId as o,SILK_METHOD as r,JSON_RPC_METHOD as c}from"@human.tech/waap-interface-core";export{SILK_METHOD,SILK_METHOD as WAAP_METHOD}from"@human.tech/waap-interface-core";import{EthersAdapter as l}from"@reown/appkit-adapter-ethers";import{registerWallet as d}from"@mysten/wallet-standard";import{useState as u,useRef as h,useEffect as g,useCallback as m}from"react";function p(){return p=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},p.apply(null,arguments)}var w;!function(e){e.show_modal="show_modal",e.hide_modal="hide_modal"}(w||(w={}));class f extends i{constructor(){super()}}async function y(e,t,n,i,a){const s=e.method,o=e.params,r=await n.postSilkRequest({method:s,params:o,interactionRequired:t,silkOptions:a});return new Promise((e,t)=>{i.once(r,n=>{n.error?t(n.error):e(n.data)})})}const v={styles:{darkMode:!1}};class M{static setProjectId(e){this.projectId=e}static getProjectIdFromEnv(){try{if("undefined"!=typeof process&&process.env)return process.env.NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID||process.env.VITE_WALLET_CONNECT_PROJECT_ID||process.env.REACT_APP_WALLET_CONNECT_PROJECT_ID||process.env.WALLET_CONNECT_PROJECT_ID}catch(e){return}}static async getInstance(){if("undefined"==typeof window||"undefined"==typeof document)return null;const{createAppKit:e}=await import("@reown/appkit"),{mainnet:t,sepolia:n,optimism:i,arbitrum:a,polygon:s,gnosis:o,avalanche:r,aurora:c,fantom:d,base:u,celo:h}=await import("@reown/appkit/networks");try{const g={name:"Human Wallet",description:"Silk lets you create human keys for web3 wallets that are recoverable with private identity proofs and secured by zero trust protocols.",url:window.location.origin,icons:["https://imagedelivery.net/_aTEfDRm7z3tKgu9JhfeKA/f11f5753-616a-4aa0-2aee-9b75befea700/sm"]},m=this.projectId||this.getProjectIdFromEnv();return m?(this.projectId=m,this.instance||(this.instance=e({adapters:[new l],projectId:m,metadata:g,networks:[t,n,a,i,s,o,r,c,d,u,h],features:{socials:!1,email:!1}})),this.instance):(console.error('WalletConnect project ID not found. Please set it using one of these methods:\n1. Pass walletConnectProjectId when calling initSilk\n2. Call SilkWalletConnect.setProjectId("your-project-id")\n3. Set WALLET_CONNECT_PROJECT_ID (NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID for Next projects) environment variable'),null)}catch(e){return console.error("Error importing or initializing WalletConnect:",e),null}}static async listenToAccountChangeEvent(){await new Promise(e=>{this.instance.subscribeAccount(t=>{null!=t&&t.isConnected&&e()})})}static async waitForReadyAndCheckConnection(){if(!this.instance)return!1;let e=!1,t=0;for(;!e&&t<15;){const n=t<5?500:1e3;await new Promise(e=>setTimeout(e,n)),e=this.instance.getIsConnectedState(),t++,console.log(`WalletConnect connection check attempt ${t}: ${e}`)}return e}static isConnected(){var e,t;return null!=(e=null==(t=this.instance)?void 0:t.getIsConnectedState())&&e}static getWalletProvider(){var e,t;return null!=(e=null==(t=this.instance)?void 0:t.getWalletProvider())?e:null}}M.instance=null,M.projectId=void 0,M.chains=[1,10,100,137,8453,43114,42161,42220,84532,11155111];const E=["silkOptions"];class A{constructor(n,i){this.iframeWindow=null,this.walletOrigin=void 0,this.iframeWindow=n,this.walletOrigin=i?e:t}postSilkNotification(e){this.iframeWindow.postMessage({target:"silk",messageType:a.notification,data:e},this.walletOrigin)}postReadyNotification(){this.postSilkNotification(s.ready)}postConnectNotification(){this.postSilkNotification(s.connect)}pingIframe(){return new Promise((e,t)=>{setTimeout(()=>t("Wallet ping timed out."),1e4);const n=t=>{"silk"===t.data.target&&t.data.messageType===a.notification&&t.data.data===s.ready&&(window.removeEventListener("message",n),e())};window.addEventListener("message",n),this.postReadyNotification()})}async postSilkRequest(e){const{silkOptions:t}=e,n=p({},function(e,t){if(null==e)return{};var n={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;n[i]=e[i]}return n}(e,E),{target:"silk",messageType:a.request},t&&{silkOptions:t}),i=await o(n);return this.iframeWindow.postMessage(p({},n,{id:i}),this.walletOrigin),i}addListener(e){const{handleResponse:t,handleRequest:n,onReceiveConnectNotif:i,onAccountChanged:o,onAsyncTxNotification:r}=e;window.addEventListener("message",e=>{var c,l,d;try{if("undefined"!=typeof process&&process,e.origin!==this.walletOrigin)return}catch(t){if(e.origin!==this.walletOrigin)return}if((null==(c=e.data)?void 0:c.messageType)===a.request)n(e.data);else if((null==(l=e.data)?void 0:l.messageType)===a.response)t(e.data);else if((null==(d=e.data)?void 0:d.messageType)===a.notification){var u,h,g,m;(null==(u=e.data)?void 0:u.data)===s.connect?null==i||i():(null==(h=e.data)||null==(h=h.data)?void 0:h.type)===s.account_changed&&o?o(e.data.data.account):(null!=(g=e.data)&&null!=(g=g.data)&&null!=(g=g.type)&&g.startsWith("waap_sign_")||null!=(m=e.data)&&null!=(m=m.data)&&null!=(m=m.type)&&m.startsWith("waap_tx_"))&&r&&r({type:e.data.data.type,payload:e.data.data.payload})}})}}const b=["waap","human","injected","walletconnect"];class C extends i{constructor(e,t,n,a,s,o=!1,c=!1){super(),this.isSilk=!0,this.isWaaP=!0,this.connected=!1,this.walletMessageManager=void 0,this.uiMessageManager=void 0,this.config=void 0,this.currentAccount=null,this.walletConnectProvider=null,this.asyncTxs=!1,this.legacyAsyncSigning=!1,this.persistedMethods=void 0,this.internalEventEmitter=new i,this.asyncTxs=o,this.legacyAsyncSigning=c,this.uiMessageManager=new f,this.walletMessageManager=new A(e,!!s),this.config=p({},v,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),orcid:this.orcid.bind(this),enable:this.enable.bind(this),isConnected:this.isConnected.bind(this),toggleDarkMode:this.toggleDarkMode.bind(this),silkRequest:this.request.bind(this),waaPRequest:this.request.bind(this)},this.walletMessageManager.addListener({onReceiveConnectNotif:()=>{console.log("onReceiveConnectNotif"),this.connected=!0,this.emit("connect")},handleResponse:e=>this.internalEventEmitter.emit(e.id,e),handleRequest:e=>{e.method===r.show_modal?this.uiMessageManager.emit(w.show_modal):e.method===r.hide_modal&&this.uiMessageManager.emit(w.hide_modal)},onAccountChanged:e=>{this.currentAccount!==e&&(this.currentAccount=e,this.emit("accountsChanged",e?[e]:[]))},onAsyncTxNotification:e=>{this.emit(e.type,e.payload)}}),t&&this.walletMessageManager.pingIframe().then(()=>y({method:r.set_points_referral_code,params:[t]},!1,this.walletMessageManager,this.internalEventEmitter)).catch(e=>{console.error("Error setting referral code in Silk iframe:",e)}),a&&(console.log(" =========== project =========== ",a),this.walletMessageManager.pingIframe().then(()=>y({method:r.set_project,params:[a,window.location.origin]},!1,this.walletMessageManager,this.internalEventEmitter))),n&&this.walletMessageManager.pingIframe().then(()=>y({method:r.set_custom_config,params:[n]},!1,this.walletMessageManager,this.internalEventEmitter)).catch(e=>{console.error("Error setting custom config in Silk iframe:",e)})}async initializeWalletConnect(){try{this.walletConnectProvider=await M.getInstance(),console.log("WalletConnect provider initialized")}catch(e){console.error("Failed to initialize WalletConnect provider:",e),this.walletConnectProvider=null}}async enable(){return this.request({method:"eth_requestAccounts"})}isConnected(){return this.connected}async request(e){if(!Object.keys(c).includes(e.method))return Promise.reject({error:`Not implemented (${e.method})`});const t=await this.attemptAutoConnect(e.method);if(null!==t)return t;if(function(e){try{var t;if(!e||!Array.isArray(e))return!1;const n=JSON.parse("string"==typeof e[1]?e[1]:JSON.stringify(e[1]));return"SafeTx"===n.primaryType&&void 0!==(null==(t=n.domain)?void 0:t.verifyingContract)&&n.message&&"to"in n.message&&"value"in n.message&&"safeTxGas"in n.message&&"baseGas"in n.message&&"gasPrice"in n.message&&"nonce"in n.message}catch(e){return!1}}(e.params)&&e.method!==c.eth_signTypedData_v4)return Promise.reject({error:"Safe transactions must be signed using eth_signTypedData_v4"});await this.walletMessageManager.pingIframe();const i=(e.method===c.eth_sendTransaction||e.method===c.eth_signTransaction||e.method===c.eth_signTypedData_v4||e.method===c.personal_sign)&&this.asyncTxs||e.async,a=i||e.withPT?this.legacyAsyncSigning?{asyncSigning:i||void 0,withPT:e.withPT}:{async:i,withPT:e.withPT}:void 0,s=await y(e,n(e.method),this.walletMessageManager,this.internalEventEmitter,a);if((e.method===c.wallet_switchEthereumChain||e.method===c.wallet_addEthereumChain)&&null===s){var o;this.emit("chainChanged",null==(o=e.params)||null==(o=o[0])?void 0:o.chainId);try{const t=await this.request({method:"eth_accounts"});var r,l;t&&t.length>0&&(this.currentAccount=t[0],this.emit("accountsChanged",t),this.emit("connect",{chainId:null==(r=e.params)||null==(r=r[0])?void 0:r.chainId}),console.log("[EthereumProvider] Re-emitted accounts and connect after chain switch:",{accounts:t,chainId:null==(l=e.params)||null==(l=l[0])?void 0:l.chainId}))}catch(t){var d;console.warn("[EthereumProvider] Failed to get accounts after chain switch:",t),this.currentAccount&&(this.emit("accountsChanged",[this.currentAccount]),this.emit("connect",{chainId:null==(d=e.params)||null==(d=d[0])?void 0:d.chainId}))}}return s}async login(e){var t;if("undefined"==typeof window||"undefined"==typeof document)return null;null!=(t=this.config.authenticationMethods)&&t.includes("wallet")&&!this.walletConnectProvider&&await this.initializeWalletConnect();const n=e||window.ethereum,i=n&&function(e){return!(null==e||!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)}(n)?"MetaMask":"Browser Wallet";await this.walletMessageManager.pingIframe();const a=function(e){if(null==e)return null;if("string"==typeof e){if(b.includes(e))return e;throw new Error(`[EthereumProvider] Unexpected login method: "${e}". Expected one of: ${b.join(", ")}`)}if("object"==typeof e&&"loginMethod"in e&&"string"==typeof e.loginMethod){const t=e.loginMethod;if(console.warn(`[EthereumProvider] Received object login response. Normalizing "${t}" to string. This is unexpected for the web SDK.`),b.includes(t))return t;throw new Error(`[EthereumProvider] Unknown loginMethod in object: "${t}". Expected one of: ${b.join(", ")}`)}throw new Error(`[EthereumProvider] Unexpected login response: ${JSON.stringify(e)} (type: ${typeof e})`)}(await y({method:r.login,params:[i]},!0,this.walletMessageManager,this.internalEventEmitter));if(null===a)return null;switch(a){case"waap":case"human":localStorage.setItem(`${window.location.origin}-connected`,"waap"),this.setupWaaP();break;case"injected":n&&(localStorage.setItem(`${window.location.origin}-connected`,"injected"),this.setupInjectedWallet(n));break;case"walletconnect":{localStorage.setItem(`${window.location.origin}-connected`,"walletconnect"),M.isConnected()||(await this.walletConnectProvider.open({view:"Connect"}),await M.listenToAccountChangeEvent());const e=M.getWalletProvider();this.setupWalletConnect(e);break}}return a}async logout(){await this.walletMessageManager.pingIframe(),this.cleanupInvalidLoginState();try{this.walletConnectProvider&&await this.walletConnectProvider.disconnect()}catch(e){console.error("Error disconnecting from WalletConnect:",e)}return y({method:r.logout},!1,this.walletMessageManager,this.internalEventEmitter)}cleanupInvalidLoginState(){try{localStorage.removeItem(`${window.location.origin}-connected`)}catch(e){console.warn("Could not clean up login state:",e)}}setupWaaP(){const e=p({},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){var t,n,i,a,s;const o=p({},this.persistedMethods,e,{isSilk:!0,connected:null!=(t=e.connected)&&t,on:null!=(n=null==(i=e.on)?void 0:i.bind(e))?n:()=>{},removeListener:null!=(a=null==(s=e.removeListener)?void 0:s.bind(e))?a:()=>{},request:e.request.bind(e)});window.silk=o,window.waap=o}setupWalletConnect(e){var t,n,i,a;const s=p({},this.persistedMethods,e,{isSilk:!0,connected:!0,on:null!=(t=null==(n=e.on)?void 0:n.bind(e))?t:()=>{},removeListener:null!=(i=null==(a=e.removeListener)?void 0:a.bind(e))?i:()=>{},request:e.request.bind(e)});window.silk=s,window.waap=s}setupAutoConnectInjected(e){var t,n,i,a,s;const o=p({},this.persistedMethods,e,{isSilk:!1,connected:null!=(t=null==e.isConnected?void 0:e.isConnected())&&t,on:null!=(n=null==(i=e.on)?void 0:i.bind(e))?n:()=>{},removeListener:null!=(a=null==(s=e.removeListener)?void 0:s.bind(e))?a:()=>{},request:e.request.bind(e)});window.silk=o,window.waap=o}setupAutoConnectWalletConnect(e){var t,n,i,a;const s=p({},this.persistedMethods,e,{isSilk:!1,connected:!0,on:null!=(t=null==(n=e.on)?void 0:n.bind(e))?t:()=>{},removeListener:null!=(i=null==(a=e.removeListener)?void 0:a.bind(e))?i:()=>{},request:e.request.bind(e)});window.silk=s,window.waap=s}async attemptAutoConnect(e){var t=this;if("eth_requestAccounts"!==e&&"eth_accounts"!==e)return null;this.walletMessageManager.pingIframe().then(async function(){await y({method:r.auto_conn,params:[window.location.origin]},!1,t.walletMessageManager,t.internalEventEmitter)});const n=this.getLoginMethod();if("injected"===n&&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("walletconnect"===n)try{if(this.walletConnectProvider||(this.walletConnectProvider=await M.getInstance()),await M.waitForReadyAndCheckConnection()){const e=M.getWalletProvider();return this.setupAutoConnectWalletConnect(e),e.request({method:"eth_requestAccounts"})}return console.log("WalletConnect not connected, cleaning up and falling through to normal flow"),this.cleanupInvalidLoginState(),null}catch(e){return console.warn("WalletConnect auto-connect failed:",e),this.cleanupInvalidLoginState(),null}return null}getLoginMethod(){if("undefined"==typeof window||"undefined"==typeof localStorage)return null;try{const 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 M.isConnected()?"walletconnect":(this.cleanupInvalidLoginState(),null)}catch(e){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,this.walletMessageManager.pingIframe().then(()=>y({method:r.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(){this.walletMessageManager.pingIframe().then(()=>y({method:r.safe},!0,this.walletMessageManager,this.internalEventEmitter))}async orcid(){this.walletMessageManager.pingIframe().then(()=>y({method:r.orcid},!0,this.walletMessageManager,this.internalEventEmitter))}async portal(e,t,n){let i;switch(await this.walletMessageManager.pingIframe(),t){case"get":i="gastank"===e?r.gastank_get_settings:r.customization_get;break;case"update":i="gastank"===e?r.gastank_update_settings:r.customization_update;break;case"topup":i=r.gastank_topup;break;case"init":i=r.project_init}return y({method:i,params:[n,window.location.origin]},"get"!==t&&"customization"!==e,this.walletMessageManager,this.internalEventEmitter)}async requestEmail(){return await this.walletMessageManager.pingIframe(),y({method:r.silk_requestEmail},!0,this.walletMessageManager,this.internalEventEmitter)}async requestPermissionToken(e){return await this.walletMessageManager.pingIframe(),y({method:r.waap_requestPermissionToken,params:[e]},!0,this.walletMessageManager,this.internalEventEmitter)}async requestSBT(e){return await this.walletMessageManager.pingIframe(),y({method:r.silk_requestSbt,params:[e]},!0,this.walletMessageManager,this.internalEventEmitter)}}const _="waap-wallet",k="waap-component-container",I="undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof HTMLElement;let T;function x(){return!(!I||!document.getElementById(k)&&!document.querySelector(_))}function P(){return I?document.getElementById(k)||document.querySelector(_):null}I?(T=class extends HTMLElement{constructor(){super(),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=k}connectedCallback(){this.setAttribute("data-waap-mounted","true")}disconnectedCallback(){this.removeAttribute("data-waap-mounted")}},"undefined"==typeof customElements||customElements.get(_)||customElements.define(_,T)):T=class{};const S="waap-wallet-iframe-container",q="waap-wallet-iframe-wrapper",W="waap-wallet-iframe",L=()=>document.getElementById(S)||document.getElementById("silk-wallet-iframe-container"),R=()=>document.getElementById(q)||document.getElementById("silk-wallet-iframe-wrapper"),j=()=>document.getElementById(W)||document.getElementById("silk-wallet-iframe"),O=S,N=q,B=W,D=n=>{const i=window.document.createElement("iframe");return i.id=B,i.src=`${n?e:t}/iframe`,console.log("iframe.src: ",i.src),i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.borderRadius="24px",i.style.backgroundColor="transparent",i.style.background="transparent",i.style.padding="0",i.style.margin="0",i},F=(n,i)=>{const a=i=>{if(i.origin!==(n?e:t))return;if(!i.data||"object"!=typeof i.data)return;if("silk-iframe-size"!==i.data.type)return;const a=i.data.height,s=i.data.width;if("number"!=typeof a||"number"!=typeof s)return;if(a<50||a>2e3)return;if(s<50||s>2e3)return;if(!Number.isFinite(a)||!Number.isFinite(s))return;const o=R();o&&(o.style.height=`${Math.floor(a)}px`,o.style.width=`${Math.floor(s)}px`)};window.addEventListener("message",a),i.__silkCleanup=()=>{window.removeEventListener("message",a)}},z=(e={})=>{var t;t=!!e.useStaging,x()?(e=>{const t=P();if(!t)throw new Error("WaaP component not found in DOM");if(j())return;const n=window.document.createElement("div");n.id=N,n.style.position="relative",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0",n.style.margin="0",n.style.height="600px",n.style.width="380px";const i=D(e);F(e,i),setTimeout(()=>{const e=R();e&&(e.style.height="600px",e.style.width="380px")},100),n.appendChild(i),t.appendChild(n)})(t):(e=>{if(L())return;const t=window.document.createElement("div");t.id=O,t.style.position="fixed",t.style.top="0",t.style.left="0",t.style.right="0",t.style.bottom="0",t.style.width="100%",t.style.height="100%",t.style.display="flex",t.style.alignItems="center",t.style.justifyContent="center",t.style.backgroundColor="rgba(0, 0, 0, 0.5)",t.style.zIndex="9999999999",t.style.display="none";const n=window.document.createElement("div");n.id=N,n.style.position="relative",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0",n.style.margin="0",n.style.height="600px",n.style.width="380px",t.appendChild(n);const i=D(e);F(e,i),setTimeout(()=>{const e=R();e&&(e.style.height="600px",e.style.width="380px")},100),n.appendChild(i),window.document.body.appendChild(t)})(t);const n=j();if(!n)throw new Error("WaaP iframe does not exist on page");const i=x();e.walletConnectProjectId&&M.setProjectId(e.walletConnectProjectId);const{referralCode:a,config:s,project:o,asyncTxs:r,asyncSigning:c}=e;c&&!r&&console.warn("[WaaP SDK] `asyncSigning` is deprecated. Use `asyncTxs` instead.");const l=new C(n.contentWindow,a,s||{},o||{},e.useStaging,r||c||!1);let d=i?"component":"modal";return l.uiMessageManager.on(w.show_modal,()=>{const e=x(),t=e?"component":"modal",n=R();if(t!==d&&n)if(d=t,e){const e=P();e&&e.appendChild(n)}else{let e=L();e||(e=window.document.createElement("div"),e.id=O,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.display="flex",e.style.alignItems="center",e.style.justifyContent="center",e.style.backgroundColor="rgba(0, 0, 0, 0.5)",e.style.zIndex="9999999999",window.document.body.appendChild(e)),e.appendChild(n)}const i=L();e&&n?n.style.display="flex":i&&(i.style.display="flex")}),l.uiMessageManager.on(w.hide_modal,()=>{const e=x(),t=R(),n=L();e&&t?t.style.display="none":n&&(n.style.display="none")}),window.silk=l,window.waap=l,l};class J extends i{constructor(e){super(),this.isSilk=!0,this.connected=!1,this.config=void 0,this.config=p({},v,e||{})}sendToExtension(e){return new Promise((t,n)=>{window.postMessage({type:"FROM_PAGE",request:e},"*"),window.addEventListener("message",e=>{"FROM_EXTENSION"===e.data.type&&(e.data.error?n(e.data.error):t(e.data.result))})})}async request(e){if(!Object.keys(c).includes(e.method))return Promise.reject({error:`Not implemented (${e.method})`});const t=await this.sendToExtension(e);var n;return e.method!==c.wallet_switchEthereumChain&&e.method!==c.wallet_addEthereumChain||null!==t||this.emit("chainChanged",null==(n=e.params)||null==(n=n[0])?void 0:n.chainId),t}async enable(){return this.request({method:"eth_requestAccounts"})}isConnected(){return this.connected}async login(){return this.sendToExtension({method:r.login})}async requestSBT(e){return this.sendToExtension({method:r.silk_requestSbt,params:[e]})}async toggleDarkMode(){this.config.styles.darkMode=!this.config.styles.darkMode,await this.sendToExtension({method:r.set_custom_config,params:[this.config]})}async safe(){return this.sendToExtension({method:r.safe})}}class U{constructor(e,t={}){var n,a=this;this.name="WaaP",this.version="1.0.0",this.icon="data:image/webp;base64,UklGRpoDAABXRUJQVlA4WAoAAAAQAAAAYwAAYwAAQUxQSDMDAAABJyAQSOFmFxERA8TatqpGoimANbEAxlBAPhSgQP9FyXv3vkcFEf134EZS5DREhGvTM8z0ki8stMRvK4cm8bk5rIu3xNbvkgPk4K6ti5IHquRQnLi6KrdBb81hdyF1jTLM1CW425943iba38/djOcG+dg85p/KXGd/g7+xAzJ2VPWTS8R+q65uA1ZcwG3iZ4urjw9Lh4xn83n3gZmQQ3VMVGEO6D403jdr81Ml1OISAAf7RGImBHISwQ5zCJonTuEyOyP7Sga4cDcjMPgXuiK9cUpaGrIDJtH4iAB25utB8O0DDztOKTr8u9hpX0jrx6k8UM5eAlqsynNxlX9tPRLQEtySKwcDOIDnMqEcek1UnylVNac4r0mlypNvhmCNODlhUXuT4fxTQyrDKY0uyV+gi0iiLLpY76A08C/IX8GQoYb8PcVxK7HkZkT5IjAF4gZicOfJW1ovJjyAlYVPlM6BkkHGI0fniAIZIXC0CbAM92BB8SBznU0ITYLr9XkfnKlDgV8170HGMWwitY51+zxcgkftLD4RLh4HSTIa3QzRWKxlaHZTz21s6GLxnBmjogkVilW4kuaMMMGUfgkZ1JhrBSEANrEDMwucAXgbTqIExY3FYRMdtkQRDFjD6BKtJ2GWTopGRY4P9DBkdE4rp9LJHuYhju45oeVZVv3zNmVdZiIOffHDppOz0Q34p0e/+nXy7JmF1846lmF2ZombLt8pgZpbPNeqpJSVJ0bGd4cH8dUNflNPfdQVXUkC95UQS0ZGfDmOJgjs3IyVOExZBEsxONd080gYK/ftQ2nbYaqGW89Hu7M6avmzXEjhO4G8O8ae8gwWtwZsyp8v8j/ys5H7bM+unOfurO4bbbL4v865Nb8s98Ld2X9yg6tLBQanMP8fhplOMMN8fiNDzTvNOMXGuYzejo12vY7s3clhXwgDPuBIcxi9QZftbKVxAjLCcVQdRxGR1QknhCs3GuieMLzfrrC9RhfJgVpcXRn71nZfEjsiYy/Ca1J7ch0clK64ReH3G/s2cekpP+BIx2YteMvSoLy6G9FCgd1nvF/VoVRtJoNJNLQ0RM3BXY9WgPbcHF78swAAVlA4IEAAAACwBQCdASpkAGQAPpFIoUylpCMiIKgAsBIJaW7hc+AAY2upvcReWAa6m9xF5YBrqb3EXlgGngAA/v81aVcAAAAA",this._accounts=[],this._chains=["sui:mainnet","sui:testnet","sui:devnet"],this.walletMessageManager=void 0,this.uiMessageManager=void 0,this.internalEventEmitter=new i,this.changeListeners=new Set;const s=null!=(n=t.useStaging)&&n;this.walletMessageManager=new A(e,s),this.uiMessageManager=new f,t.referralCode&&this.walletMessageManager.pingIframe().then(()=>{this.postRequestAndWait({method:r.set_points_referral_code,params:[t.referralCode],interactionRequired:!1}).catch(e=>console.error("Error setting referral code:",e))}),t.project&&this.walletMessageManager.pingIframe().then(()=>{this.postRequestAndWait({method:r.set_project,params:[t.project,window.location.origin],interactionRequired:!1}).catch(e=>console.error("Error setting project:",e))}),t.config&&this.walletMessageManager.pingIframe().then(()=>{this.postRequestAndWait({method:r.set_custom_config,params:[t.config],interactionRequired:!1}).catch(e=>console.error("Error setting custom config:",e))}),this.walletMessageManager.addListener({handleResponse:e=>{this.internalEventEmitter.emit(e.id,e)},handleRequest:e=>{e.method===r.show_modal?this.uiMessageManager.emit(w.show_modal):e.method===r.hide_modal&&this.uiMessageManager.emit(w.hide_modal)},onAccountChanged:async function(e){try{const e=await a.refreshAccounts();a.notifyChange({accounts:e.accounts})}catch(e){console.error("Failed to refresh Sui accounts:",e),a._accounts=[],a.notifyChange({accounts:[]})}}})}async refreshAccounts(){try{var e;await this.walletMessageManager.pingIframe();const t=await this.postRequestAndWait({method:"sui_connect",params:[{silent:!0}],interactionRequired:!1});if(t.error)return this._accounts=[],{accounts:[]};const n=(null==(e=t.data)?void 0:e.accounts)||[];return this._accounts=n,{accounts:this._accounts}}catch(e){return this._accounts=[],{accounts:[]}}}get chains(){return this._chains}get accounts(){return this._accounts}get ui(){return this.uiMessageManager}async connect(e){var t;await this.walletMessageManager.pingIframe();const n=await this.postRequestAndWait({method:"sui_connect",params:[e||{}],interactionRequired:!(null!=e&&e.silent)});if(n.error)throw new Error(n.error.message||"Failed to connect");const i=(null==(t=n.data)?void 0:t.accounts)||[];return this._accounts=i,this.notifyChange({accounts:this._accounts}),{accounts:this._accounts}}async disconnect(){await this.walletMessageManager.pingIframe(),await this.postRequestAndWait({method:"sui_disconnect",params:[],interactionRequired:!1}),this._accounts=[],this.notifyChange({accounts:[]})}async signPersonalMessage(e){await this.walletMessageManager.pingIframe();const t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw new Error(`Account ${t} is not connected`);const n=await this.postRequestAndWait({method:"sui_signPersonalMessage",params:[{message:Array.from(e.message),account:t,chain:e.chain}],interactionRequired:!0});if(n.error)throw new Error(n.error.message||"Failed to sign message");return{bytes:n.data.bytes,signature:n.data.signature}}async resolveTransactionBytes(e,t="sui:mainnet"){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return new Uint8Array(e);if("string"!=typeof e){if(e&&"object"==typeof e){if("function"==typeof e.build)try{const{getFullnodeUrl:n,SuiClient:i}=await import("@mysten/sui/client");let a="mainnet";"sui:testnet"===t?a="testnet":"sui:devnet"===t?a="devnet":"sui:localnet"===t&&(a="localnet");const s=new i({url:n(a)});return await e.build({client:s})}catch(e){throw console.warn("[SuiWallet] Failed to build transaction object:",e),new Error(`Failed to build transaction: ${e instanceof Error?e.message:String(e)}`)}if("function"==typeof e.serialize)try{const t=await e.serialize();if("string"==typeof t)return Uint8Array.from(atob(t),e=>e.charCodeAt(0));if(t instanceof Uint8Array)return t}catch(e){console.warn("[SuiWallet] serialize() failed:",e)}if("function"==typeof e.toJSON)try{const t=await e.toJSON();if("string"==typeof t)try{return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}catch(e){try{const e=JSON.parse(t);if(e.bytes&&"string"==typeof e.bytes)return Uint8Array.from(atob(e.bytes),e=>e.charCodeAt(0))}catch(e){}}}catch(e){console.warn("[SuiWallet] toJSON() failed:",e)}if("function"==typeof e.getData)try{const t=e.getData();if(t instanceof Uint8Array)return t}catch(e){console.warn("[SuiWallet] getData() failed:",e)}throw new Error(`Unsupported transaction format. Keys: ${Object.keys(e).join(", ")}`)}throw new Error(`Unsupported transaction format: ${typeof e}. Please pass Uint8Array bytes or a Transaction object.`)}try{return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}catch(e){throw new Error("Transaction string must be base64 encoded bytes. If you have a serialized transaction JSON, please build it to bytes first.")}}async signTransaction(e){await this.walletMessageManager.pingIframe();const t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw new Error(`Account ${t} is not connected`);const n=await this.resolveTransactionBytes(e.transaction,e.chain),i=await this.postRequestAndWait({method:"sui_signTransaction",params:[{transaction:Array.from(n),account:t,chain:e.chain}],interactionRequired:!0});if(i.error)throw new Error(i.error.message||"Failed to sign transaction");return{bytes:i.data.bytes,signature:i.data.signature}}async signAndExecuteTransaction(e){await this.walletMessageManager.pingIframe();const t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw new Error(`Account ${t} is not connected`);const n=await this.resolveTransactionBytes(e.transaction,e.chain),i=await this.postRequestAndWait({method:"sui_signAndExecuteTransaction",params:[{transaction:Array.from(n),account:t,chain:e.chain,options:e.options,requestType:e.requestType}],interactionRequired:!0});if(i.error)throw new Error(i.error.message||"Failed to sign and execute transaction");return i.data}async switchChain(e){if(await this.walletMessageManager.pingIframe(),!this._chains.includes(e.chain))throw new Error(`Chain ${e.chain} is not supported`);const t=await this.postRequestAndWait({method:"sui_switchChain",params:[e],interactionRequired:!1});if(t.error)throw new Error(t.error.message||"Failed to switch chain");this.notifyChange({chains:this._chains,accounts:this._accounts})}on(e,t){return"change"===e?(this.changeListeners.add(t),()=>{this.changeListeners.delete(t)}):()=>{}}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)},"sui:signPersonalMessage":{version:"1.1.0",signPersonalMessage:this.signPersonalMessage.bind(this)},"sui:signTransaction":{version:"2.0.0",signTransaction:this.signTransaction.bind(this)},"sui:signAndExecuteTransaction":{version:"1.0.0",signAndExecuteTransaction:this.signAndExecuteTransaction.bind(this)},"sui:signTransactionBlock":{version:"2.0.0",signTransactionBlock:this.signTransactionBlock.bind(this)},"sui:signAndExecuteTransactionBlock":{version:"1.0.0",signAndExecuteTransactionBlock:this.signAndExecuteTransactionBlock.bind(this)},"sui:switchChain":{version:"1.0.0",switchChain:this.switchChain.bind(this)}}}async signTransactionBlock(e){return this.signTransaction({transaction:e.transactionBlock,account:e.account,chain:e.chain})}async signAndExecuteTransactionBlock(e){return this.signAndExecuteTransaction({transaction:e.transactionBlock,account:e.account,chain:e.chain,options:e.options,requestType:e.requestType})}async requestEmail(){await this.walletMessageManager.pingIframe();const e=await this.postRequestAndWait({method:r.silk_requestEmail,params:[],interactionRequired:!0});if(e.error)throw new Error(e.error.message||"Failed to request email");return e.data}async postRequestAndWait(e){const t=await this.walletMessageManager.postSilkRequest({method:e.method,params:e.params,interactionRequired:e.interactionRequired});return new Promise(e=>{this.internalEventEmitter.once(t,t=>{e(t)})})}notifyChange(e){Array.from(this.changeListeners).forEach(t=>{t(e)})}}const H="waap-wallet-iframe-container",G="waap-wallet-iframe",$=()=>document.getElementById(H)||document.getElementById("silk-wallet-iframe-container"),K="waap-wallet-iframe-wrapper";function Q(n={}){var i;(n=>{if($())return;const i=document.createElement("div");i.id=H,i.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n width: 100%;\n height: 100%;\n display: none;\n align-items: center;\n justify-content: center;\n background-color: rgba(0, 0, 0, 0.5);\n z-index: 9999999999;\n ";const a=document.createElement("div");a.id=K,a.style.cssText="\n position: relative;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 0;\n margin: 0;\n height: 600px;\n width: 380px;\n ",i.appendChild(a);const s=document.createElement("iframe");s.id=G,s.src=`${n?e:t}/iframe`,s.style.cssText="\n width: 100%;\n height: 100%;\n border: none;\n border-radius: 24px;\n background: transparent;\n ",a.appendChild(s),(n=>{window.addEventListener("message",i=>{if(i.origin!==(n?e:t))return;if(!i.data||"object"!=typeof i.data)return;if("silk-iframe-size"!==i.data.type)return;const a=i.data.height,s=i.data.width;if("number"!=typeof a||"number"!=typeof s)return;if(a<50||a>2e3)return;if(s<50||s>2e3)return;if(!Number.isFinite(a)||!Number.isFinite(s))return;const o=document.getElementById(K)||document.getElementById("silk-wallet-iframe-wrapper");o&&(o.style.height=`${Math.floor(a)}px`,o.style.width=`${Math.floor(s)}px`)})})(n),document.body.appendChild(i)})(null!=(i=n.useStaging)&&i);const a=$(),s=document.getElementById(G)||document.getElementById("silk-wallet-iframe");if(!a||!s)throw new Error("Failed to create WaaP iframe");const o=new U(s.contentWindow,n);return o.ui.on(w.show_modal,()=>{a.style.display="flex",document.querySelectorAll('[data-dapp-kit][class*="overlay"]').forEach(e=>{e.style.display="none"})}),o.ui.on(w.hide_modal,()=>{a.style.display="none",document.querySelectorAll('[data-dapp-kit][class*="overlay"]').forEach(e=>{e.style.display=""})}),o}function V(e,t={}){const n=new U(e,t);return d(n),n}function X(e){const[t,n]=u(new Map),i=h(e);g(()=>{i.current=e},[e]),g(()=>{const e=window.waap||window.silk;if(!e)return void console.warn("[useWaapTransaction] WaaP provider not found. Make sure initWaaP() was called.");const t=e=>{var t;n(t=>{const n=new Map(t);return n.set(e.txHash,{status:"signed",txHash:e.txHash,pendingTxId:e.txHash,signature:e.signature,serializedTx:e.serializedTx}),n}),null==(t=i.current)||null==t.onSigned||t.onSigned(e)},a=e=>{var t;n(t=>{const n=new Map(t),i=n.get(e.txHash);return i&&n.set(e.txHash,p({},i,{status:"tx_pending"})),n}),null==(t=i.current)||null==t.onTxPending||t.onTxPending(e)},s=e=>{var t;n(t=>{const n=new Map(t),i=n.get(e.txHash);return i&&n.set(e.txHash,p({},i,{status:"confirmed",receipt:e.receipt})),n}),null==(t=i.current)||null==t.onConfirmed||t.onConfirmed(e)},o=e=>{var t;n(t=>{const n=new Map(t),i=n.get(e.txHash);return i&&n.set(e.txHash,p({},i,{status:"failed",error:e.error,stage:e.stage})),n}),null==(t=i.current)||null==t.onFailed||t.onFailed(e)};return e.on("waap_sign_complete",t),e.on("waap_tx_pending",a),e.on("waap_tx_confirmed",s),e.on("waap_tx_failed",o),()=>{null==e.removeListener||e.removeListener("waap_sign_complete",t),null==e.removeListener||e.removeListener("waap_tx_pending",a),null==e.removeListener||e.removeListener("waap_tx_confirmed",s),null==e.removeListener||e.removeListener("waap_tx_failed",o)}},[]);const a=m(async e=>{const t=window.waap||window.silk;if(!t)throw new Error("WaaP provider not found");return t.request({method:"eth_sendTransaction",params:e})},[]),s=m(async e=>{const t=window.waap||window.silk;if(!t)throw new Error("WaaP provider not found");return t.request({method:"eth_signTransaction",params:e})},[]),o=Array.from(t.values()).some(e=>"signed"===e.status||"tx_pending"===e.status);return{sendTransaction:a,signTransaction:s,pendingTransactions:t,isAnyPending:o}}export{C as EthereumProvider,J as EthereumProviderExtension,M as SilkWalletConnect,f as UIMessageManager,w as UI_EVENT_NAMES,T as WaaP,U as WaaPSuiWallet,M as WaaPWalletConnect,A as WalletMessageManager,y as handleWalletRequestAndResponse,z as initWaaP,Q as initWaaPSui,V as registerWaaPSuiWallet,X as useWaapTransaction};
1
+ import{silkWalletAppOrigin2Staging as e,silkWalletAppOrigin2 as t,rpcMethodRequiresUI as n}from"@human.tech/waap-constants";export{rpcMethodRequiresUI}from"@human.tech/waap-constants";import{EventEmitter as i}from"events";import{SILK_MESSAGE_TYPE as a,SILK_NOTIFICATION as s,generateMessageId as o,SILK_METHOD as r,JSON_RPC_METHOD as c}from"@human.tech/waap-interface-core";export{SILK_METHOD,SILK_METHOD as WAAP_METHOD}from"@human.tech/waap-interface-core";import{EthersAdapter as l}from"@reown/appkit-adapter-ethers";import{registerWallet as d}from"@mysten/wallet-standard";import{useState as u,useRef as h,useEffect as g,useCallback as m}from"react";function p(){return p=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},p.apply(null,arguments)}var w;!function(e){e.show_modal="show_modal",e.hide_modal="hide_modal"}(w||(w={}));class f extends i{constructor(){super()}}async function y(e,t,n,i,a){const s=e.method,o=e.params,r=await n.postSilkRequest({method:s,params:o,interactionRequired:t,silkOptions:a});return new Promise((e,t)=>{i.once(r,n=>{n.error?t(n.error):e(n.data)})})}const v={styles:{darkMode:!1}};class M{static setProjectId(e){this.projectId=e}static getProjectIdFromEnv(){try{if("undefined"!=typeof process&&process.env)return process.env.NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID||process.env.VITE_WALLET_CONNECT_PROJECT_ID||process.env.REACT_APP_WALLET_CONNECT_PROJECT_ID||process.env.WALLET_CONNECT_PROJECT_ID}catch(e){return}}static async getInstance(){if("undefined"==typeof window||"undefined"==typeof document)return null;const{createAppKit:e}=await import("@reown/appkit"),{mainnet:t,sepolia:n,optimism:i,arbitrum:a,polygon:s,gnosis:o,avalanche:r,aurora:c,fantom:d,base:u,celo:h}=await import("@reown/appkit/networks");try{const g={name:"Human Wallet",description:"Silk lets you create human keys for web3 wallets that are recoverable with private identity proofs and secured by zero trust protocols.",url:window.location.origin,icons:["https://imagedelivery.net/_aTEfDRm7z3tKgu9JhfeKA/f11f5753-616a-4aa0-2aee-9b75befea700/sm"]},m=this.projectId||this.getProjectIdFromEnv();return m?(this.projectId=m,this.instance||(this.instance=e({adapters:[new l],projectId:m,metadata:g,networks:[t,n,a,i,s,o,r,c,d,u,h],features:{socials:!1,email:!1}})),this.instance):(console.error('WalletConnect project ID not found. Please set it using one of these methods:\n1. Pass walletConnectProjectId when calling initSilk\n2. Call SilkWalletConnect.setProjectId("your-project-id")\n3. Set WALLET_CONNECT_PROJECT_ID (NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID for Next projects) environment variable'),null)}catch(e){return console.error("Error importing or initializing WalletConnect:",e),null}}static async listenToAccountChangeEvent(){await new Promise(e=>{this.instance.subscribeAccount(t=>{null!=t&&t.isConnected&&e()})})}static async waitForReadyAndCheckConnection(){if(!this.instance)return!1;let e=!1,t=0;for(;!e&&t<15;){const n=t<5?500:1e3;await new Promise(e=>setTimeout(e,n)),e=this.instance.getIsConnectedState(),t++,console.log(`WalletConnect connection check attempt ${t}: ${e}`)}return e}static isConnected(){var e,t;return null!=(e=null==(t=this.instance)?void 0:t.getIsConnectedState())&&e}static getWalletProvider(){var e,t;return null!=(e=null==(t=this.instance)?void 0:t.getWalletProvider())?e:null}}M.instance=null,M.projectId=void 0,M.chains=[1,10,100,137,8453,43114,42161,42220,84532,11155111];const E=["silkOptions"];class A{constructor(n,i){this.iframeWindow=null,this.walletOrigin=void 0,this.iframeWindow=n,this.walletOrigin=i?e:t}postSilkNotification(e){this.iframeWindow.postMessage({target:"silk",messageType:a.notification,data:e},this.walletOrigin)}postReadyNotification(){this.postSilkNotification(s.ready)}postConnectNotification(){this.postSilkNotification(s.connect)}pingIframe(){return new Promise((e,t)=>{setTimeout(()=>t("Wallet ping timed out."),1e4);const n=t=>{"silk"===t.data.target&&t.data.messageType===a.notification&&t.data.data===s.ready&&(window.removeEventListener("message",n),e())};window.addEventListener("message",n),this.postReadyNotification()})}async postSilkRequest(e){const{silkOptions:t}=e,n=p({},function(e,t){if(null==e)return{};var n={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;n[i]=e[i]}return n}(e,E),{target:"silk",messageType:a.request},t&&{silkOptions:t}),i=await o(n);return this.iframeWindow.postMessage(p({},n,{id:i}),this.walletOrigin),i}addListener(e){const{handleResponse:t,handleRequest:n,onReceiveConnectNotif:i,onAccountChanged:o,onAsyncTxNotification:r}=e;window.addEventListener("message",e=>{var c,l,d;try{if("undefined"!=typeof process&&process,e.origin!==this.walletOrigin)return}catch(t){if(e.origin!==this.walletOrigin)return}if((null==(c=e.data)?void 0:c.messageType)===a.request)n(e.data);else if((null==(l=e.data)?void 0:l.messageType)===a.response)t(e.data);else if((null==(d=e.data)?void 0:d.messageType)===a.notification){var u,h,g,m;(null==(u=e.data)?void 0:u.data)===s.connect?null==i||i():(null==(h=e.data)||null==(h=h.data)?void 0:h.type)===s.account_changed&&o?o(e.data.data.account):(null!=(g=e.data)&&null!=(g=g.data)&&null!=(g=g.type)&&g.startsWith("waap_sign_")||null!=(m=e.data)&&null!=(m=m.data)&&null!=(m=m.type)&&m.startsWith("waap_tx_"))&&r&&r({type:e.data.data.type,payload:e.data.data.payload})}})}}const b=["waap","human","injected","walletconnect"];class C extends i{constructor(e,t,n,a,s,o=!1,c=!1){super(),this.isSilk=!0,this.isWaaP=!0,this.connected=!1,this.walletMessageManager=void 0,this.uiMessageManager=void 0,this.config=void 0,this.currentAccount=null,this.walletConnectProvider=null,this.asyncTxs=!1,this.legacyAsyncSigning=!1,this.persistedMethods=void 0,this.internalEventEmitter=new i,this.asyncTxs=o,this.legacyAsyncSigning=c,this.uiMessageManager=new f,this.walletMessageManager=new A(e,!!s),this.config=p({},v,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),orcid:this.orcid.bind(this),enable:this.enable.bind(this),isConnected:this.isConnected.bind(this),toggleDarkMode:this.toggleDarkMode.bind(this),silkRequest:this.request.bind(this),waaPRequest:this.request.bind(this)},this.walletMessageManager.addListener({onReceiveConnectNotif:()=>{console.log("onReceiveConnectNotif"),this.connected=!0,this.emit("connect")},handleResponse:e=>this.internalEventEmitter.emit(e.id,e),handleRequest:e=>{e.method===r.show_modal?this.uiMessageManager.emit(w.show_modal):e.method===r.hide_modal&&this.uiMessageManager.emit(w.hide_modal)},onAccountChanged:e=>{this.currentAccount!==e&&(this.currentAccount=e,this.emit("accountsChanged",e?[e]:[]))},onAsyncTxNotification:e=>{this.emit(e.type,e.payload)}}),t&&this.walletMessageManager.pingIframe().then(()=>y({method:r.set_points_referral_code,params:[t]},!1,this.walletMessageManager,this.internalEventEmitter)).catch(e=>{console.error("Error setting referral code in Silk iframe:",e)}),a&&(console.log(" =========== project =========== ",a),this.walletMessageManager.pingIframe().then(()=>y({method:r.set_project,params:[a,window.location.origin]},!1,this.walletMessageManager,this.internalEventEmitter))),n&&this.walletMessageManager.pingIframe().then(()=>y({method:r.set_custom_config,params:[n]},!1,this.walletMessageManager,this.internalEventEmitter)).catch(e=>{console.error("Error setting custom config in Silk iframe:",e)})}async initializeWalletConnect(){try{this.walletConnectProvider=await M.getInstance(),console.log("WalletConnect provider initialized")}catch(e){console.error("Failed to initialize WalletConnect provider:",e),this.walletConnectProvider=null}}async enable(){return this.request({method:"eth_requestAccounts"})}isConnected(){return this.connected}async request(e){if(!Object.keys(c).includes(e.method))return Promise.reject({error:`Not implemented (${e.method})`});const t=await this.attemptAutoConnect(e.method);if(null!==t)return t;if(function(e){try{var t;if(!e||!Array.isArray(e))return!1;const n=JSON.parse("string"==typeof e[1]?e[1]:JSON.stringify(e[1]));return"SafeTx"===n.primaryType&&void 0!==(null==(t=n.domain)?void 0:t.verifyingContract)&&n.message&&"to"in n.message&&"value"in n.message&&"safeTxGas"in n.message&&"baseGas"in n.message&&"gasPrice"in n.message&&"nonce"in n.message}catch(e){return!1}}(e.params)&&e.method!==c.eth_signTypedData_v4)return Promise.reject({error:"Safe transactions must be signed using eth_signTypedData_v4"});await this.walletMessageManager.pingIframe();const i=(e.method===c.eth_sendTransaction||e.method===c.eth_signTransaction||e.method===c.eth_signTypedData_v4||e.method===c.personal_sign)&&this.asyncTxs||e.async,a=i||e.withPT?this.legacyAsyncSigning?{asyncSigning:i||void 0,withPT:e.withPT}:{async:i,withPT:e.withPT}:void 0,s=await y(e,n(e.method),this.walletMessageManager,this.internalEventEmitter,a);if((e.method===c.wallet_switchEthereumChain||e.method===c.wallet_addEthereumChain)&&null===s){var o;this.emit("chainChanged",null==(o=e.params)||null==(o=o[0])?void 0:o.chainId);try{const t=await this.request({method:"eth_accounts"});var r,l;t&&t.length>0&&(this.currentAccount=t[0],this.emit("accountsChanged",t),this.emit("connect",{chainId:null==(r=e.params)||null==(r=r[0])?void 0:r.chainId}),console.log("[EthereumProvider] Re-emitted accounts and connect after chain switch:",{accounts:t,chainId:null==(l=e.params)||null==(l=l[0])?void 0:l.chainId}))}catch(t){var d;console.warn("[EthereumProvider] Failed to get accounts after chain switch:",t),this.currentAccount&&(this.emit("accountsChanged",[this.currentAccount]),this.emit("connect",{chainId:null==(d=e.params)||null==(d=d[0])?void 0:d.chainId}))}}return s}async login(e){var t;if("undefined"==typeof window||"undefined"==typeof document)return null;null!=(t=this.config.authenticationMethods)&&t.includes("wallet")&&!this.walletConnectProvider&&await this.initializeWalletConnect();const n=e||window.ethereum,i=n&&function(e){return!(null==e||!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)}(n)?"MetaMask":"Browser Wallet";await this.walletMessageManager.pingIframe();const a=function(e){if(null==e)return null;if("string"==typeof e){if(b.includes(e))return e;throw new Error(`[EthereumProvider] Unexpected login method: "${e}". Expected one of: ${b.join(", ")}`)}if("object"==typeof e&&"loginMethod"in e&&"string"==typeof e.loginMethod){const t=e.loginMethod;if(console.warn(`[EthereumProvider] Received object login response. Normalizing "${t}" to string. This is unexpected for the web SDK.`),b.includes(t))return t;throw new Error(`[EthereumProvider] Unknown loginMethod in object: "${t}". Expected one of: ${b.join(", ")}`)}throw new Error(`[EthereumProvider] Unexpected login response: ${JSON.stringify(e)} (type: ${typeof e})`)}(await y({method:r.login,params:[i]},!0,this.walletMessageManager,this.internalEventEmitter));if(null===a)return null;switch(a){case"waap":case"human":localStorage.setItem(`${window.location.origin}-connected`,"waap"),this.setupWaaP();break;case"injected":n&&(localStorage.setItem(`${window.location.origin}-connected`,"injected"),this.setupInjectedWallet(n));break;case"walletconnect":{localStorage.setItem(`${window.location.origin}-connected`,"walletconnect"),M.isConnected()||(await this.walletConnectProvider.open({view:"Connect"}),await M.listenToAccountChangeEvent());const e=M.getWalletProvider();this.setupWalletConnect(e);break}}return a}async logout(){await this.walletMessageManager.pingIframe(),this.cleanupInvalidLoginState();try{this.walletConnectProvider&&await this.walletConnectProvider.disconnect()}catch(e){console.error("Error disconnecting from WalletConnect:",e)}return y({method:r.logout},!1,this.walletMessageManager,this.internalEventEmitter)}cleanupInvalidLoginState(){try{localStorage.removeItem(`${window.location.origin}-connected`)}catch(e){console.warn("Could not clean up login state:",e)}}setupWaaP(){const e=p({},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){var t,n,i,a,s;const o=p({},this.persistedMethods,e,{isSilk:!0,connected:null!=(t=e.connected)&&t,on:null!=(n=null==(i=e.on)?void 0:i.bind(e))?n:()=>{},removeListener:null!=(a=null==(s=e.removeListener)?void 0:s.bind(e))?a:()=>{},request:e.request.bind(e)});window.silk=o,window.waap=o}setupWalletConnect(e){var t,n,i,a;const s=p({},this.persistedMethods,e,{isSilk:!0,connected:!0,on:null!=(t=null==(n=e.on)?void 0:n.bind(e))?t:()=>{},removeListener:null!=(i=null==(a=e.removeListener)?void 0:a.bind(e))?i:()=>{},request:e.request.bind(e)});window.silk=s,window.waap=s}setupAutoConnectInjected(e){var t,n,i,a,s;const o=p({},this.persistedMethods,e,{isSilk:!1,connected:null!=(t=null==e.isConnected?void 0:e.isConnected())&&t,on:null!=(n=null==(i=e.on)?void 0:i.bind(e))?n:()=>{},removeListener:null!=(a=null==(s=e.removeListener)?void 0:s.bind(e))?a:()=>{},request:e.request.bind(e)});window.silk=o,window.waap=o}setupAutoConnectWalletConnect(e){var t,n,i,a;const s=p({},this.persistedMethods,e,{isSilk:!1,connected:!0,on:null!=(t=null==(n=e.on)?void 0:n.bind(e))?t:()=>{},removeListener:null!=(i=null==(a=e.removeListener)?void 0:a.bind(e))?i:()=>{},request:e.request.bind(e)});window.silk=s,window.waap=s}async attemptAutoConnect(e){var t=this;if("eth_requestAccounts"!==e&&"eth_accounts"!==e)return null;this.walletMessageManager.pingIframe().then(async function(){await y({method:r.auto_conn,params:[window.location.origin]},!1,t.walletMessageManager,t.internalEventEmitter)});const n=this.getLoginMethod();if("injected"===n&&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("walletconnect"===n)try{if(this.walletConnectProvider||(this.walletConnectProvider=await M.getInstance()),await M.waitForReadyAndCheckConnection()){const e=M.getWalletProvider();return this.setupAutoConnectWalletConnect(e),e.request({method:"eth_requestAccounts"})}return console.log("WalletConnect not connected, cleaning up and falling through to normal flow"),this.cleanupInvalidLoginState(),null}catch(e){return console.warn("WalletConnect auto-connect failed:",e),this.cleanupInvalidLoginState(),null}return null}getLoginMethod(){if("undefined"==typeof window||"undefined"==typeof localStorage)return null;try{const 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 M.isConnected()?"walletconnect":(this.cleanupInvalidLoginState(),null)}catch(e){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,this.walletMessageManager.pingIframe().then(()=>y({method:r.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(){this.walletMessageManager.pingIframe().then(()=>y({method:r.safe},!0,this.walletMessageManager,this.internalEventEmitter))}async orcid(){this.walletMessageManager.pingIframe().then(()=>y({method:r.orcid},!0,this.walletMessageManager,this.internalEventEmitter))}async portal(e,t,n){let i;switch(await this.walletMessageManager.pingIframe(),t){case"get":i="gastank"===e?r.gastank_get_settings:r.customization_get;break;case"update":i="gastank"===e?r.gastank_update_settings:r.customization_update;break;case"topup":i=r.gastank_topup;break;case"init":i=r.project_init}return y({method:i,params:[n,window.location.origin]},"get"!==t&&"customization"!==e,this.walletMessageManager,this.internalEventEmitter)}async requestEmail(){return await this.walletMessageManager.pingIframe(),y({method:r.silk_requestEmail},!0,this.walletMessageManager,this.internalEventEmitter)}async requestPermissionToken(e){return await this.walletMessageManager.pingIframe(),y({method:r.waap_requestPermissionToken,params:[e]},!0,this.walletMessageManager,this.internalEventEmitter)}async requestSBT(e){return await this.walletMessageManager.pingIframe(),y({method:r.silk_requestSbt,params:[e]},!0,this.walletMessageManager,this.internalEventEmitter)}}const _="waap-wallet",k="waap-component-container",I="undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof HTMLElement;let T;function x(){return!(!I||!document.getElementById(k)&&!document.querySelector(_))}function P(){return I?document.getElementById(k)||document.querySelector(_):null}I?(T=class extends HTMLElement{constructor(){super(),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=k}connectedCallback(){this.setAttribute("data-waap-mounted","true")}disconnectedCallback(){this.removeAttribute("data-waap-mounted")}},"undefined"==typeof customElements||customElements.get(_)||customElements.define(_,T)):T=class{};const S="waap-wallet-iframe-container",q="waap-wallet-iframe-wrapper",W="waap-wallet-iframe",L=()=>document.getElementById(S)||document.getElementById("silk-wallet-iframe-container"),R=()=>document.getElementById(q)||document.getElementById("silk-wallet-iframe-wrapper"),j=()=>document.getElementById(W)||document.getElementById("silk-wallet-iframe"),O=S,N=q,B=W,D=n=>{const i=window.document.createElement("iframe");return i.id=B,i.src=`${n?e:t}/iframe`,console.log("iframe.src: ",i.src),i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.borderRadius="24px",i.style.backgroundColor="transparent",i.style.background="transparent",i.style.padding="0",i.style.margin="0",i},F=(n,i)=>{const a=i=>{if(i.origin!==(n?e:t))return;if(!i.data||"object"!=typeof i.data)return;if("silk-iframe-size"!==i.data.type)return;const a=i.data.height,s=i.data.width;if("number"!=typeof a||"number"!=typeof s)return;if(a<50||a>2e3)return;if(s<50||s>2e3)return;if(!Number.isFinite(a)||!Number.isFinite(s))return;const o=R();o&&(o.style.height=`${Math.floor(a)}px`,o.style.width=`${Math.floor(s)}px`)};window.addEventListener("message",a),i.__silkCleanup=()=>{window.removeEventListener("message",a)}},z=(e={})=>{var t;t=!!e.useStaging,x()?(e=>{const t=P();if(!t)throw new Error("WaaP component not found in DOM");if(j())return;const n=window.document.createElement("div");n.id=N,n.style.position="relative",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0",n.style.margin="0",n.style.height="600px",n.style.width="380px";const i=D(e);F(e,i),setTimeout(()=>{const e=R();e&&(e.style.height="600px",e.style.width="380px")},100),n.appendChild(i),t.appendChild(n)})(t):(e=>{if(L())return;const t=window.document.createElement("div");t.id=O,t.style.position="fixed",t.style.top="0",t.style.left="0",t.style.right="0",t.style.bottom="0",t.style.width="100%",t.style.height="100%",t.style.display="flex",t.style.alignItems="center",t.style.justifyContent="center",t.style.backgroundColor="rgba(0, 0, 0, 0.5)",t.style.zIndex="9999999999",t.style.display="none";const n=window.document.createElement("div");n.id=N,n.style.position="relative",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0",n.style.margin="0",n.style.height="600px",n.style.width="380px",t.appendChild(n);const i=D(e);F(e,i),setTimeout(()=>{const e=R();e&&(e.style.height="600px",e.style.width="380px")},100),n.appendChild(i),window.document.body.appendChild(t)})(t);const n=j();if(!n)throw new Error("WaaP iframe does not exist on page");const i=x();e.walletConnectProjectId&&M.setProjectId(e.walletConnectProjectId);const{referralCode:a,config:s,project:o,asyncTxs:r,asyncSigning:c}=e;c&&!r&&console.warn("[WaaP SDK] `asyncSigning` is deprecated. Use `asyncTxs` instead.");const l=new C(n.contentWindow,a,s||{},o||{},e.useStaging,r||c||!1,!!c&&!r);let d=i?"component":"modal";return l.uiMessageManager.on(w.show_modal,()=>{const e=x(),t=e?"component":"modal",n=R();if(t!==d&&n)if(d=t,e){const e=P();e&&e.appendChild(n)}else{let e=L();e||(e=window.document.createElement("div"),e.id=O,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.display="flex",e.style.alignItems="center",e.style.justifyContent="center",e.style.backgroundColor="rgba(0, 0, 0, 0.5)",e.style.zIndex="9999999999",window.document.body.appendChild(e)),e.appendChild(n)}const i=L();e&&n?n.style.display="flex":i&&(i.style.display="flex")}),l.uiMessageManager.on(w.hide_modal,()=>{const e=x(),t=R(),n=L();e&&t?t.style.display="none":n&&(n.style.display="none")}),window.silk=l,window.waap=l,l};class J extends i{constructor(e){super(),this.isSilk=!0,this.connected=!1,this.config=void 0,this.config=p({},v,e||{})}sendToExtension(e){return new Promise((t,n)=>{window.postMessage({type:"FROM_PAGE",request:e},"*"),window.addEventListener("message",e=>{"FROM_EXTENSION"===e.data.type&&(e.data.error?n(e.data.error):t(e.data.result))})})}async request(e){if(!Object.keys(c).includes(e.method))return Promise.reject({error:`Not implemented (${e.method})`});const t=await this.sendToExtension(e);var n;return e.method!==c.wallet_switchEthereumChain&&e.method!==c.wallet_addEthereumChain||null!==t||this.emit("chainChanged",null==(n=e.params)||null==(n=n[0])?void 0:n.chainId),t}async enable(){return this.request({method:"eth_requestAccounts"})}isConnected(){return this.connected}async login(){return this.sendToExtension({method:r.login})}async requestSBT(e){return this.sendToExtension({method:r.silk_requestSbt,params:[e]})}async toggleDarkMode(){this.config.styles.darkMode=!this.config.styles.darkMode,await this.sendToExtension({method:r.set_custom_config,params:[this.config]})}async safe(){return this.sendToExtension({method:r.safe})}}class U{constructor(e,t={}){var n,a=this;this.name="WaaP",this.version="1.0.0",this.icon="data:image/webp;base64,UklGRpoDAABXRUJQVlA4WAoAAAAQAAAAYwAAYwAAQUxQSDMDAAABJyAQSOFmFxERA8TatqpGoimANbEAxlBAPhSgQP9FyXv3vkcFEf134EZS5DREhGvTM8z0ki8stMRvK4cm8bk5rIu3xNbvkgPk4K6ti5IHquRQnLi6KrdBb81hdyF1jTLM1CW425943iba38/djOcG+dg85p/KXGd/g7+xAzJ2VPWTS8R+q65uA1ZcwG3iZ4urjw9Lh4xn83n3gZmQQ3VMVGEO6D403jdr81Ml1OISAAf7RGImBHISwQ5zCJonTuEyOyP7Sga4cDcjMPgXuiK9cUpaGrIDJtH4iAB25utB8O0DDztOKTr8u9hpX0jrx6k8UM5eAlqsynNxlX9tPRLQEtySKwcDOIDnMqEcek1UnylVNac4r0mlypNvhmCNODlhUXuT4fxTQyrDKY0uyV+gi0iiLLpY76A08C/IX8GQoYb8PcVxK7HkZkT5IjAF4gZicOfJW1ovJjyAlYVPlM6BkkHGI0fniAIZIXC0CbAM92BB8SBznU0ITYLr9XkfnKlDgV8170HGMWwitY51+zxcgkftLD4RLh4HSTIa3QzRWKxlaHZTz21s6GLxnBmjogkVilW4kuaMMMGUfgkZ1JhrBSEANrEDMwucAXgbTqIExY3FYRMdtkQRDFjD6BKtJ2GWTopGRY4P9DBkdE4rp9LJHuYhju45oeVZVv3zNmVdZiIOffHDppOz0Q34p0e/+nXy7JmF1846lmF2ZombLt8pgZpbPNeqpJSVJ0bGd4cH8dUNflNPfdQVXUkC95UQS0ZGfDmOJgjs3IyVOExZBEsxONd080gYK/ftQ2nbYaqGW89Hu7M6avmzXEjhO4G8O8ae8gwWtwZsyp8v8j/ys5H7bM+unOfurO4bbbL4v865Nb8s98Ld2X9yg6tLBQanMP8fhplOMMN8fiNDzTvNOMXGuYzejo12vY7s3clhXwgDPuBIcxi9QZftbKVxAjLCcVQdRxGR1QknhCs3GuieMLzfrrC9RhfJgVpcXRn71nZfEjsiYy/Ca1J7ch0clK64ReH3G/s2cekpP+BIx2YteMvSoLy6G9FCgd1nvF/VoVRtJoNJNLQ0RM3BXY9WgPbcHF78swAAVlA4IEAAAACwBQCdASpkAGQAPpFIoUylpCMiIKgAsBIJaW7hc+AAY2upvcReWAa6m9xF5YBrqb3EXlgGngAA/v81aVcAAAAA",this._accounts=[],this._chains=["sui:mainnet","sui:testnet","sui:devnet"],this.walletMessageManager=void 0,this.uiMessageManager=void 0,this.internalEventEmitter=new i,this.changeListeners=new Set;const s=null!=(n=t.useStaging)&&n;this.walletMessageManager=new A(e,s),this.uiMessageManager=new f,t.referralCode&&this.walletMessageManager.pingIframe().then(()=>{this.postRequestAndWait({method:r.set_points_referral_code,params:[t.referralCode],interactionRequired:!1}).catch(e=>console.error("Error setting referral code:",e))}),t.project&&this.walletMessageManager.pingIframe().then(()=>{this.postRequestAndWait({method:r.set_project,params:[t.project,window.location.origin],interactionRequired:!1}).catch(e=>console.error("Error setting project:",e))}),t.config&&this.walletMessageManager.pingIframe().then(()=>{this.postRequestAndWait({method:r.set_custom_config,params:[t.config],interactionRequired:!1}).catch(e=>console.error("Error setting custom config:",e))}),this.walletMessageManager.addListener({handleResponse:e=>{this.internalEventEmitter.emit(e.id,e)},handleRequest:e=>{e.method===r.show_modal?this.uiMessageManager.emit(w.show_modal):e.method===r.hide_modal&&this.uiMessageManager.emit(w.hide_modal)},onAccountChanged:async function(e){try{const e=await a.refreshAccounts();a.notifyChange({accounts:e.accounts})}catch(e){console.error("Failed to refresh Sui accounts:",e),a._accounts=[],a.notifyChange({accounts:[]})}}})}async refreshAccounts(){try{var e;await this.walletMessageManager.pingIframe();const t=await this.postRequestAndWait({method:"sui_connect",params:[{silent:!0}],interactionRequired:!1});if(t.error)return this._accounts=[],{accounts:[]};const n=(null==(e=t.data)?void 0:e.accounts)||[];return this._accounts=n,{accounts:this._accounts}}catch(e){return this._accounts=[],{accounts:[]}}}get chains(){return this._chains}get accounts(){return this._accounts}get ui(){return this.uiMessageManager}async connect(e){var t;await this.walletMessageManager.pingIframe();const n=await this.postRequestAndWait({method:"sui_connect",params:[e||{}],interactionRequired:!(null!=e&&e.silent)});if(n.error)throw new Error(n.error.message||"Failed to connect");const i=(null==(t=n.data)?void 0:t.accounts)||[];return this._accounts=i,this.notifyChange({accounts:this._accounts}),{accounts:this._accounts}}async disconnect(){await this.walletMessageManager.pingIframe(),await this.postRequestAndWait({method:"sui_disconnect",params:[],interactionRequired:!1}),this._accounts=[],this.notifyChange({accounts:[]})}async signPersonalMessage(e){await this.walletMessageManager.pingIframe();const t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw new Error(`Account ${t} is not connected`);const n=await this.postRequestAndWait({method:"sui_signPersonalMessage",params:[{message:Array.from(e.message),account:t,chain:e.chain}],interactionRequired:!0});if(n.error)throw new Error(n.error.message||"Failed to sign message");return{bytes:n.data.bytes,signature:n.data.signature}}async resolveTransactionBytes(e,t="sui:mainnet"){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return new Uint8Array(e);if("string"!=typeof e){if(e&&"object"==typeof e){if("function"==typeof e.build)try{const{getFullnodeUrl:n,SuiClient:i}=await import("@mysten/sui/client");let a="mainnet";"sui:testnet"===t?a="testnet":"sui:devnet"===t?a="devnet":"sui:localnet"===t&&(a="localnet");const s=new i({url:n(a)});return await e.build({client:s})}catch(e){throw console.warn("[SuiWallet] Failed to build transaction object:",e),new Error(`Failed to build transaction: ${e instanceof Error?e.message:String(e)}`)}if("function"==typeof e.serialize)try{const t=await e.serialize();if("string"==typeof t)return Uint8Array.from(atob(t),e=>e.charCodeAt(0));if(t instanceof Uint8Array)return t}catch(e){console.warn("[SuiWallet] serialize() failed:",e)}if("function"==typeof e.toJSON)try{const t=await e.toJSON();if("string"==typeof t)try{return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}catch(e){try{const e=JSON.parse(t);if(e.bytes&&"string"==typeof e.bytes)return Uint8Array.from(atob(e.bytes),e=>e.charCodeAt(0))}catch(e){}}}catch(e){console.warn("[SuiWallet] toJSON() failed:",e)}if("function"==typeof e.getData)try{const t=e.getData();if(t instanceof Uint8Array)return t}catch(e){console.warn("[SuiWallet] getData() failed:",e)}throw new Error(`Unsupported transaction format. Keys: ${Object.keys(e).join(", ")}`)}throw new Error(`Unsupported transaction format: ${typeof e}. Please pass Uint8Array bytes or a Transaction object.`)}try{return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}catch(e){throw new Error("Transaction string must be base64 encoded bytes. If you have a serialized transaction JSON, please build it to bytes first.")}}async signTransaction(e){await this.walletMessageManager.pingIframe();const t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw new Error(`Account ${t} is not connected`);const n=await this.resolveTransactionBytes(e.transaction,e.chain),i=await this.postRequestAndWait({method:"sui_signTransaction",params:[{transaction:Array.from(n),account:t,chain:e.chain}],interactionRequired:!0});if(i.error)throw new Error(i.error.message||"Failed to sign transaction");return{bytes:i.data.bytes,signature:i.data.signature}}async signAndExecuteTransaction(e){await this.walletMessageManager.pingIframe();const t=e.account.address;if(!this._accounts.some(e=>e.address===t))throw new Error(`Account ${t} is not connected`);const n=await this.resolveTransactionBytes(e.transaction,e.chain),i=await this.postRequestAndWait({method:"sui_signAndExecuteTransaction",params:[{transaction:Array.from(n),account:t,chain:e.chain,options:e.options,requestType:e.requestType}],interactionRequired:!0});if(i.error)throw new Error(i.error.message||"Failed to sign and execute transaction");return i.data}async switchChain(e){if(await this.walletMessageManager.pingIframe(),!this._chains.includes(e.chain))throw new Error(`Chain ${e.chain} is not supported`);const t=await this.postRequestAndWait({method:"sui_switchChain",params:[e],interactionRequired:!1});if(t.error)throw new Error(t.error.message||"Failed to switch chain");this.notifyChange({chains:this._chains,accounts:this._accounts})}on(e,t){return"change"===e?(this.changeListeners.add(t),()=>{this.changeListeners.delete(t)}):()=>{}}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)},"sui:signPersonalMessage":{version:"1.1.0",signPersonalMessage:this.signPersonalMessage.bind(this)},"sui:signTransaction":{version:"2.0.0",signTransaction:this.signTransaction.bind(this)},"sui:signAndExecuteTransaction":{version:"1.0.0",signAndExecuteTransaction:this.signAndExecuteTransaction.bind(this)},"sui:signTransactionBlock":{version:"2.0.0",signTransactionBlock:this.signTransactionBlock.bind(this)},"sui:signAndExecuteTransactionBlock":{version:"1.0.0",signAndExecuteTransactionBlock:this.signAndExecuteTransactionBlock.bind(this)},"sui:switchChain":{version:"1.0.0",switchChain:this.switchChain.bind(this)}}}async signTransactionBlock(e){return this.signTransaction({transaction:e.transactionBlock,account:e.account,chain:e.chain})}async signAndExecuteTransactionBlock(e){return this.signAndExecuteTransaction({transaction:e.transactionBlock,account:e.account,chain:e.chain,options:e.options,requestType:e.requestType})}async requestEmail(){await this.walletMessageManager.pingIframe();const e=await this.postRequestAndWait({method:r.silk_requestEmail,params:[],interactionRequired:!0});if(e.error)throw new Error(e.error.message||"Failed to request email");return e.data}async postRequestAndWait(e){const t=await this.walletMessageManager.postSilkRequest({method:e.method,params:e.params,interactionRequired:e.interactionRequired});return new Promise(e=>{this.internalEventEmitter.once(t,t=>{e(t)})})}notifyChange(e){Array.from(this.changeListeners).forEach(t=>{t(e)})}}const H="waap-wallet-iframe-container",G="waap-wallet-iframe",$=()=>document.getElementById(H)||document.getElementById("silk-wallet-iframe-container"),K="waap-wallet-iframe-wrapper";function Q(n={}){var i;(n=>{if($())return;const i=document.createElement("div");i.id=H,i.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n width: 100%;\n height: 100%;\n display: none;\n align-items: center;\n justify-content: center;\n background-color: rgba(0, 0, 0, 0.5);\n z-index: 9999999999;\n ";const a=document.createElement("div");a.id=K,a.style.cssText="\n position: relative;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 0;\n margin: 0;\n height: 600px;\n width: 380px;\n ",i.appendChild(a);const s=document.createElement("iframe");s.id=G,s.src=`${n?e:t}/iframe`,s.style.cssText="\n width: 100%;\n height: 100%;\n border: none;\n border-radius: 24px;\n background: transparent;\n ",a.appendChild(s),(n=>{window.addEventListener("message",i=>{if(i.origin!==(n?e:t))return;if(!i.data||"object"!=typeof i.data)return;if("silk-iframe-size"!==i.data.type)return;const a=i.data.height,s=i.data.width;if("number"!=typeof a||"number"!=typeof s)return;if(a<50||a>2e3)return;if(s<50||s>2e3)return;if(!Number.isFinite(a)||!Number.isFinite(s))return;const o=document.getElementById(K)||document.getElementById("silk-wallet-iframe-wrapper");o&&(o.style.height=`${Math.floor(a)}px`,o.style.width=`${Math.floor(s)}px`)})})(n),document.body.appendChild(i)})(null!=(i=n.useStaging)&&i);const a=$(),s=document.getElementById(G)||document.getElementById("silk-wallet-iframe");if(!a||!s)throw new Error("Failed to create WaaP iframe");const o=new U(s.contentWindow,n);return o.ui.on(w.show_modal,()=>{a.style.display="flex",document.querySelectorAll('[data-dapp-kit][class*="overlay"]').forEach(e=>{e.style.display="none"})}),o.ui.on(w.hide_modal,()=>{a.style.display="none",document.querySelectorAll('[data-dapp-kit][class*="overlay"]').forEach(e=>{e.style.display=""})}),o}function V(e,t={}){const n=new U(e,t);return d(n),n}function X(e){const[t,n]=u(new Map),i=h(e);g(()=>{i.current=e},[e]),g(()=>{const e=window.waap||window.silk;if(!e)return void console.warn("[useWaapTransaction] WaaP provider not found. Make sure initWaaP() was called.");const t=e=>{var t;n(t=>{const n=new Map(t);return n.set(e.txHash,{status:"signed",txHash:e.txHash,pendingTxId:e.txHash,signature:e.signature,serializedTx:e.serializedTx}),n}),null==(t=i.current)||null==t.onSigned||t.onSigned(e)},a=e=>{var t;n(t=>{const n=new Map(t),i=n.get(e.txHash);return i&&n.set(e.txHash,p({},i,{status:"tx_pending"})),n}),null==(t=i.current)||null==t.onTxPending||t.onTxPending(e)},s=e=>{var t;n(t=>{const n=new Map(t),i=n.get(e.txHash);return i&&n.set(e.txHash,p({},i,{status:"confirmed",receipt:e.receipt})),n}),null==(t=i.current)||null==t.onConfirmed||t.onConfirmed(e)},o=e=>{var t;n(t=>{const n=new Map(t),i=n.get(e.txHash);return i&&n.set(e.txHash,p({},i,{status:"failed",error:e.error,stage:e.stage})),n}),null==(t=i.current)||null==t.onFailed||t.onFailed(e)};return e.on("waap_sign_complete",t),e.on("waap_tx_pending",a),e.on("waap_tx_confirmed",s),e.on("waap_tx_failed",o),()=>{null==e.removeListener||e.removeListener("waap_sign_complete",t),null==e.removeListener||e.removeListener("waap_tx_pending",a),null==e.removeListener||e.removeListener("waap_tx_confirmed",s),null==e.removeListener||e.removeListener("waap_tx_failed",o)}},[]);const a=m(async e=>{const t=window.waap||window.silk;if(!t)throw new Error("WaaP provider not found");return t.request({method:"eth_sendTransaction",params:e})},[]),s=m(async e=>{const t=window.waap||window.silk;if(!t)throw new Error("WaaP provider not found");return t.request({method:"eth_signTransaction",params:e})},[]),o=Array.from(t.values()).some(e=>"signed"===e.status||"tx_pending"===e.status);return{sendTransaction:a,signTransaction:s,pendingTransactions:t,isAnyPending:o}}export{C as EthereumProvider,J as EthereumProviderExtension,M as SilkWalletConnect,f as UIMessageManager,w as UI_EVENT_NAMES,T as WaaP,U as WaaPSuiWallet,M as WaaPWalletConnect,A as WalletMessageManager,y as handleWalletRequestAndResponse,z as initWaaP,Q as initWaaPSui,V as registerWaaPSuiWallet,X as useWaapTransaction};
2
2
  //# sourceMappingURL=index.modern.mjs.map