From 459ed226c4464e797b2f25a94e3cd7d4e5ff01e0 Mon Sep 17 00:00:00 2001 From: Nam Nguyen Date: Tue, 3 Oct 2023 09:24:08 +0700 Subject: [PATCH] feat: Krystal walletconnect (#2246) --- .github/workflows/pr.yaml | 2 +- package.json | 3 +- ...alletconnect+ethereum-provider+2.8.1.patch | 29 +++++++ src/components/AddressInputPanel/index.tsx | 3 + .../Header/web3/WalletModal/index.tsx | 8 +- src/components/Menu/index.tsx | 2 +- src/components/ProAmm/CandleStickChart.tsx | 12 +-- .../TransactionConfirmationModal/index.tsx | 1 + .../swapv2/LimitOrder/ListOrder/index.tsx | 8 +- src/constants/connectors/evm.ts | 79 +++++++++++-------- src/constants/connectors/utils.ts | 44 ++++++++--- src/constants/wallets.ts | 50 ++++++++---- src/hooks/index.ts | 5 +- src/hooks/kyberdao/index.tsx | 53 ++++--------- src/hooks/useApproveCallback.ts | 1 - src/hooks/useSwapCallbackV3.ts | 6 +- src/hooks/useSwapV2Callback.ts | 7 +- src/hooks/web3/useActivationWallet.ts | 13 ++- src/hooks/web3/useChangeNetwork.ts | 4 +- src/hooks/web3/useDisconnectWallet.ts | 4 +- src/hooks/web3/useWalletSupportedChains.ts | 3 +- .../Campaign/CampaignButtonWithOptions.tsx | 4 +- src/pages/ElasticSwap/hooks/index.ts | 26 +++--- .../SinglePosition/CollectFeesPanel.tsx | 4 +- src/utils/errorMessage.ts | 14 +++- src/utils/numbers.ts | 17 ---- src/utils/sendTransaction.ts | 25 +++++- src/utils/sentry.ts | 27 +++++-- src/vite-env.d.ts | 1 + tsconfig.json | 3 +- yarn.lock | 16 +++- 31 files changed, 304 insertions(+), 170 deletions(-) create mode 100644 patches/@walletconnect+ethereum-provider+2.8.1.patch diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 4fc367b68b..0b9eaa7c9a 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -114,7 +114,7 @@ jobs: VITE_TAG: ${{ needs.prepare.outputs.image_tag }} CURRENT_BRANCH: ${{ needs.prepare.outputs.current_branch }} NODE_OPTIONS: '--max_old_space_size=4096' - run: yarn build-adpr + run: yarn build-prod - name: Docker build and push uses: docker/build-push-action@v2 diff --git a/package.json b/package.json index 89fedc6195..819d521cbf 100644 --- a/package.json +++ b/package.json @@ -49,6 +49,7 @@ "@coinbase/wallet-sdk": "^3.0.4", "@esbuild-plugins/node-globals-polyfill": "^0.2.3", "@kybernetwork/oauth2": "1.0.0", + "@kyberswap/krystal-walletconnect-v2": "0.0.1", "@kyberswap/ks-sdk-classic": "^1.0.3", "@kyberswap/ks-sdk-core": "1.0.11", "@kyberswap/ks-sdk-elastic": "^1.1.2", @@ -207,4 +208,4 @@ "@lingui/core": "3.14.0", "@lingui/conf": "3.16.0" } -} +} \ No newline at end of file diff --git a/patches/@walletconnect+ethereum-provider+2.8.1.patch b/patches/@walletconnect+ethereum-provider+2.8.1.patch new file mode 100644 index 0000000000..3f1eb1b4c8 --- /dev/null +++ b/patches/@walletconnect+ethereum-provider+2.8.1.patch @@ -0,0 +1,29 @@ +diff --git a/node_modules/@walletconnect/ethereum-provider/dist/index.cjs.js b/node_modules/@walletconnect/ethereum-provider/dist/index.cjs.js +index 4c23c8c..b87fc08 100644 +--- a/node_modules/@walletconnect/ethereum-provider/dist/index.cjs.js ++++ b/node_modules/@walletconnect/ethereum-provider/dist/index.cjs.js +@@ -1,2 +1,2 @@ +-"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var A=require("events"),h=require("@walletconnect/utils"),T=require("@walletconnect/universal-provider");function R(i){if(i&&i.__esModule)return i;var t=Object.create(null);return i&&Object.keys(i).forEach(function(e){if(e!=="default"){var s=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(t,e,s.get?s:{enumerable:!0,get:function(){return i[e]}})}}),t.default=i,Object.freeze(t)}const S="wc",j="ethereum_provider",N=`${S}@2:${j}:`,q="https://rpc.walletconnect.com/v1/",u=["eth_sendTransaction","personal_sign"],D=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],m=["chainChanged","accountsChanged"],$=["message","disconnect","connect"];var U=Object.defineProperty,Q=Object.defineProperties,L=Object.getOwnPropertyDescriptors,_=Object.getOwnPropertySymbols,V=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable,O=(i,t,e)=>t in i?U(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,I=(i,t)=>{for(var e in t||(t={}))V.call(t,e)&&O(i,e,t[e]);if(_)for(var e of _(t))H.call(t,e)&&O(i,e,t[e]);return i},y=(i,t)=>Q(i,L(t));function C(i){return Number(i[0].split(":")[1])}function E(i){return`0x${i.toString(16)}`}function z(i){const{chains:t,optionalChains:e,methods:s,optionalMethods:n,events:a,optionalEvents:l,rpcMap:c}=i;if(!h.isValidArray(t))throw new Error("Invalid chains");const o=t,r=s||u,f=a||m,b={[C(o)]:c[C(o)]},w={chains:o,methods:r,events:f,rpcMap:b},d=a?.filter(v=>!m.includes(v)),p=s?.filter(v=>!u.includes(v));if(!e&&!l&&!n&&!(d!=null&&d.length)&&!(p!=null&&p.length))return{required:w};const M=d?.length&&p?.length||!e,P={chains:[...new Set(M?o.concat(e||[]):e)],methods:[...new Set(r.concat(n||[]))],events:[...new Set(f.concat(l||[]))],rpcMap:c};return{required:w,optional:P}}class g{constructor(){this.events=new A.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=N,this.on=(t,e)=>(this.events.on(t,e),this),this.once=(t,e)=>(this.events.once(t,e),this),this.removeListener=(t,e)=>(this.events.removeListener(t,e),this),this.off=(t,e)=>(this.events.off(t,e),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){const e=new g;return await e.initialize(t),e}async request(t){return await this.signer.request(t,this.formatChainId(this.chainId))}sendAsync(t,e){this.signer.sendAsync(t,e,this.formatChainId(this.chainId))}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:e,optional:s}=z(this.rpc);try{const n=await new Promise(async(l,c)=>{var o;this.rpc.showQrModal&&((o=this.modal)==null||o.subscribeModal(r=>{!r.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(y(I({namespaces:{[this.namespace]:e}},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:t?.pairingTopic})).then(r=>{l(r)}).catch(r=>{c(new Error(r.message))})});if(!n)return;this.setChainIds(this.rpc.chains);const a=h.getAccountsFromNamespaces(n.namespaces,[this.namespace]);this.setAccounts(a),this.events.emit("connect",{chainId:E(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{const{params:e}=t,{event:s}=e;s.name==="accountsChanged"?(this.accounts=this.parseAccounts(s.data),this.events.emit("accountsChanged",this.accounts)):s.name==="chainChanged"?this.setChainId(this.formatChainId(s.data)):this.events.emit(s.name,s.data),this.events.emit("session_event",t)}),this.signer.on("chainChanged",t=>{const e=parseInt(t);this.chainId=e,this.events.emit("chainChanged",E(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",y(I({},h.getSdkError("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{var e,s;this.rpc.showQrModal&&((e=this.modal)==null||e.closeModal(),(s=this.modal)==null||s.openModal({uri:t})),this.events.emit("display_uri",t)})}setHttpProvider(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const e=t.filter(s=>this.isCompatibleChainId(s)).map(s=>this.parseChainId(s));e.length&&(this.chainId=e[0],this.events.emit("chainChanged",E(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const e=this.parseChainId(t);this.chainId=e,this.setHttpProvider(e)}}parseAccountId(t){const[e,s,n]=t.split(":");return{chainId:`${e}:${s}`,address:n}}setAccounts(t){this.accounts=t.filter(e=>this.parseChainId(this.parseAccountId(e).chainId)===this.chainId).map(e=>this.parseAccountId(e).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var e,s;return{chains:((e=t.chains)==null?void 0:e.map(n=>this.formatChainId(n)))||[`${this.namespace}:1`],optionalChains:t.optionalChains?t.optionalChains.map(n=>this.formatChainId(n)):void 0,methods:t?.methods||u,events:t?.events||m,optionalMethods:t?.optionalMethods||[],optionalEvents:t?.optionalEvents||[],rpcMap:t?.rpcMap||this.buildRpcMap(t.chains.concat(t.optionalChains||[]),t.projectId),showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:(s=t?.qrModalOptions)!=null?s:void 0,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,e){const s={};return t.forEach(n=>{s[n]=this.getRpcUrl(n,e)}),s}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=C(this.rpc.chains),this.signer=await T.UniversalProvider.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let e;try{const{WalletConnectModal:s}=await Promise.resolve().then(function(){return R(require("@walletconnect/modal"))});e=s}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(e)try{this.modal=new e(I({walletConnectVersion:2,projectId:this.rpc.projectId,standaloneChains:this.rpc.chains},this.rpc.qrModalOptions))}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:e,optionalChains:s,rpcMap:n}=t;e&&h.isValidArray(e)&&(this.rpc.chains=e.map(a=>this.formatChainId(a)),e.forEach(a=>{this.rpc.rpcMap[a]=n?.[a]||this.getRpcUrl(a)})),s&&h.isValidArray(s)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=s?.map(a=>this.formatChainId(a)),s.forEach(a=>{this.rpc.rpcMap[a]=n?.[a]||this.getRpcUrl(a)}))}getRpcUrl(t,e){var s;return((s=this.rpc.rpcMap)==null?void 0:s[t])||`${q}?chainId=eip155:${t}&projectId=${e||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const t=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`);this.setChainIds(t?[this.formatChainId(t)]:this.session.namespaces[this.namespace].accounts),this.setAccounts(this.session.namespaces[this.namespace].accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(e=>this.parseAccount(e))}}const G=g;exports.EthereumProvider=G,exports.OPTIONAL_EVENTS=$,exports.OPTIONAL_METHODS=D,exports.REQUIRED_EVENTS=m,exports.REQUIRED_METHODS=u,exports.default=g; ++"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var A=require("events"),h=require("@walletconnect/utils"),T=require("@walletconnect/universal-provider");function R(i){if(i&&i.__esModule)return i;var t=Object.create(null);return i&&Object.keys(i).forEach(function(e){if(e!=="default"){var s=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(t,e,s.get?s:{enumerable:!0,get:function(){return i[e]}})}}),t.default=i,Object.freeze(t)}const S="wc",j="ethereum_provider",N=`${S}@2:${j}:`,q="https://rpc.walletconnect.com/v1/",u=["eth_sendTransaction","personal_sign"],D=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],m=["chainChanged","accountsChanged"],$=["message","disconnect","connect"];var U=Object.defineProperty,Q=Object.defineProperties,L=Object.getOwnPropertyDescriptors,_=Object.getOwnPropertySymbols,V=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable,O=(i,t,e)=>t in i?U(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,I=(i,t)=>{for(var e in t||(t={}))V.call(t,e)&&O(i,e,t[e]);if(_)for(var e of _(t))H.call(t,e)&&O(i,e,t[e]);return i},y=(i,t)=>Q(i,L(t));function C(i){return Number(i[0].split(":")[1])}function E(i){return`0x${i.toString(16)}`}function z(i){const{chains:t,optionalChains:e,methods:s,optionalMethods:n,events:a,optionalEvents:l,rpcMap:c}=i;if(!h.isValidArray(t))throw new Error("Invalid chains");const o=t,r=s||u,f=a||m,b={[C(o)]:c[C(o)]},w={chains:o,methods:r,events:f,rpcMap:b},d=a?.filter(v=>!m.includes(v)),p=s?.filter(v=>!u.includes(v));if(!e&&!l&&!n&&!(d!=null&&d.length)&&!(p!=null&&p.length))return{required:w};const M=d?.length&&p?.length||!e,P={chains:[...new Set(M?o.concat(e||[]):e)],methods:[...new Set(r.concat(n||[]))],events:[...new Set(f.concat(l||[]))],rpcMap:c};return{required:w,optional:P}}class g{constructor(){this.events=new A.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=N,this.on=(t,e)=>(this.events.on(t,e),this),this.once=(t,e)=>(this.events.once(t,e),this),this.removeListener=(t,e)=>(this.events.removeListener(t,e),this),this.off=(t,e)=>(this.events.off(t,e),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){const e=new g;return await e.initialize(t),e}async request(t){return await this.signer.request(t,this.formatChainId(this.chainId))}sendAsync(t,e){this.signer.sendAsync(t,e,this.formatChainId(this.chainId))}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:e,optional:s}=z(this.rpc);try{const n=await new Promise(async(l,c)=>{var o;this.rpc.showQrModal&&((o=this.modal)==null||o.subscribeModal(r=>{!r.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(y(I({namespaces:{[this.namespace]:e}},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:t?.pairingTopic})).then(r=>{l(r)}).catch(r=>{c(new Error(r.message))})});if(!n)return;const chainId=this.signer.rpcProviders.eip155.chainId;this.setChainIds([this.formatChainId(chainId)]);const a=h.getAccountsFromNamespaces(n.namespaces,[this.namespace]);this.setAccounts(a),this.events.emit("connect",{chainId:E(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{const{params:e}=t,{event:s}=e;s.name==="accountsChanged"?(this.accounts=this.parseAccounts(s.data),this.events.emit("accountsChanged",this.accounts)):s.name==="chainChanged"?this.setChainId(this.formatChainId(s.data)):this.events.emit(s.name,s.data),this.events.emit("session_event",t)}),this.signer.on("chainChanged",t=>{const e=parseInt(t);this.chainId=e,this.events.emit("chainChanged",E(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",y(I({},h.getSdkError("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{var e,s;this.rpc.showQrModal&&((e=this.modal)==null||e.closeModal(),(s=this.modal)==null||s.openModal({uri:t})),this.events.emit("display_uri",t)})}setHttpProvider(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const e=t.filter(s=>this.isCompatibleChainId(s)).map(s=>this.parseChainId(s));e.length&&(this.chainId=e[0],this.events.emit("chainChanged",E(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const e=this.parseChainId(t);this.chainId=e,this.setHttpProvider(e)}}parseAccountId(t){const[e,s,n]=t.split(":");return{chainId:`${e}:${s}`,address:n}}setAccounts(t){this.accounts=t.filter(e=>this.parseChainId(this.parseAccountId(e).chainId)===this.chainId).map(e=>this.parseAccountId(e).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var e,s;return{chains:((e=t.chains)==null?void 0:e.map(n=>this.formatChainId(n)))||[`${this.namespace}:1`],optionalChains:t.optionalChains?t.optionalChains.map(n=>this.formatChainId(n)):void 0,methods:t?.methods||u,events:t?.events||m,optionalMethods:t?.optionalMethods||[],optionalEvents:t?.optionalEvents||[],rpcMap:t?.rpcMap||this.buildRpcMap(t.chains.concat(t.optionalChains||[]),t.projectId),showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:(s=t?.qrModalOptions)!=null?s:void 0,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,e){const s={};return t.forEach(n=>{s[n]=this.getRpcUrl(n,e)}),s}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=C(this.rpc.chains),this.signer=await T.UniversalProvider.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let e;try{const{WalletConnectModal:s}=await Promise.resolve().then(function(){return R(require("@walletconnect/modal"))});e=s}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(e)try{this.modal=new e(I({walletConnectVersion:2,projectId:this.rpc.projectId,standaloneChains:this.rpc.chains},this.rpc.qrModalOptions))}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:e,optionalChains:s,rpcMap:n}=t;e&&h.isValidArray(e)&&(this.rpc.chains=e.map(a=>this.formatChainId(a)),e.forEach(a=>{this.rpc.rpcMap[a]=n?.[a]||this.getRpcUrl(a)})),s&&h.isValidArray(s)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=s?.map(a=>this.formatChainId(a)),s.forEach(a=>{this.rpc.rpcMap[a]=n?.[a]||this.getRpcUrl(a)}))}getRpcUrl(t,e){var s;return((s=this.rpc.rpcMap)==null?void 0:s[t])||`${q}?chainId=eip155:${t}&projectId=${e||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const t=this.signer.rpcProviders.eip155.chainId;this.setChainIds(t?[this.formatChainId(t)]:this.session.namespaces[this.namespace].accounts),this.setAccounts(this.session.namespaces[this.namespace].accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(e=>this.parseAccount(e))}}const G=g;exports.EthereumProvider=G,exports.OPTIONAL_EVENTS=$,exports.OPTIONAL_METHODS=D,exports.REQUIRED_EVENTS=m,exports.REQUIRED_METHODS=u,exports.default=g; + //# sourceMappingURL=index.cjs.js.map +diff --git a/node_modules/@walletconnect/ethereum-provider/dist/index.es.js b/node_modules/@walletconnect/ethereum-provider/dist/index.es.js +index db2e087..2ba50a0 100644 +--- a/node_modules/@walletconnect/ethereum-provider/dist/index.es.js ++++ b/node_modules/@walletconnect/ethereum-provider/dist/index.es.js +@@ -1,2 +1,2 @@ +-import{EventEmitter as P}from"events";import{getAccountsFromNamespaces as R,getSdkError as T,isValidArray as v}from"@walletconnect/utils";import{UniversalProvider as S}from"@walletconnect/universal-provider";const j="wc",q="ethereum_provider",N=`${j}@2:${q}:`,$="https://rpc.walletconnect.com/v1/",p=["eth_sendTransaction","personal_sign"],D=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],u=["chainChanged","accountsChanged"],U=["message","disconnect","connect"];var Q=Object.defineProperty,L=Object.defineProperties,H=Object.getOwnPropertyDescriptors,_=Object.getOwnPropertySymbols,G=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable,y=(a,t,s)=>t in a?Q(a,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):a[t]=s,I=(a,t)=>{for(var s in t||(t={}))G.call(t,s)&&y(a,s,t[s]);if(_)for(var s of _(t))K.call(t,s)&&y(a,s,t[s]);return a},M=(a,t)=>L(a,H(t));function C(a){return Number(a[0].split(":")[1])}function w(a){return`0x${a.toString(16)}`}function V(a){const{chains:t,optionalChains:s,methods:i,optionalMethods:n,events:e,optionalEvents:h,rpcMap:c}=a;if(!v(t))throw new Error("Invalid chains");const o=t,r=i||p,f=e||u,O={[C(o)]:c[C(o)]},E={chains:o,methods:r,events:f,rpcMap:O},l=e?.filter(g=>!u.includes(g)),d=i?.filter(g=>!p.includes(g));if(!s&&!h&&!n&&!(l!=null&&l.length)&&!(d!=null&&d.length))return{required:E};const b=l?.length&&d?.length||!s,A={chains:[...new Set(b?o.concat(s||[]):s)],methods:[...new Set(r.concat(n||[]))],events:[...new Set(f.concat(h||[]))],rpcMap:c};return{required:E,optional:A}}class m{constructor(){this.events=new P,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=N,this.on=(t,s)=>(this.events.on(t,s),this),this.once=(t,s)=>(this.events.once(t,s),this),this.removeListener=(t,s)=>(this.events.removeListener(t,s),this),this.off=(t,s)=>(this.events.off(t,s),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){const s=new m;return await s.initialize(t),s}async request(t){return await this.signer.request(t,this.formatChainId(this.chainId))}sendAsync(t,s){this.signer.sendAsync(t,s,this.formatChainId(this.chainId))}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:s,optional:i}=V(this.rpc);try{const n=await new Promise(async(h,c)=>{var o;this.rpc.showQrModal&&((o=this.modal)==null||o.subscribeModal(r=>{!r.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(M(I({namespaces:{[this.namespace]:s}},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:t?.pairingTopic})).then(r=>{h(r)}).catch(r=>{c(new Error(r.message))})});if(!n)return;this.setChainIds(this.rpc.chains);const e=R(n.namespaces,[this.namespace]);this.setAccounts(e),this.events.emit("connect",{chainId:w(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{const{params:s}=t,{event:i}=s;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",t)}),this.signer.on("chainChanged",t=>{const s=parseInt(t);this.chainId=s,this.events.emit("chainChanged",w(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",M(I({},T("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{var s,i;this.rpc.showQrModal&&((s=this.modal)==null||s.closeModal(),(i=this.modal)==null||i.openModal({uri:t})),this.events.emit("display_uri",t)})}setHttpProvider(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const s=t.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));s.length&&(this.chainId=s[0],this.events.emit("chainChanged",w(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const s=this.parseChainId(t);this.chainId=s,this.setHttpProvider(s)}}parseAccountId(t){const[s,i,n]=t.split(":");return{chainId:`${s}:${i}`,address:n}}setAccounts(t){this.accounts=t.filter(s=>this.parseChainId(this.parseAccountId(s).chainId)===this.chainId).map(s=>this.parseAccountId(s).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var s,i;return{chains:((s=t.chains)==null?void 0:s.map(n=>this.formatChainId(n)))||[`${this.namespace}:1`],optionalChains:t.optionalChains?t.optionalChains.map(n=>this.formatChainId(n)):void 0,methods:t?.methods||p,events:t?.events||u,optionalMethods:t?.optionalMethods||[],optionalEvents:t?.optionalEvents||[],rpcMap:t?.rpcMap||this.buildRpcMap(t.chains.concat(t.optionalChains||[]),t.projectId),showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:(i=t?.qrModalOptions)!=null?i:void 0,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,s){const i={};return t.forEach(n=>{i[n]=this.getRpcUrl(n,s)}),i}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=C(this.rpc.chains),this.signer=await S.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let s;try{const{WalletConnectModal:i}=await import("@walletconnect/modal");s=i}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(s)try{this.modal=new s(I({walletConnectVersion:2,projectId:this.rpc.projectId,standaloneChains:this.rpc.chains},this.rpc.qrModalOptions))}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:s,optionalChains:i,rpcMap:n}=t;s&&v(s)&&(this.rpc.chains=s.map(e=>this.formatChainId(e)),s.forEach(e=>{this.rpc.rpcMap[e]=n?.[e]||this.getRpcUrl(e)})),i&&v(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(e=>this.formatChainId(e)),i.forEach(e=>{this.rpc.rpcMap[e]=n?.[e]||this.getRpcUrl(e)}))}getRpcUrl(t,s){var i;return((i=this.rpc.rpcMap)==null?void 0:i[t])||`${$}?chainId=eip155:${t}&projectId=${s||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const t=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`);this.setChainIds(t?[this.formatChainId(t)]:this.session.namespaces[this.namespace].accounts),this.setAccounts(this.session.namespaces[this.namespace].accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(s=>this.parseAccount(s))}}const W=m;export{W as EthereumProvider,U as OPTIONAL_EVENTS,D as OPTIONAL_METHODS,u as REQUIRED_EVENTS,p as REQUIRED_METHODS,m as default}; ++import{EventEmitter as P}from"events";import{getAccountsFromNamespaces as R,getSdkError as T,isValidArray as v}from"@walletconnect/utils";import{UniversalProvider as S}from"@walletconnect/universal-provider";const j="wc",q="ethereum_provider",N=`${j}@2:${q}:`,$="https://rpc.walletconnect.com/v1/",p=["eth_sendTransaction","personal_sign"],D=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],u=["chainChanged","accountsChanged"],U=["message","disconnect","connect"];var Q=Object.defineProperty,L=Object.defineProperties,H=Object.getOwnPropertyDescriptors,_=Object.getOwnPropertySymbols,G=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable,y=(a,t,s)=>t in a?Q(a,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):a[t]=s,I=(a,t)=>{for(var s in t||(t={}))G.call(t,s)&&y(a,s,t[s]);if(_)for(var s of _(t))K.call(t,s)&&y(a,s,t[s]);return a},M=(a,t)=>L(a,H(t));function C(a){return Number(a[0].split(":")[1])}function w(a){return`0x${a.toString(16)}`}function V(a){const{chains:t,optionalChains:s,methods:i,optionalMethods:n,events:e,optionalEvents:h,rpcMap:c}=a;if(!v(t))throw new Error("Invalid chains");const o=t,r=i||p,f=e||u,O={[C(o)]:c[C(o)]},E={chains:o,methods:r,events:f,rpcMap:O},l=e?.filter(g=>!u.includes(g)),d=i?.filter(g=>!p.includes(g));if(!s&&!h&&!n&&!(l!=null&&l.length)&&!(d!=null&&d.length))return{required:E};const b=l?.length&&d?.length||!s,A={chains:[...new Set(b?o.concat(s||[]):s)],methods:[...new Set(r.concat(n||[]))],events:[...new Set(f.concat(h||[]))],rpcMap:c};return{required:E,optional:A}}class m{constructor(){this.events=new P,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=N,this.on=(t,s)=>(this.events.on(t,s),this),this.once=(t,s)=>(this.events.once(t,s),this),this.removeListener=(t,s)=>(this.events.removeListener(t,s),this),this.off=(t,s)=>(this.events.off(t,s),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){const s=new m;return await s.initialize(t),s}async request(t){return await this.signer.request(t,this.formatChainId(this.chainId))}sendAsync(t,s){this.signer.sendAsync(t,s,this.formatChainId(this.chainId))}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:s,optional:i}=V(this.rpc);try{const n=await new Promise(async(h,c)=>{var o;this.rpc.showQrModal&&((o=this.modal)==null||o.subscribeModal(r=>{!r.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(M(I({namespaces:{[this.namespace]:s}},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:t?.pairingTopic})).then(r=>{h(r)}).catch(r=>{c(new Error(r.message))})});if(!n)return;const chainId = this.signer.rpcProviders.eip155.chainId;this.setChainIds([this.formatChainId(chainId)]);const e=R(n.namespaces,[this.namespace]);this.setAccounts(e),this.events.emit("connect",{chainId:w(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{const{params:s}=t,{event:i}=s;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",t)}),this.signer.on("chainChanged",t=>{const s=parseInt(t);this.chainId=s,this.events.emit("chainChanged",w(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",M(I({},T("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{var s,i;this.rpc.showQrModal&&((s=this.modal)==null||s.closeModal(),(i=this.modal)==null||i.openModal({uri:t})),this.events.emit("display_uri",t)})}setHttpProvider(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const s=t.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));s.length&&(this.chainId=s[0],this.events.emit("chainChanged",w(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const s=this.parseChainId(t);this.chainId=s,this.setHttpProvider(s)}}parseAccountId(t){const[s,i,n]=t.split(":");return{chainId:`${s}:${i}`,address:n}}setAccounts(t){this.accounts=t.filter(s=>this.parseChainId(this.parseAccountId(s).chainId)===this.chainId).map(s=>this.parseAccountId(s).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var s,i;return{chains:((s=t.chains)==null?void 0:s.map(n=>this.formatChainId(n)))||[`${this.namespace}:1`],optionalChains:t.optionalChains?t.optionalChains.map(n=>this.formatChainId(n)):void 0,methods:t?.methods||p,events:t?.events||u,optionalMethods:t?.optionalMethods||[],optionalEvents:t?.optionalEvents||[],rpcMap:t?.rpcMap||this.buildRpcMap(t.chains.concat(t.optionalChains||[]),t.projectId),showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:(i=t?.qrModalOptions)!=null?i:void 0,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,s){const i={};return t.forEach(n=>{i[n]=this.getRpcUrl(n,s)}),i}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=C(this.rpc.chains),this.signer=await S.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let s;try{const{WalletConnectModal:i}=await import("@walletconnect/modal");s=i}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(s)try{this.modal=new s(I({walletConnectVersion:2,projectId:this.rpc.projectId,standaloneChains:this.rpc.chains},this.rpc.qrModalOptions))}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:s,optionalChains:i,rpcMap:n}=t;s&&v(s)&&(this.rpc.chains=s.map(e=>this.formatChainId(e)),s.forEach(e=>{this.rpc.rpcMap[e]=n?.[e]||this.getRpcUrl(e)})),i&&v(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(e=>this.formatChainId(e)),i.forEach(e=>{this.rpc.rpcMap[e]=n?.[e]||this.getRpcUrl(e)}))}getRpcUrl(t,s){var i;return((i=this.rpc.rpcMap)==null?void 0:i[t])||`${$}?chainId=eip155:${t}&projectId=${s||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const t=this.signer.rpcProviders.eip155.chainId;console.trace('namgold es eip155.chainId', t);this.setChainIds(t?[this.formatChainId(t)]:this.session.namespaces[this.namespace].accounts),this.setAccounts(this.session.namespaces[this.namespace].accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(s=>this.parseAccount(s))}}const W=m;export{W as EthereumProvider,U as OPTIONAL_EVENTS,D as OPTIONAL_METHODS,u as REQUIRED_EVENTS,p as REQUIRED_METHODS,m as default}; + //# sourceMappingURL=index.es.js.map +diff --git a/node_modules/@walletconnect/ethereum-provider/dist/index.umd.js b/node_modules/@walletconnect/ethereum-provider/dist/index.umd.js +index 83e05d2..7df0974 100644 +--- a/node_modules/@walletconnect/ethereum-provider/dist/index.umd.js ++++ b/node_modules/@walletconnect/ethereum-provider/dist/index.umd.js +@@ -95,7 +95,7 @@ __p += '`),wt&&(pe+=`' + + function print() { __p += __j.call(arguments, '') } + `:`; + `)+pe+`return __p +-}`;var ot=uw(function(){return vt(S,Pe+"return "+pe).apply(r,M)});if(ot.source=pe,X0(ot))throw ot;return ot}function qR(s){return yt(s).toLowerCase()}function VR(s){return yt(s).toUpperCase()}function KR(s,a,u){if(s=yt(s),s&&(u||a===r))return ym(s);if(!s||!(a=tn(a)))return s;var g=In(s),y=In(a),S=bm(g,y),M=_m(g,y)+1;return Ni(g,S,M).join("")}function GR(s,a,u){if(s=yt(s),s&&(u||a===r))return s.slice(0,xm(s)+1);if(!s||!(a=tn(a)))return s;var g=In(s),y=_m(g,In(a))+1;return Ni(g,0,y).join("")}function ZR(s,a,u){if(s=yt(s),s&&(u||a===r))return s.replace(Kt,"");if(!s||!(a=tn(a)))return s;var g=In(s),y=bm(g,In(a));return Ni(g,y).join("")}function YR(s,a){var u=z,g=ee;if(Bt(a)){var y="separator"in a?a.separator:y;u="length"in a?it(a.length):u,g="omission"in a?tn(a.omission):g}s=yt(s);var S=s.length;if(oo(s)){var M=In(s);S=M.length}if(u>=S)return s;var k=u-ao(g);if(k<1)return g;var Z=M?Ni(M,0,k).join(""):s.slice(0,k);if(y===r)return Z+g;if(M&&(k+=Z.length-k),Q0(y)){if(s.slice(k).search(y)){var ue,he=Z;for(y.global||(y=g0(y.source,yt(fn.exec(y))+"g")),y.lastIndex=0;ue=y.exec(he);)var pe=ue.index;Z=Z.slice(0,pe===r?k:pe)}}else if(s.indexOf(tn(y),k)!=k){var be=Z.lastIndexOf(y);be>-1&&(Z=Z.slice(0,be))}return Z+g}function JR(s){return s=yt(s),s&&zt.test(s)?s.replace(Ii,OS):s}var XR=go(function(s,a,u){return s+(u?" ":"")+a.toUpperCase()}),rd=h2("toUpperCase");function lw(s,a,u){return s=yt(s),a=u?r:a,a===r?_S(s)?DS(s):fS(s):s.match(a)||[]}var uw=ct(function(s,a){try{return vr(s,r,a)}catch(u){return X0(u)?u:new Ye(u)}}),QR=ii(function(s,a){return pn(a,function(u){u=Hn(u),ri(s,u,Y0(s[u],s))}),s});function eN(s){var a=s==null?0:s.length,u=ze();return s=a?Ut(s,function(g){if(typeof g[1]!="function")throw new gn(c);return[u(g[0]),g[1]]}):[],ct(function(g){for(var y=-1;++yre)return[];var u=ie,g=Ar(s,ie);a=ze(a),s-=ie;for(var y=f0(g,a);++u0||a<0)?new dt(u):(s<0?u=u.takeRight(-s):s&&(u=u.drop(s)),a!==r&&(a=it(a),u=a<0?u.dropRight(-a):u.take(a-s)),u)},dt.prototype.takeRightWhile=function(s){return this.reverse().takeWhile(s).reverse()},dt.prototype.toArray=function(){return this.take(ie)},Bn(dt.prototype,function(s,a){var u=/^(?:filter|find|map|reject)|While$/.test(a),g=/^(?:head|last)$/.test(a),y=C[g?"take"+(a=="last"?"Right":""):a],S=g||/^find/.test(a);y&&(C.prototype[a]=function(){var M=this.__wrapped__,k=g?[1]:arguments,Z=M instanceof dt,ue=k[0],he=Z||Qe(M),pe=function(ft){var wt=y.apply(C,Si([ft],k));return g&&be?wt[0]:wt};he&&u&&typeof ue=="function"&&ue.length!=1&&(Z=he=!1);var be=this.__chain__,Pe=!!this.__actions__.length,We=S&&!be,ot=Z&&!Pe;if(!S&&he){M=ot?M:new dt(this);var qe=s.apply(M,k);return qe.__actions__.push({func:Wl,args:[pe],thisArg:r}),new mn(qe,be)}return We&&ot?s.apply(this,k):(qe=this.thru(pe),We?g?qe.value()[0]:qe.value():qe)})}),pn(["pop","push","shift","sort","splice","unshift"],function(s){var a=ml[s],u=/^(?:push|sort|unshift)$/.test(s)?"tap":"thru",g=/^(?:pop|shift)$/.test(s);C.prototype[s]=function(){var y=arguments;if(g&&!this.__chain__){var S=this.value();return a.apply(Qe(S)?S:[],y)}return this[u](function(M){return a.apply(Qe(M)?M:[],y)})}}),Bn(dt.prototype,function(s,a){var u=C[a];if(u){var g=u.name+"";bt.call(ho,g)||(ho[g]=[]),ho[g].push({name:a,func:u})}}),ho[Ul(r,G).name]=[{name:"wrapper",func:r}],dt.prototype.clone=JS,dt.prototype.reverse=XS,dt.prototype.value=QS,C.prototype.at=SP,C.prototype.chain=DP,C.prototype.commit=$P,C.prototype.next=PP,C.prototype.plant=RP,C.prototype.reverse=NP,C.prototype.toJSON=C.prototype.valueOf=C.prototype.value=LP,C.prototype.first=C.prototype.head,_a&&(C.prototype[_a]=TP),C},co=$S();Qt?((Qt.exports=co)._=co,Ot._=co):mt._=co}).call(Wo)})(gh,gh.exports);var b7=Object.defineProperty,_7=Object.defineProperties,E7=Object.getOwnPropertyDescriptors,Eg=Object.getOwnPropertySymbols,x7=Object.prototype.hasOwnProperty,C7=Object.prototype.propertyIsEnumerable,xg=(t,e,r)=>e in t?b7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,oc=(t,e)=>{for(var r in e||(e={}))x7.call(e,r)&&xg(t,r,e[r]);if(Eg)for(var r of Eg(e))C7.call(e,r)&&xg(t,r,e[r]);return t},I7=(t,e)=>_7(t,E7(e));function cn(t,e,r){let n;const i=mh(t);return e.rpcMap&&(n=e.rpcMap[i]),n||(n=`${y7}?chainId=eip155:${i}&projectId=${r}`),n}function mh(t){return t.includes("eip155")?Number(t.split(":")[1]):Number(t)}function O7(t,e){if(!e.includes(t))throw new Error(`Chain '${t}' not approved. Please use one of the following: ${e.toString()}`)}function A7(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function S7(t,e){const r=Object.keys(e.namespaces).filter(i=>i.includes(t));if(!r.length)return[];const n=[];return r.forEach(i=>{const o=e.namespaces[i].accounts;n.push(...o)}),n}function D7(t,e={}){const r=Cg(t),n=Cg(e);return gh.exports.merge(r,n)}function Cg(t){var e,r,n,i;const o={};if(!Ds(t))return o;for(const[c,l]of Object.entries(t)){const h=M1(c)?[c]:l.chains,d=l.methods||[],v=l.events||[],x=l.rpcMap||{},_=Za(c);o[_]=I7(oc(oc({},o[_]),l),{chains:Su(h,(e=o[_])==null?void 0:e.chains),methods:Su(d,(r=o[_])==null?void 0:r.methods),events:Su(v,(n=o[_])==null?void 0:n.events),rpcMap:oc(oc({},x),(i=o[_])==null?void 0:i.rpcMap)})}return o}const Ig={},Jt=t=>Ig[t],wh=(t,e)=>{Ig[t]=e};class $7{constructor(e){this.name="polkadot",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class P7{constructor(e){this.name="eip155",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){var r;switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return this.handleSwitchChain(e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0"),null;case"eth_chainId":return parseInt(this.getDefaultChain())}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,r){const n=mh(e);if(!this.httpProviders[n]){const i=r||cn(`${this.name}:${n}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${n}`);this.setHttpProvider(n,i)}this.chainId=n,this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${n}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,r){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=mh(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}handleSwitchChain(e){const r=parseInt(e,16),n=`${this.name}:${r}`;O7(n,this.namespace.chains),this.setDefaultChain(`${r}`)}}class T7{constructor(e){this.name="solana",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class R7{constructor(e){this.name="cosmos",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class N7{constructor(e){this.name="cip34",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||this.getCardanoRPCUrl(e);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const n=this.getCardanoRPCUrl(r);e[r]=this.createHttpProvider(r,n)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||this.getCardanoRPCUrl(e);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class L7{constructor(e){this.name="elrond",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class M7{constructor(e){this.name="multiversx",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}var U7=Object.defineProperty,j7=Object.defineProperties,F7=Object.getOwnPropertyDescriptors,Og=Object.getOwnPropertySymbols,B7=Object.prototype.hasOwnProperty,k7=Object.prototype.propertyIsEnumerable,Ag=(t,e,r)=>e in t?U7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ac=(t,e)=>{for(var r in e||(e={}))B7.call(e,r)&&Ag(t,r,e[r]);if(Og)for(var r of Og(e))k7.call(e,r)&&Ag(t,r,e[r]);return t},vh=(t,e)=>j7(t,F7(e));class yh{constructor(e){this.events=new br.exports,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||bg})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new yh(e);return await r.initialize(),r}async request(e,r){const[n,i]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:ac({},e),chainId:`${n}:${i}`,topic:this.session.topic})}sendAsync(e,r,n){this.request(e,n).then(i=>r(null,i)).catch(i=>r(i,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Yt("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){this.shouldAbortPairingAttempt=!1;let r=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(r>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:n,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});n&&(this.uri=n,this.events.emit("display_uri",n)),await i().then(o=>{this.session=o}).catch(o=>{if(o.message!==pg)throw o;r++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(e,r){try{const[n,i]=this.validateChain(e);this.getProvider(n).setDefaultChain(i,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(zn(r)){for(const n of r)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await dh.init({logger:this.providerOpts.logger||bg,relayUrl:this.providerOpts.relayUrl||m7,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,name:this.providerOpts.name}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(r=>Za(r)))];wh("client",this.client),wh("events",this.events),wh("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const n=S7(r,this.session),i=A7(n),o=D7(this.namespaces,this.optionalNamespaces),c=vh(ac({},o[r]),{accounts:n,chains:i});switch(r){case"eip155":this.rpcProviders[r]=new P7({namespace:c});break;case"solana":this.rpcProviders[r]=new T7({namespace:c});break;case"cosmos":this.rpcProviders[r]=new R7({namespace:c});break;case"polkadot":this.rpcProviders[r]=new $7({namespace:c});break;case"cip34":this.rpcProviders[r]=new N7({namespace:c});break;case"elrond":this.rpcProviders[r]=new L7({namespace:c});break;case"multiversx":this.rpcProviders[r]=new M7({namespace:c});break}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?this.events.emit("accountsChanged",n.data):n.name==="chainChanged"?this.onChainChanged(r.chainId):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var n;const{namespaces:i}=r,o=(n=this.client)==null?void 0:n.session.get(e);this.session=vh(ac({},o),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",vh(ac({},Yt("USER_DISCONNECTED")),{data:e.topic}))}),this.on(di.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){if(!this.rpcProviders[e])throw new Error(`Provider not found: ${e}`);return this.rpcProviders[e]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r,optionalNamespaces:n,sessionProperties:i}=e;if(!r||!Object.keys(r).length)throw new Error("Namespaces must be not empty");this.namespaces=r,this.optionalNamespaces=n,this.sessionProperties=i,this.persist("namespaces",r),this.persist("optionalNamespaces",n)}validateChain(e){const[r,n]=e?.split(":")||["",""];if(r&&!Object.keys(this.namespaces).map(c=>Za(c)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];const i=Za(Object.keys(this.namespaces)[0]),o=this.rpcProviders[i].getDefaultChain();return[i,o]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,r=!1){var n;const[i,o]=this.validateChain(e);r||this.getProvider(i).setDefaultChain(o),((n=this.namespaces[i])!=null?n:this.namespaces[`${i}:${o}`]).defaultChain=o,this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",o)}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0})}persist(e,r){this.client.core.storage.setItem(`${_g}/${e}`,r)}async getFromStore(e){return await this.client.core.storage.getItem(`${_g}/${e}`)}}const H7=yh,z7="wc",W7="ethereum_provider",q7=`${z7}@2:${W7}:`,V7="https://rpc.walletconnect.com/v1/",cc=["eth_sendTransaction","personal_sign"],K7=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],lc=["chainChanged","accountsChanged"],G7=["message","disconnect","connect"];var Z7=Object.defineProperty,Y7=Object.defineProperties,J7=Object.getOwnPropertyDescriptors,Sg=Object.getOwnPropertySymbols,X7=Object.prototype.hasOwnProperty,Q7=Object.prototype.propertyIsEnumerable,Dg=(t,e,r)=>e in t?Z7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bh=(t,e)=>{for(var r in e||(e={}))X7.call(e,r)&&Dg(t,r,e[r]);if(Sg)for(var r of Sg(e))Q7.call(e,r)&&Dg(t,r,e[r]);return t},$g=(t,e)=>Y7(t,J7(e));function _h(t){return Number(t[0].split(":")[1])}function Eh(t){return`0x${t.toString(16)}`}function ex(t){const{chains:e,optionalChains:r,methods:n,optionalMethods:i,events:o,optionalEvents:c,rpcMap:l}=t;if(!zn(e))throw new Error("Invalid chains");const h=e,d=n||cc,v=o||lc,x={[_h(h)]:l[_h(h)]},_={chains:h,methods:d,events:v,rpcMap:x},O=o?.filter(G=>!lc.includes(G)),P=n?.filter(G=>!cc.includes(G));if(!r&&!c&&!i&&!(O!=null&&O.length)&&!(P!=null&&P.length))return{required:_};const U=O?.length&&P?.length||!r,H={chains:[...new Set(U?h.concat(r||[]):r)],methods:[...new Set(d.concat(i||[]))],events:[...new Set(v.concat(c||[]))],rpcMap:l};return{required:_,optional:H}}class uc{constructor(){this.events=new br.exports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=q7,this.on=(e,r)=>(this.events.on(e,r),this),this.once=(e,r)=>(this.events.once(e,r),this),this.removeListener=(e,r)=>(this.events.removeListener(e,r),this),this.off=(e,r)=>(this.events.off(e,r),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(e){const r=new uc;return await r.initialize(e),r}async request(e){return await this.signer.request(e,this.formatChainId(this.chainId))}sendAsync(e,r){this.signer.sendAsync(e,r,this.formatChainId(this.chainId))}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:n}=ex(this.rpc);try{const i=await new Promise(async(c,l)=>{var h;this.rpc.showQrModal&&((h=this.modal)==null||h.subscribeModal(d=>{!d.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),l(new Error("Connection request reset. Please try again.")))})),await this.signer.connect($g(bh({namespaces:{[this.namespace]:r}},n&&{optionalNamespaces:{[this.namespace]:n}}),{pairingTopic:e?.pairingTopic})).then(d=>{c(d)}).catch(d=>{l(new Error(d.message))})});if(!i)return;this.setChainIds(this.rpc.chains);const o=N5(i.namespaces,[this.namespace]);this.setAccounts(o),this.events.emit("connect",{chainId:Eh(this.chainId)})}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",Eh(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",$g(bh({},Yt("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var r,n;this.rpc.showQrModal&&((r=this.modal)==null||r.closeModal(),(n=this.modal)==null||n.openModal({uri:e})),this.events.emit("display_uri",e)})}setHttpProvider(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",Eh(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.setHttpProvider(r)}}parseAccountId(e){const[r,n,i]=e.split(":");return{chainId:`${r}:${n}`,address:i}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,n;return{chains:((r=e.chains)==null?void 0:r.map(i=>this.formatChainId(i)))||[`${this.namespace}:1`],optionalChains:e.optionalChains?e.optionalChains.map(i=>this.formatChainId(i)):void 0,methods:e?.methods||cc,events:e?.events||lc,optionalMethods:e?.optionalMethods||[],optionalEvents:e?.optionalEvents||[],rpcMap:e?.rpcMap||this.buildRpcMap(e.chains.concat(e.optionalChains||[]),e.projectId),showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:(n=e?.qrModalOptions)!=null?n:void 0,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const n={};return e.forEach(i=>{n[i]=this.getRpcUrl(i,r)}),n}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=_h(this.rpc.chains),this.signer=await H7.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{const{WalletConnectModal:n}=await Promise.resolve().then(function(){return Px});r=n}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(r)try{this.modal=new r(bh({walletConnectVersion:2,projectId:this.rpc.projectId,standaloneChains:this.rpc.chains},this.rpc.qrModalOptions))}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:n,rpcMap:i}=e;r&&zn(r)&&(this.rpc.chains=r.map(o=>this.formatChainId(o)),r.forEach(o=>{this.rpc.rpcMap[o]=i?.[o]||this.getRpcUrl(o)})),n&&zn(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(o=>this.formatChainId(o)),n.forEach(o=>{this.rpc.rpcMap[o]=i?.[o]||this.getRpcUrl(o)}))}getRpcUrl(e,r){var n;return((n=this.rpc.rpcMap)==null?void 0:n[e])||`${V7}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`);this.setChainIds(e?[this.formatChainId(e)]:this.session.namespaces[this.namespace].accounts),this.setAccounts(this.session.namespaces[this.namespace].accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const tx=uc,rx=Symbol(),Pg=Object.getPrototypeOf,xh=new WeakMap,nx=t=>t&&(xh.has(t)?xh.get(t):Pg(t)===Object.prototype||Pg(t)===Array.prototype),ix=t=>nx(t)&&t[rx]||null,Tg=(t,e=!0)=>{xh.set(t,e)},Ch=t=>typeof t=="object"&&t!==null,pi=new WeakMap,hc=new WeakSet,sx=(t=Object.is,e=(d,v)=>new Proxy(d,v),r=d=>Ch(d)&&!hc.has(d)&&(Array.isArray(d)||!(Symbol.iterator in d))&&!(d instanceof WeakMap)&&!(d instanceof WeakSet)&&!(d instanceof Error)&&!(d instanceof Number)&&!(d instanceof Date)&&!(d instanceof String)&&!(d instanceof RegExp)&&!(d instanceof ArrayBuffer),n=d=>{switch(d.status){case"fulfilled":return d.value;case"rejected":throw d.reason;default:throw d}},i=new WeakMap,o=(d,v,x=n)=>{const _=i.get(d);if(_?.[0]===v)return _[1];const O=Array.isArray(d)?[]:Object.create(Object.getPrototypeOf(d));return Tg(O,!0),i.set(d,[v,O]),Reflect.ownKeys(d).forEach(P=>{if(Object.getOwnPropertyDescriptor(O,P))return;const U=Reflect.get(d,P),H={value:U,enumerable:!0,configurable:!0};if(hc.has(U))Tg(U,!1);else if(U instanceof Promise)delete H.value,H.get=()=>x(U);else if(pi.has(U)){const[G,N]=pi.get(U);H.value=o(G,N(),x)}Object.defineProperty(O,P,H)}),O},c=new WeakMap,l=[1,1],h=d=>{if(!Ch(d))throw new Error("object required");const v=c.get(d);if(v)return v;let x=l[0];const _=new Set,O=(J,z=++l[0])=>{x!==z&&(x=z,_.forEach(ee=>ee(J,z)))};let P=l[1];const U=(J=++l[1])=>(P!==J&&!_.size&&(P=J,G.forEach(([z])=>{const ee=z[1](J);ee>x&&(x=ee)})),x),H=J=>(z,ee)=>{const de=[...z];de[1]=[J,...de[1]],O(de,ee)},G=new Map,N=(J,z)=>{if(G.has(J))throw new Error("prop listener already exists");if(_.size){const ee=z[3](H(J));G.set(J,[z,ee])}else G.set(J,[z])},L=J=>{var z;const ee=G.get(J);ee&&(G.delete(J),(z=ee[1])==null||z.call(ee))},$=J=>(_.add(J),_.size===1&&G.forEach(([ee,de],me)=>{if(de)throw new Error("remove already exists");const A=ee[3](H(me));G.set(me,[ee,A])}),()=>{_.delete(J),_.size===0&&G.forEach(([ee,de],me)=>{de&&(de(),G.set(me,[ee]))})}),T=Array.isArray(d)?[]:Object.create(Object.getPrototypeOf(d)),f=e(T,{deleteProperty(J,z){const ee=Reflect.get(J,z);L(z);const de=Reflect.deleteProperty(J,z);return de&&O(["delete",[z],ee]),de},set(J,z,ee,de){const me=Reflect.has(J,z),A=Reflect.get(J,z,de);if(me&&(t(A,ee)||c.has(ee)&&t(A,c.get(ee))))return!0;L(z),Ch(ee)&&(ee=ix(ee)||ee);let j=ee;if(ee instanceof Promise)ee.then(ce=>{ee.status="fulfilled",ee.value=ce,O(["resolve",[z],ce])}).catch(ce=>{ee.status="rejected",ee.reason=ce,O(["reject",[z],ce])});else{!pi.has(ee)&&r(ee)&&(j=h(ee));const ce=!hc.has(j)&&pi.get(j);ce&&N(z,ce)}return Reflect.set(J,z,j,de),O(["set",[z],ee,A]),!0}});c.set(d,f);const E=[T,U,o,$];return pi.set(f,E),Reflect.ownKeys(d).forEach(J=>{const z=Object.getOwnPropertyDescriptor(d,J);"value"in z&&(f[J]=d[J],delete z.value,delete z.writable),Object.defineProperty(T,J,z)}),f})=>[h,pi,hc,t,e,r,n,i,o,c,l],[ox]=sx();function Rn(t={}){return ox(t)}function Kn(t,e,r){const n=pi.get(t);n||console.warn("Please use proxy object");let i;const o=[],c=n[3];let l=!1;const d=c(v=>{if(o.push(v),r){e(o.splice(0));return}i||(i=Promise.resolve().then(()=>{i=void 0,l&&e(o.splice(0))}))});return l=!0,()=>{l=!1,d()}}function ax(t,e){const r=pi.get(t);r||console.warn("Please use proxy object");const[n,i,o]=r;return o(n,i(),e)}var Rg={},fc={};fc.byteLength=ux,fc.toByteArray=fx,fc.fromByteArray=gx;for(var Nn=[],ln=[],cx=typeof Uint8Array<"u"?Uint8Array:Array,Ih="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ps=0,lx=Ih.length;Ps0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function ux(t){var e=Ng(t),r=e[0],n=e[1];return(r+n)*3/4-n}function hx(t,e,r){return(e+r)*3/4-r}function fx(t){var e,r=Ng(t),n=r[0],i=r[1],o=new cx(hx(t,n,i)),c=0,l=i>0?n-4:n,h;for(h=0;h>16&255,o[c++]=e>>8&255,o[c++]=e&255;return i===2&&(e=ln[t.charCodeAt(h)]<<2|ln[t.charCodeAt(h+1)]>>4,o[c++]=e&255),i===1&&(e=ln[t.charCodeAt(h)]<<10|ln[t.charCodeAt(h+1)]<<4|ln[t.charCodeAt(h+2)]>>2,o[c++]=e>>8&255,o[c++]=e&255),o}function dx(t){return Nn[t>>18&63]+Nn[t>>12&63]+Nn[t>>6&63]+Nn[t&63]}function px(t,e,r){for(var n,i=[],o=e;ol?l:c+o));return n===1?(e=t[r-1],i.push(Nn[e>>2]+Nn[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Nn[e>>10]+Nn[e>>4&63]+Nn[e<<2&63]+"=")),i.join("")}var Oh={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */Oh.read=function(t,e,r,n,i){var o,c,l=i*8-n-1,h=(1<>1,v=-7,x=r?i-1:0,_=r?-1:1,O=t[e+x];for(x+=_,o=O&(1<<-v)-1,O>>=-v,v+=l;v>0;o=o*256+t[e+x],x+=_,v-=8);for(c=o&(1<<-v)-1,o>>=-v,v+=n;v>0;c=c*256+t[e+x],x+=_,v-=8);if(o===0)o=1-d;else{if(o===h)return c?NaN:(O?-1:1)*(1/0);c=c+Math.pow(2,n),o=o-d}return(O?-1:1)*c*Math.pow(2,o-n)},Oh.write=function(t,e,r,n,i,o){var c,l,h,d=o*8-i-1,v=(1<>1,_=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,O=n?0:o-1,P=n?1:-1,U=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,c=v):(c=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-c))<1&&(c--,h*=2),c+x>=1?e+=_/h:e+=_*Math.pow(2,1-x),e*h>=2&&(c++,h/=2),c+x>=v?(l=0,c=v):c+x>=1?(l=(e*h-1)*Math.pow(2,i),c=c+x):(l=e*Math.pow(2,x-1)*Math.pow(2,i),c=0));i>=8;t[r+O]=l&255,O+=P,l/=256,i-=8);for(c=c<0;t[r+O]=c&255,O+=P,c/=256,d-=8);t[r+O-P]|=U*128};/*! ++}`;var ot=uw(function(){return vt(S,Pe+"return "+pe).apply(r,M)});if(ot.source=pe,X0(ot))throw ot;return ot}function qR(s){return yt(s).toLowerCase()}function VR(s){return yt(s).toUpperCase()}function KR(s,a,u){if(s=yt(s),s&&(u||a===r))return ym(s);if(!s||!(a=tn(a)))return s;var g=In(s),y=In(a),S=bm(g,y),M=_m(g,y)+1;return Ni(g,S,M).join("")}function GR(s,a,u){if(s=yt(s),s&&(u||a===r))return s.slice(0,xm(s)+1);if(!s||!(a=tn(a)))return s;var g=In(s),y=_m(g,In(a))+1;return Ni(g,0,y).join("")}function ZR(s,a,u){if(s=yt(s),s&&(u||a===r))return s.replace(Kt,"");if(!s||!(a=tn(a)))return s;var g=In(s),y=bm(g,In(a));return Ni(g,y).join("")}function YR(s,a){var u=z,g=ee;if(Bt(a)){var y="separator"in a?a.separator:y;u="length"in a?it(a.length):u,g="omission"in a?tn(a.omission):g}s=yt(s);var S=s.length;if(oo(s)){var M=In(s);S=M.length}if(u>=S)return s;var k=u-ao(g);if(k<1)return g;var Z=M?Ni(M,0,k).join(""):s.slice(0,k);if(y===r)return Z+g;if(M&&(k+=Z.length-k),Q0(y)){if(s.slice(k).search(y)){var ue,he=Z;for(y.global||(y=g0(y.source,yt(fn.exec(y))+"g")),y.lastIndex=0;ue=y.exec(he);)var pe=ue.index;Z=Z.slice(0,pe===r?k:pe)}}else if(s.indexOf(tn(y),k)!=k){var be=Z.lastIndexOf(y);be>-1&&(Z=Z.slice(0,be))}return Z+g}function JR(s){return s=yt(s),s&&zt.test(s)?s.replace(Ii,OS):s}var XR=go(function(s,a,u){return s+(u?" ":"")+a.toUpperCase()}),rd=h2("toUpperCase");function lw(s,a,u){return s=yt(s),a=u?r:a,a===r?_S(s)?DS(s):fS(s):s.match(a)||[]}var uw=ct(function(s,a){try{return vr(s,r,a)}catch(u){return X0(u)?u:new Ye(u)}}),QR=ii(function(s,a){return pn(a,function(u){u=Hn(u),ri(s,u,Y0(s[u],s))}),s});function eN(s){var a=s==null?0:s.length,u=ze();return s=a?Ut(s,function(g){if(typeof g[1]!="function")throw new gn(c);return[u(g[0]),g[1]]}):[],ct(function(g){for(var y=-1;++yre)return[];var u=ie,g=Ar(s,ie);a=ze(a),s-=ie;for(var y=f0(g,a);++u0||a<0)?new dt(u):(s<0?u=u.takeRight(-s):s&&(u=u.drop(s)),a!==r&&(a=it(a),u=a<0?u.dropRight(-a):u.take(a-s)),u)},dt.prototype.takeRightWhile=function(s){return this.reverse().takeWhile(s).reverse()},dt.prototype.toArray=function(){return this.take(ie)},Bn(dt.prototype,function(s,a){var u=/^(?:filter|find|map|reject)|While$/.test(a),g=/^(?:head|last)$/.test(a),y=C[g?"take"+(a=="last"?"Right":""):a],S=g||/^find/.test(a);y&&(C.prototype[a]=function(){var M=this.__wrapped__,k=g?[1]:arguments,Z=M instanceof dt,ue=k[0],he=Z||Qe(M),pe=function(ft){var wt=y.apply(C,Si([ft],k));return g&&be?wt[0]:wt};he&&u&&typeof ue=="function"&&ue.length!=1&&(Z=he=!1);var be=this.__chain__,Pe=!!this.__actions__.length,We=S&&!be,ot=Z&&!Pe;if(!S&&he){M=ot?M:new dt(this);var qe=s.apply(M,k);return qe.__actions__.push({func:Wl,args:[pe],thisArg:r}),new mn(qe,be)}return We&&ot?s.apply(this,k):(qe=this.thru(pe),We?g?qe.value()[0]:qe.value():qe)})}),pn(["pop","push","shift","sort","splice","unshift"],function(s){var a=ml[s],u=/^(?:push|sort|unshift)$/.test(s)?"tap":"thru",g=/^(?:pop|shift)$/.test(s);C.prototype[s]=function(){var y=arguments;if(g&&!this.__chain__){var S=this.value();return a.apply(Qe(S)?S:[],y)}return this[u](function(M){return a.apply(Qe(M)?M:[],y)})}}),Bn(dt.prototype,function(s,a){var u=C[a];if(u){var g=u.name+"";bt.call(ho,g)||(ho[g]=[]),ho[g].push({name:a,func:u})}}),ho[Ul(r,G).name]=[{name:"wrapper",func:r}],dt.prototype.clone=JS,dt.prototype.reverse=XS,dt.prototype.value=QS,C.prototype.at=SP,C.prototype.chain=DP,C.prototype.commit=$P,C.prototype.next=PP,C.prototype.plant=RP,C.prototype.reverse=NP,C.prototype.toJSON=C.prototype.valueOf=C.prototype.value=LP,C.prototype.first=C.prototype.head,_a&&(C.prototype[_a]=TP),C},co=$S();Qt?((Qt.exports=co)._=co,Ot._=co):mt._=co}).call(Wo)})(gh,gh.exports);var b7=Object.defineProperty,_7=Object.defineProperties,E7=Object.getOwnPropertyDescriptors,Eg=Object.getOwnPropertySymbols,x7=Object.prototype.hasOwnProperty,C7=Object.prototype.propertyIsEnumerable,xg=(t,e,r)=>e in t?b7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,oc=(t,e)=>{for(var r in e||(e={}))x7.call(e,r)&&xg(t,r,e[r]);if(Eg)for(var r of Eg(e))C7.call(e,r)&&xg(t,r,e[r]);return t},I7=(t,e)=>_7(t,E7(e));function cn(t,e,r){let n;const i=mh(t);return e.rpcMap&&(n=e.rpcMap[i]),n||(n=`${y7}?chainId=eip155:${i}&projectId=${r}`),n}function mh(t){return t.includes("eip155")?Number(t.split(":")[1]):Number(t)}function O7(t,e){if(!e.includes(t))throw new Error(`Chain '${t}' not approved. Please use one of the following: ${e.toString()}`)}function A7(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function S7(t,e){const r=Object.keys(e.namespaces).filter(i=>i.includes(t));if(!r.length)return[];const n=[];return r.forEach(i=>{const o=e.namespaces[i].accounts;n.push(...o)}),n}function D7(t,e={}){const r=Cg(t),n=Cg(e);return gh.exports.merge(r,n)}function Cg(t){var e,r,n,i;const o={};if(!Ds(t))return o;for(const[c,l]of Object.entries(t)){const h=M1(c)?[c]:l.chains,d=l.methods||[],v=l.events||[],x=l.rpcMap||{},_=Za(c);o[_]=I7(oc(oc({},o[_]),l),{chains:Su(h,(e=o[_])==null?void 0:e.chains),methods:Su(d,(r=o[_])==null?void 0:r.methods),events:Su(v,(n=o[_])==null?void 0:n.events),rpcMap:oc(oc({},x),(i=o[_])==null?void 0:i.rpcMap)})}return o}const Ig={},Jt=t=>Ig[t],wh=(t,e)=>{Ig[t]=e};class $7{constructor(e){this.name="polkadot",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class P7{constructor(e){this.name="eip155",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){var r;switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return this.handleSwitchChain(e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0"),null;case"eth_chainId":return parseInt(this.getDefaultChain())}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,r){const n=mh(e);if(!this.httpProviders[n]){const i=r||cn(`${this.name}:${n}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${n}`);this.setHttpProvider(n,i)}this.chainId=n,this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${n}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,r){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=mh(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}handleSwitchChain(e){const r=parseInt(e,16),n=`${this.name}:${r}`;O7(n,this.namespace.chains),this.setDefaultChain(`${r}`)}}class T7{constructor(e){this.name="solana",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class R7{constructor(e){this.name="cosmos",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class N7{constructor(e){this.name="cip34",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||this.getCardanoRPCUrl(e);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const n=this.getCardanoRPCUrl(r);e[r]=this.createHttpProvider(r,n)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||this.getCardanoRPCUrl(e);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class L7{constructor(e){this.name="elrond",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}class M7{constructor(e){this.name="multiversx",this.namespace=e.namespace,this.events=Jt("events"),this.client=Jt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const n=r||cn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(di.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||cn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new hi(new Vi(n,Jt("disableProviderPing")))}}var U7=Object.defineProperty,j7=Object.defineProperties,F7=Object.getOwnPropertyDescriptors,Og=Object.getOwnPropertySymbols,B7=Object.prototype.hasOwnProperty,k7=Object.prototype.propertyIsEnumerable,Ag=(t,e,r)=>e in t?U7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ac=(t,e)=>{for(var r in e||(e={}))B7.call(e,r)&&Ag(t,r,e[r]);if(Og)for(var r of Og(e))k7.call(e,r)&&Ag(t,r,e[r]);return t},vh=(t,e)=>j7(t,F7(e));class yh{constructor(e){this.events=new br.exports,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||bg})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new yh(e);return await r.initialize(),r}async request(e,r){const[n,i]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:ac({},e),chainId:`${n}:${i}`,topic:this.session.topic})}sendAsync(e,r,n){this.request(e,n).then(i=>r(null,i)).catch(i=>r(i,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Yt("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){this.shouldAbortPairingAttempt=!1;let r=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(r>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:n,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});n&&(this.uri=n,this.events.emit("display_uri",n)),await i().then(o=>{this.session=o}).catch(o=>{if(o.message!==pg)throw o;r++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(e,r){try{const[n,i]=this.validateChain(e);this.getProvider(n).setDefaultChain(i,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(zn(r)){for(const n of r)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await dh.init({logger:this.providerOpts.logger||bg,relayUrl:this.providerOpts.relayUrl||m7,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,name:this.providerOpts.name}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(r=>Za(r)))];wh("client",this.client),wh("events",this.events),wh("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const n=S7(r,this.session),i=A7(n),o=D7(this.namespaces,this.optionalNamespaces),c=vh(ac({},o[r]),{accounts:n,chains:i});switch(r){case"eip155":this.rpcProviders[r]=new P7({namespace:c});break;case"solana":this.rpcProviders[r]=new T7({namespace:c});break;case"cosmos":this.rpcProviders[r]=new R7({namespace:c});break;case"polkadot":this.rpcProviders[r]=new $7({namespace:c});break;case"cip34":this.rpcProviders[r]=new N7({namespace:c});break;case"elrond":this.rpcProviders[r]=new L7({namespace:c});break;case"multiversx":this.rpcProviders[r]=new M7({namespace:c});break}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?this.events.emit("accountsChanged",n.data):n.name==="chainChanged"?this.onChainChanged(r.chainId):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var n;const{namespaces:i}=r,o=(n=this.client)==null?void 0:n.session.get(e);this.session=vh(ac({},o),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",vh(ac({},Yt("USER_DISCONNECTED")),{data:e.topic}))}),this.on(di.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){if(!this.rpcProviders[e])throw new Error(`Provider not found: ${e}`);return this.rpcProviders[e]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r,optionalNamespaces:n,sessionProperties:i}=e;if(!r||!Object.keys(r).length)throw new Error("Namespaces must be not empty");this.namespaces=r,this.optionalNamespaces=n,this.sessionProperties=i,this.persist("namespaces",r),this.persist("optionalNamespaces",n)}validateChain(e){const[r,n]=e?.split(":")||["",""];if(r&&!Object.keys(this.namespaces).map(c=>Za(c)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];const i=Za(Object.keys(this.namespaces)[0]),o=this.rpcProviders[i].getDefaultChain();return[i,o]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,r=!1){var n;const[i,o]=this.validateChain(e);r||this.getProvider(i).setDefaultChain(o),((n=this.namespaces[i])!=null?n:this.namespaces[`${i}:${o}`]).defaultChain=o,this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",o)}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0})}persist(e,r){this.client.core.storage.setItem(`${_g}/${e}`,r)}async getFromStore(e){return await this.client.core.storage.getItem(`${_g}/${e}`)}}const H7=yh,z7="wc",W7="ethereum_provider",q7=`${z7}@2:${W7}:`,V7="https://rpc.walletconnect.com/v1/",cc=["eth_sendTransaction","personal_sign"],K7=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],lc=["chainChanged","accountsChanged"],G7=["message","disconnect","connect"];var Z7=Object.defineProperty,Y7=Object.defineProperties,J7=Object.getOwnPropertyDescriptors,Sg=Object.getOwnPropertySymbols,X7=Object.prototype.hasOwnProperty,Q7=Object.prototype.propertyIsEnumerable,Dg=(t,e,r)=>e in t?Z7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bh=(t,e)=>{for(var r in e||(e={}))X7.call(e,r)&&Dg(t,r,e[r]);if(Sg)for(var r of Sg(e))Q7.call(e,r)&&Dg(t,r,e[r]);return t},$g=(t,e)=>Y7(t,J7(e));function _h(t){return Number(t[0].split(":")[1])}function Eh(t){return`0x${t.toString(16)}`}function ex(t){const{chains:e,optionalChains:r,methods:n,optionalMethods:i,events:o,optionalEvents:c,rpcMap:l}=t;if(!zn(e))throw new Error("Invalid chains");const h=e,d=n||cc,v=o||lc,x={[_h(h)]:l[_h(h)]},_={chains:h,methods:d,events:v,rpcMap:x},O=o?.filter(G=>!lc.includes(G)),P=n?.filter(G=>!cc.includes(G));if(!r&&!c&&!i&&!(O!=null&&O.length)&&!(P!=null&&P.length))return{required:_};const U=O?.length&&P?.length||!r,H={chains:[...new Set(U?h.concat(r||[]):r)],methods:[...new Set(d.concat(i||[]))],events:[...new Set(v.concat(c||[]))],rpcMap:l};return{required:_,optional:H}}class uc{constructor(){this.events=new br.exports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=q7,this.on=(e,r)=>(this.events.on(e,r),this),this.once=(e,r)=>(this.events.once(e,r),this),this.removeListener=(e,r)=>(this.events.removeListener(e,r),this),this.off=(e,r)=>(this.events.off(e,r),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(e){const r=new uc;return await r.initialize(e),r}async request(e){return await this.signer.request(e,this.formatChainId(this.chainId))}sendAsync(e,r){this.signer.sendAsync(e,r,this.formatChainId(this.chainId))}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:n}=ex(this.rpc);try{const i=await new Promise(async(c,l)=>{var h;this.rpc.showQrModal&&((h=this.modal)==null||h.subscribeModal(d=>{!d.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),l(new Error("Connection request reset. Please try again.")))})),await this.signer.connect($g(bh({namespaces:{[this.namespace]:r}},n&&{optionalNamespaces:{[this.namespace]:n}}),{pairingTopic:e?.pairingTopic})).then(d=>{c(d)}).catch(d=>{l(new Error(d.message))})});if(!i)return;const chainId = this.signer.rpcProviders.eip155.chainId;console.trace('namgold umd chainId', chainId, this.signer);this.setChainIds([this.formatChainId(chainId)]);const o=N5(i.namespaces,[this.namespace]);this.setAccounts(o),this.events.emit("connect",{chainId:Eh(this.chainId)})}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",Eh(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",$g(bh({},Yt("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var r,n;this.rpc.showQrModal&&((r=this.modal)==null||r.closeModal(),(n=this.modal)==null||n.openModal({uri:e})),this.events.emit("display_uri",e)})}setHttpProvider(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",Eh(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.setHttpProvider(r)}}parseAccountId(e){const[r,n,i]=e.split(":");return{chainId:`${r}:${n}`,address:i}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,n;return{chains:((r=e.chains)==null?void 0:r.map(i=>this.formatChainId(i)))||[`${this.namespace}:1`],optionalChains:e.optionalChains?e.optionalChains.map(i=>this.formatChainId(i)):void 0,methods:e?.methods||cc,events:e?.events||lc,optionalMethods:e?.optionalMethods||[],optionalEvents:e?.optionalEvents||[],rpcMap:e?.rpcMap||this.buildRpcMap(e.chains.concat(e.optionalChains||[]),e.projectId),showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:(n=e?.qrModalOptions)!=null?n:void 0,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const n={};return e.forEach(i=>{n[i]=this.getRpcUrl(i,r)}),n}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=_h(this.rpc.chains),this.signer=await H7.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{const{WalletConnectModal:n}=await Promise.resolve().then(function(){return Px});r=n}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(r)try{this.modal=new r(bh({walletConnectVersion:2,projectId:this.rpc.projectId,standaloneChains:this.rpc.chains},this.rpc.qrModalOptions))}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:n,rpcMap:i}=e;r&&zn(r)&&(this.rpc.chains=r.map(o=>this.formatChainId(o)),r.forEach(o=>{this.rpc.rpcMap[o]=i?.[o]||this.getRpcUrl(o)})),n&&zn(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(o=>this.formatChainId(o)),n.forEach(o=>{this.rpc.rpcMap[o]=i?.[o]||this.getRpcUrl(o)}))}getRpcUrl(e,r){var n;return((n=this.rpc.rpcMap)==null?void 0:n[e])||`${V7}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const e=this.signer.rpcProviders.eip155.chainId;this.setChainIds(e?[this.formatChainId(e)]:this.session.namespaces[this.namespace].accounts),this.setAccounts(this.session.namespaces[this.namespace].accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const tx=uc,rx=Symbol(),Pg=Object.getPrototypeOf,xh=new WeakMap,nx=t=>t&&(xh.has(t)?xh.get(t):Pg(t)===Object.prototype||Pg(t)===Array.prototype),ix=t=>nx(t)&&t[rx]||null,Tg=(t,e=!0)=>{xh.set(t,e)},Ch=t=>typeof t=="object"&&t!==null,pi=new WeakMap,hc=new WeakSet,sx=(t=Object.is,e=(d,v)=>new Proxy(d,v),r=d=>Ch(d)&&!hc.has(d)&&(Array.isArray(d)||!(Symbol.iterator in d))&&!(d instanceof WeakMap)&&!(d instanceof WeakSet)&&!(d instanceof Error)&&!(d instanceof Number)&&!(d instanceof Date)&&!(d instanceof String)&&!(d instanceof RegExp)&&!(d instanceof ArrayBuffer),n=d=>{switch(d.status){case"fulfilled":return d.value;case"rejected":throw d.reason;default:throw d}},i=new WeakMap,o=(d,v,x=n)=>{const _=i.get(d);if(_?.[0]===v)return _[1];const O=Array.isArray(d)?[]:Object.create(Object.getPrototypeOf(d));return Tg(O,!0),i.set(d,[v,O]),Reflect.ownKeys(d).forEach(P=>{if(Object.getOwnPropertyDescriptor(O,P))return;const U=Reflect.get(d,P),H={value:U,enumerable:!0,configurable:!0};if(hc.has(U))Tg(U,!1);else if(U instanceof Promise)delete H.value,H.get=()=>x(U);else if(pi.has(U)){const[G,N]=pi.get(U);H.value=o(G,N(),x)}Object.defineProperty(O,P,H)}),O},c=new WeakMap,l=[1,1],h=d=>{if(!Ch(d))throw new Error("object required");const v=c.get(d);if(v)return v;let x=l[0];const _=new Set,O=(J,z=++l[0])=>{x!==z&&(x=z,_.forEach(ee=>ee(J,z)))};let P=l[1];const U=(J=++l[1])=>(P!==J&&!_.size&&(P=J,G.forEach(([z])=>{const ee=z[1](J);ee>x&&(x=ee)})),x),H=J=>(z,ee)=>{const de=[...z];de[1]=[J,...de[1]],O(de,ee)},G=new Map,N=(J,z)=>{if(G.has(J))throw new Error("prop listener already exists");if(_.size){const ee=z[3](H(J));G.set(J,[z,ee])}else G.set(J,[z])},L=J=>{var z;const ee=G.get(J);ee&&(G.delete(J),(z=ee[1])==null||z.call(ee))},$=J=>(_.add(J),_.size===1&&G.forEach(([ee,de],me)=>{if(de)throw new Error("remove already exists");const A=ee[3](H(me));G.set(me,[ee,A])}),()=>{_.delete(J),_.size===0&&G.forEach(([ee,de],me)=>{de&&(de(),G.set(me,[ee]))})}),T=Array.isArray(d)?[]:Object.create(Object.getPrototypeOf(d)),f=e(T,{deleteProperty(J,z){const ee=Reflect.get(J,z);L(z);const de=Reflect.deleteProperty(J,z);return de&&O(["delete",[z],ee]),de},set(J,z,ee,de){const me=Reflect.has(J,z),A=Reflect.get(J,z,de);if(me&&(t(A,ee)||c.has(ee)&&t(A,c.get(ee))))return!0;L(z),Ch(ee)&&(ee=ix(ee)||ee);let j=ee;if(ee instanceof Promise)ee.then(ce=>{ee.status="fulfilled",ee.value=ce,O(["resolve",[z],ce])}).catch(ce=>{ee.status="rejected",ee.reason=ce,O(["reject",[z],ce])});else{!pi.has(ee)&&r(ee)&&(j=h(ee));const ce=!hc.has(j)&&pi.get(j);ce&&N(z,ce)}return Reflect.set(J,z,j,de),O(["set",[z],ee,A]),!0}});c.set(d,f);const E=[T,U,o,$];return pi.set(f,E),Reflect.ownKeys(d).forEach(J=>{const z=Object.getOwnPropertyDescriptor(d,J);"value"in z&&(f[J]=d[J],delete z.value,delete z.writable),Object.defineProperty(T,J,z)}),f})=>[h,pi,hc,t,e,r,n,i,o,c,l],[ox]=sx();function Rn(t={}){return ox(t)}function Kn(t,e,r){const n=pi.get(t);n||console.warn("Please use proxy object");let i;const o=[],c=n[3];let l=!1;const d=c(v=>{if(o.push(v),r){e(o.splice(0));return}i||(i=Promise.resolve().then(()=>{i=void 0,l&&e(o.splice(0))}))});return l=!0,()=>{l=!1,d()}}function ax(t,e){const r=pi.get(t);r||console.warn("Please use proxy object");const[n,i,o]=r;return o(n,i(),e)}var Rg={},fc={};fc.byteLength=ux,fc.toByteArray=fx,fc.fromByteArray=gx;for(var Nn=[],ln=[],cx=typeof Uint8Array<"u"?Uint8Array:Array,Ih="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ps=0,lx=Ih.length;Ps0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function ux(t){var e=Ng(t),r=e[0],n=e[1];return(r+n)*3/4-n}function hx(t,e,r){return(e+r)*3/4-r}function fx(t){var e,r=Ng(t),n=r[0],i=r[1],o=new cx(hx(t,n,i)),c=0,l=i>0?n-4:n,h;for(h=0;h>16&255,o[c++]=e>>8&255,o[c++]=e&255;return i===2&&(e=ln[t.charCodeAt(h)]<<2|ln[t.charCodeAt(h+1)]>>4,o[c++]=e&255),i===1&&(e=ln[t.charCodeAt(h)]<<10|ln[t.charCodeAt(h+1)]<<4|ln[t.charCodeAt(h+2)]>>2,o[c++]=e>>8&255,o[c++]=e&255),o}function dx(t){return Nn[t>>18&63]+Nn[t>>12&63]+Nn[t>>6&63]+Nn[t&63]}function px(t,e,r){for(var n,i=[],o=e;ol?l:c+o));return n===1?(e=t[r-1],i.push(Nn[e>>2]+Nn[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Nn[e>>10]+Nn[e>>4&63]+Nn[e<<2&63]+"=")),i.join("")}var Oh={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */Oh.read=function(t,e,r,n,i){var o,c,l=i*8-n-1,h=(1<>1,v=-7,x=r?i-1:0,_=r?-1:1,O=t[e+x];for(x+=_,o=O&(1<<-v)-1,O>>=-v,v+=l;v>0;o=o*256+t[e+x],x+=_,v-=8);for(c=o&(1<<-v)-1,o>>=-v,v+=n;v>0;c=c*256+t[e+x],x+=_,v-=8);if(o===0)o=1-d;else{if(o===h)return c?NaN:(O?-1:1)*(1/0);c=c+Math.pow(2,n),o=o-d}return(O?-1:1)*c*Math.pow(2,o-n)},Oh.write=function(t,e,r,n,i,o){var c,l,h,d=o*8-i-1,v=(1<>1,_=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,O=n?0:o-1,P=n?1:-1,U=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,c=v):(c=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-c))<1&&(c--,h*=2),c+x>=1?e+=_/h:e+=_*Math.pow(2,1-x),e*h>=2&&(c++,h/=2),c+x>=v?(l=0,c=v):c+x>=1?(l=(e*h-1)*Math.pow(2,i),c=c+x):(l=e*Math.pow(2,x-1)*Math.pow(2,i),c=0));i>=8;t[r+O]=l&255,O+=P,l/=256,i-=8);for(c=c<0;t[r+O]=c&255,O+=P,c/=256,d-=8);t[r+O-P]|=U*128};/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh diff --git a/src/components/AddressInputPanel/index.tsx b/src/components/AddressInputPanel/index.tsx index 6d35ddf137..fce0ca5253 100644 --- a/src/components/AddressInputPanel/index.tsx +++ b/src/components/AddressInputPanel/index.tsx @@ -55,14 +55,17 @@ const Input = styled.input<{ error?: boolean }>` } padding: 0px; -webkit-appearance: textfield; + appearance: textfield; ::-webkit-search-decoration { -webkit-appearance: none; + appearance: none; } ::-webkit-outer-spin-button, ::-webkit-inner-spin-button { -webkit-appearance: none; + appearance: none; } ` diff --git a/src/components/Header/web3/WalletModal/index.tsx b/src/components/Header/web3/WalletModal/index.tsx index e0122f3090..6e23129f31 100644 --- a/src/components/Header/web3/WalletModal/index.tsx +++ b/src/components/Header/web3/WalletModal/index.tsx @@ -442,8 +442,12 @@ export default function WalletModal() { minHeight={false} maxHeight={90} maxWidth={600} - bypassScrollLock={walletView === WALLET_VIEWS.PENDING && ['WALLET_CONNECT'].includes(pendingWalletKey)} - bypassFocusLock={walletView === WALLET_VIEWS.PENDING && ['WALLET_CONNECT', 'BLOCTO'].includes(pendingWalletKey)} + bypassScrollLock={ + walletView === WALLET_VIEWS.PENDING && ['WALLET_CONNECT', 'KRYSTAL_WC'].includes(pendingWalletKey) + } + bypassFocusLock={ + walletView === WALLET_VIEWS.PENDING && ['WALLET_CONNECT', 'KRYSTAL_WC', 'BLOCTO'].includes(pendingWalletKey) + } > {getModalContent()} diff --git a/src/components/Menu/index.tsx b/src/components/Menu/index.tsx index 9010df2484..e20de57811 100644 --- a/src/components/Menu/index.tsx +++ b/src/components/Menu/index.tsx @@ -426,7 +426,7 @@ export default function Menu() { title={t`About`} link={'/about'} options={[ - { link: '/about/kyberswap', label: 'Kyberswap' }, + { link: '/about/kyberswap', label: 'KyberSwap' }, { link: '/about/knc', label: 'KNC' }, ]} /> diff --git a/src/components/ProAmm/CandleStickChart.tsx b/src/components/ProAmm/CandleStickChart.tsx index 7e8de0e3fd..fa8f50d010 100644 --- a/src/components/ProAmm/CandleStickChart.tsx +++ b/src/components/ProAmm/CandleStickChart.tsx @@ -8,7 +8,7 @@ import styled from 'styled-components' import { PoolRatesEntry } from 'data/type' import useTheme from 'hooks/useTheme' import { useDarkModeManager } from 'state/user/hooks' -import { formatNotDollarAmount } from 'utils/numbers' +import { formatDisplayNumber } from 'utils/numbers' const IconWrapper = styled.div` position: absolute; @@ -38,14 +38,14 @@ type CandleStickChartPropsType = { } const valueFormatter = (val: number) => { - let e: number + let fraction: number if (val < 1.01 && val > 0.99) { const leftover = Math.abs(val - 1) - e = parseInt(leftover.toExponential().match(/e([+-][0-9]+)/)?.[1] ?? '0') + fraction = parseInt(leftover.toExponential().match(/e([+-][0-9]+)/)?.[1] ?? '0') } else { - e = parseInt(val.toExponential().match(/e([+-][0-9]+)/)?.[1] ?? '0') + fraction = parseInt(val.toExponential().match(/e([+-][0-9]+)/)?.[1] ?? '0') } - return formatNotDollarAmount(val, 3 - e) + return formatDisplayNumber(val, { fractionDigits: 3 - fraction }) } const CandleStickChart = ({ @@ -140,7 +140,7 @@ const CandleStickChart = ({ borderColor: 'rgba(197, 203, 206, 0.8)', }, localization: { - priceFormatter: (val: number) => formatNotDollarAmount(val, 6), + priceFormatter: (val: number) => formatDisplayNumber(val, { significantDigits: 6, allowNegative: true }), }, }) diff --git a/src/components/TransactionConfirmationModal/index.tsx b/src/components/TransactionConfirmationModal/index.tsx index 5b3a9aad75..993f7d6a42 100644 --- a/src/components/TransactionConfirmationModal/index.tsx +++ b/src/components/TransactionConfirmationModal/index.tsx @@ -122,6 +122,7 @@ function AddTokenToInjectedWallet({ token, chainId }: { token: Token; chainId: C if (!walletKey) return null if (!isEVM) return null if (walletKey === 'WALLET_CONNECT') return null + if (walletKey === 'KRYSTAL_WC') return null const walletConfig = SUPPORTED_WALLETS[walletKey] return ( diff --git a/src/components/swapv2/LimitOrder/ListOrder/index.tsx b/src/components/swapv2/LimitOrder/ListOrder/index.tsx index 3960f5551e..cbaaa04e76 100644 --- a/src/components/swapv2/LimitOrder/ListOrder/index.tsx +++ b/src/components/swapv2/LimitOrder/ListOrder/index.tsx @@ -35,6 +35,7 @@ import { } from 'utils/firebase' import { getContract } from 'utils/getContract' import { sendEVMTransaction } from 'utils/sendTransaction' +import { ErrorName } from 'utils/sentry' import EditOrderModal from '../EditOrderModal' import CancelOrderModal from '../Modals/CancelOrderModal' @@ -118,7 +119,7 @@ export const checkOrderActive = (order: LimitOrder) => { } export default forwardRef(function ListLimitOrder(props, ref) { - const { account, chainId, networkInfo } = useActiveWeb3React() + const { account, chainId, networkInfo, walletKey } = useActiveWeb3React() const { library } = useWeb3React() const [curPage, setCurPage] = useState(1) @@ -293,7 +294,10 @@ export default forwardRef(function ListLimitOrder(props, ref) { const newOrders = isCancelAll ? orders.map(e => e.id) : order?.id ? [order?.id] : [] const sendTransaction = async (encodedData: string, contract: string, payload: any) => { - const response = await sendEVMTransaction(account, library, contract, encodedData, BigNumber.from(0)) + const response = await sendEVMTransaction(account, library, contract, encodedData, BigNumber.from(0), { + name: ErrorName.LimitOrderError, + wallet: walletKey, + }) if (response?.hash) { insertCancellingOrder({ maker: account, diff --git a/src/constants/connectors/evm.ts b/src/constants/connectors/evm.ts index 707ecef9d8..a1999ad4cc 100644 --- a/src/constants/connectors/evm.ts +++ b/src/constants/connectors/evm.ts @@ -1,4 +1,5 @@ import { BloctoConnector } from '@blocto/web3-react-connector' +import { WalletConnect as KrystalWalletConnect } from '@kyberswap/krystal-walletconnect-v2' import { ChainId } from '@kyberswap/ks-sdk-core' import { OPTIONAL_EVENTS } from '@walletconnect/ethereum-provider' import { CoinbaseWallet } from '@web3-react/coinbase-wallet' @@ -35,43 +36,53 @@ export const [blocto, bloctoHooks] = initializeConnector( export const [bloctoInject, bloctoInjectHooks] = initializeConnector(actions => new MetaMask({ actions })) const darkmode = Boolean(window.matchMedia('(prefers-color-scheme: dark)')) +const walletconnectConfig = { + options: { + projectId: WALLETCONNECT_PROJECT_ID, + chains: WALLET_CONNECT_REQUIRED_CHAIN_IDS, + optionalChains: WALLET_CONNECT_OPTIONAL_CHAIN_IDS, + showQrModal: true, + methods: ['eth_sendTransaction', 'personal_sign', 'eth_signTypedData_v4'], + optionalMethods: ['eth_signTypedData', 'eth_sign'], + // optionalMethods: OPTIONAL_METHODS, + optionalEvents: OPTIONAL_EVENTS, + rpcMap: WALLET_CONNECT_SUPPORTED_CHAIN_IDS.reduce((acc, cur) => { + acc[cur] = NETWORKS_INFO[cur].defaultRpcUrl + return acc + }, {} as { [key in ChainId]: string }), + qrModalOptions: { + chainImages: undefined, + themeMode: darkmode ? ('dark' as const) : ('light' as const), + themeVariables: { + '--w3m-z-index': '1000', + '--w3m-logo-image-url': Kyber, + '--w3m-background-image-url': WC_BG, + '--w3m-accent-color': '#31CB9E', + '--w3m-accent-fill-color': '#222222', + '--w3m-color-bg-1': '#0F0F0F', + } as any, + }, + metadata: { + name: 'KyberSwap', + description: document.title, + url: window.location.origin, + icons: ['https://kyberswap.com/favicon.svg'], + }, + }, +} + export const [walletConnectV2, walletConnectV2Hooks] = initializeConnector( actions => new WalletConnectV2({ actions, - defaultChainId: ChainId.MAINNET, - options: { - projectId: WALLETCONNECT_PROJECT_ID, - chains: WALLET_CONNECT_REQUIRED_CHAIN_IDS, - optionalChains: WALLET_CONNECT_OPTIONAL_CHAIN_IDS, - showQrModal: true, - methods: ['eth_sendTransaction', 'personal_sign', 'eth_signTypedData_v4'], - optionalMethods: ['eth_signTypedData', 'eth_sign'], - // optionalMethods: OPTIONAL_METHODS, - optionalEvents: OPTIONAL_EVENTS, - rpcMap: WALLET_CONNECT_SUPPORTED_CHAIN_IDS.reduce((acc, cur) => { - acc[cur] = NETWORKS_INFO[cur].defaultRpcUrl - return acc - }, {} as { [key in ChainId]: string }), - qrModalOptions: { - chainImages: undefined, - themeMode: darkmode ? 'dark' : 'light', - themeVariables: { - '--w3m-z-index': '1000', - '--w3m-logo-image-url': Kyber, - '--w3m-background-image-url': WC_BG, - '--w3m-accent-color': '#31CB9E', - '--w3m-accent-fill-color': '#222222', - '--w3m-color-bg-1': '#0F0F0F', - } as any, - }, - metadata: { - name: 'Kyberswap', - description: document.title, - url: window.location.origin, - icons: ['https://kyberswap.com/favicon.svg'], - }, - }, + ...walletconnectConfig, + }), +) +export const [krystalWalletConnectV2, krystalWalletConnectV2Hooks] = initializeConnector( + actions => + new KrystalWalletConnect({ + actions, + ...walletconnectConfig, }), ) @@ -81,7 +92,7 @@ export const [coinbaseWallet, coinbaseWalletHooks] = initializeConnector { - console.log('capturing Injected window.ethereum', { level: 'info', extra: { 'window.ethereum': window.ethereum } }) - captureMessage('Injected window.ethereum', { level: 'info', extra: { 'window.ethereum': window.ethereum } }) - }, 2000) + if (getIsGenericInjector()) { + const params = { + level: 'warning', + extra: { + detector: { + isMetaMaskWallet: getIsMetaMaskWallet(), + isCoinbaseWallet: getIsCoinbaseWallet(), + isBraveWallet: getIsBraveWallet(), + isC98Wallet: getIsC98Wallet(), + isRabbyWallet: getIsRabbyWallet(), + isBloctoWallet: getIsBloctoWallet(), + isKrystalWallet: getIsKrystalWallet(), + isTrustWallet: getIsTrustWallet(), + isGenericInjector: getIsGenericInjector(), + }, + 'window.ethereum': window.ethereum, + 'window.web3': window.web3, + 'window.coin98': window.coin98, + 'window.coinbaseWalletExtension': window.coinbaseWalletExtension, + 'navigator.brave': navigator.brave, + }, + } as const + captureMessage('Unknown injected window.ethereum', params) + console.info('Capturing injected window.ethereum', { params }) + } + }, 5000) } export const getIsInjected = () => Boolean(window.ethereum) @@ -78,12 +101,15 @@ export enum ErrorCode { ALPHA_WALLET_REJECTED = 'Request rejected', } -const rejectedPhrases: readonly string[] = [ - 'user rejected transaction', - 'User declined to send the transaction', - 'user denied transaction', - 'you must accept', -].map(phrase => phrase.toLowerCase()) +// Known phrases: +// - User declined to send the transaction ... +// - user denied transaction ... +// - user rejected transaction ... +// - User rejected methods ... +// - User rejected the request ... +const rejectedPhrases: readonly string[] = ['User declined', 'user denied', 'you must accept', 'User rejected'].map( + phrase => phrase.toLowerCase(), +) export function didUserReject(error: any): boolean { const message = String( diff --git a/src/constants/wallets.ts b/src/constants/wallets.ts index 931e6e2b5e..1fd2333a3a 100644 --- a/src/constants/wallets.ts +++ b/src/constants/wallets.ts @@ -36,6 +36,8 @@ import { injectedHooks, krystal, krystalHooks, + krystalWalletConnectV2, + krystalWalletConnectV2Hooks, metaMask, metamaskHooks, rabby, @@ -65,13 +67,13 @@ import { getIsTrustWallet, } from 'constants/connectors/utils' -const detectInjected = (): WalletReadyState => { +const detectGenericInjected = (): WalletReadyState => { // used in mobile dapp if (getIsGenericInjector()) return WalletReadyState.Installed return WalletReadyState.Unsupported } -const detectMetamask = (): WalletReadyState => { +const detectMetamaskInjected = (): WalletReadyState => { if (getIsMetaMaskWallet()) return WalletReadyState.Installed return WalletReadyState.NotDetected } @@ -98,28 +100,33 @@ const detectSafe = (): WalletReadyState => { return isSafe ? WalletReadyState.Installed : WalletReadyState.NotDetected } -const detectRabby = (): WalletReadyState => { +const detectRabbyInjected = (): WalletReadyState => { if (getIsRabbyWallet()) return WalletReadyState.Installed return WalletReadyState.NotDetected } -const detectKrystal = (): WalletReadyState => { +const detectKrystalInjected = (): WalletReadyState => { if (getIsKrystalWallet()) return WalletReadyState.Installed - return WalletReadyState.NotDetected + return WalletReadyState.Unsupported +} + +const detectKrystalWC = (): WalletReadyState => { + if (!getIsKrystalWallet()) return WalletReadyState.Installed + return WalletReadyState.Unsupported } -const detectBrave = (): WalletReadyState => { +const detectBraveInjected = (): WalletReadyState => { //todo known issue: fail connect on mobile solana if (getIsBraveWallet()) return WalletReadyState.Installed return WalletReadyState.NotDetected } -const detectCoin98 = (): WalletReadyState => { +const detectCoin98Injected = (): WalletReadyState => { if (getIsC98Wallet()) return WalletReadyState.Installed return WalletReadyState.NotDetected } -const detectCoinbase = (): WalletReadyState => { +const detectCoinbaseInjected = (): WalletReadyState => { const detectCoinbase = (): WalletReadyState => { if (getIsCoinbaseWallet()) return WalletReadyState.Installed // in NotDetected case, Coinbase show install link itself @@ -130,7 +137,7 @@ const detectCoinbase = (): WalletReadyState => { return result } -const detectTrustWallet = (): WalletReadyState => { +const detectTrustWalletInjected = (): WalletReadyState => { if (getIsTrustWallet()) return WalletReadyState.Installed return WalletReadyState.NotDetected } @@ -167,7 +174,7 @@ export const SUPPORTED_WALLETS = { name: 'Browser Wallet', icon: INJECTED_DARK_ICON, iconLight: INJECTED_LIGHT_ICON, - readyState: detectInjected, + readyState: detectGenericInjected, } as EVMWalletInfo, METAMASK: { connector: metaMask, @@ -176,7 +183,7 @@ export const SUPPORTED_WALLETS = { icon: METAMASK, iconLight: METAMASK, installLink: 'https://metamask.io/download', - readyState: detectMetamask, + readyState: detectMetamaskInjected, } as EVMWalletInfo, KRYSTAL: { connector: krystal, @@ -185,7 +192,7 @@ export const SUPPORTED_WALLETS = { icon: KRYSTAL, iconLight: KRYSTAL, installLink: 'https://wallet.krystal.app', - readyState: detectKrystal, + readyState: detectKrystalInjected, } as EVMWalletInfo, RABBY: { connector: rabby, @@ -194,7 +201,7 @@ export const SUPPORTED_WALLETS = { icon: RABBY, iconLight: RABBY, installLink: 'https://rabby.io', - readyState: detectRabby, + readyState: detectRabbyInjected, } as EVMWalletInfo, TRUST_WALLET: { connector: trust, @@ -203,7 +210,7 @@ export const SUPPORTED_WALLETS = { icon: TRUSTWALLET, iconLight: TRUSTWALLET, installLink: 'https://trustwallet.com/vi/deeplink', - readyState: detectTrustWallet, + readyState: detectTrustWalletInjected, } as EVMWalletInfo, BRAVE: { connector: brave, @@ -213,7 +220,7 @@ export const SUPPORTED_WALLETS = { icon: BRAVE, iconLight: BRAVE, installLink: 'https://brave.com/download', - readyState: detectBrave, + readyState: detectBraveInjected, // If Phantom extension installed block Brave wallet readyStateSolana: () => (window.solana?.isBraveWallet ? braveAdapter.readyState : WalletReadyState.NotDetected), } as EVMWalletInfo & SolanaWalletInfo, @@ -234,7 +241,7 @@ export const SUPPORTED_WALLETS = { icon: COINBASE, iconLight: COINBASE, installLink: 'https://www.coinbase.com/wallet', - readyState: detectCoinbase, + readyState: detectCoinbaseInjected, readyStateSolana: () => (isMobile ? WalletReadyState.Unsupported : coinbaseAdapter.readyState), } as EVMWalletInfo & SolanaWalletInfo, COIN98: { @@ -245,7 +252,7 @@ export const SUPPORTED_WALLETS = { icon: COIN98, iconLight: COIN98, installLink: 'https://wallet.coin98.com/', - readyState: detectCoin98, + readyState: detectCoin98Injected, readyStateSolana: () => coin98Adapter.readyState, } as EVMWalletInfo & SolanaWalletInfo, BLOCTO_INJECTED: { @@ -256,6 +263,15 @@ export const SUPPORTED_WALLETS = { iconLight: BLOCTO, readyState: detectBloctoInjected, } as EVMWalletInfo, + KRYSTAL_WC: { + connector: krystalWalletConnectV2, + hooks: krystalWalletConnectV2Hooks, + name: 'Krystal', + icon: KRYSTAL, + iconLight: KRYSTAL, + installLink: 'https://wallet.krystal.app', + readyState: detectKrystalWC, + } as EVMWalletInfo, WALLET_CONNECT: { connector: walletConnectV2, hooks: walletConnectV2Hooks, diff --git a/src/hooks/index.ts b/src/hooks/index.ts index 2b945bdab3..ddff6ebf87 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -7,7 +7,7 @@ import { useMemo } from 'react' import { useSelector } from 'react-redux' import { useSearchParams } from 'react-router-dom' -import { blocto, gnosisSafe, walletConnectV2 } from 'constants/connectors/evm' +import { blocto, gnosisSafe, krystalWalletConnectV2, walletConnectV2 } from 'constants/connectors/evm' import { MOCK_ACCOUNT_EVM, MOCK_ACCOUNT_SOLANA } from 'constants/env' import { NETWORKS_INFO, isSupportedChainId } from 'constants/networks' import { NetworkInfo } from 'constants/networks/type' @@ -60,6 +60,9 @@ export function useActiveWeb3React(): { if (connectedConnectorEVM === walletConnectV2) { return 'WALLET_CONNECT' } + if (connectedConnectorEVM === krystalWalletConnectV2) { + return 'KRYSTAL_WC' + } if (connectedConnectorEVM === gnosisSafe) { return 'SAFE' } diff --git a/src/hooks/kyberdao/index.tsx b/src/hooks/kyberdao/index.tsx index 39732e3974..cecdf89682 100644 --- a/src/hooks/kyberdao/index.tsx +++ b/src/hooks/kyberdao/index.tsx @@ -20,7 +20,6 @@ import DaoABI from 'constants/abis/kyberdao/dao.json' import MigrateABI from 'constants/abis/kyberdao/migrate.json' import RewardDistributorABI from 'constants/abis/kyberdao/reward_distributor.json' import StakingABI from 'constants/abis/kyberdao/staking.json' -import { didUserReject } from 'constants/connectors/utils' import { REWARD_SERVICE_API } from 'constants/env' import { CONTRACT_NOT_FOUND_MSG } from 'constants/messages' import { NETWORKS_INFO, SUPPORTED_NETWORKS, isEVM } from 'constants/networks' @@ -40,6 +39,7 @@ import { aggregateValue } from 'utils/array' import { friendlyError } from 'utils/errorMessage' import { formatUnitsToFixed } from 'utils/formatBalance' import { sendEVMTransaction } from 'utils/sendTransaction' +import { ErrorName } from 'utils/sentry' import { EligibleTxsInfo, @@ -89,11 +89,7 @@ export function useKyberDaoStakeActions() { }) return tx.hash } catch (error) { - if (didUserReject(error)) { - throw new Error('Transaction rejected.') - } else { - throw error - } + throw error } }, [addTransactionWithType, stakingContract, kyberDaoInfo], @@ -120,11 +116,7 @@ export function useKyberDaoStakeActions() { }) return tx.hash } catch (error) { - if (didUserReject(error)) { - throw new Error('Transaction rejected.') - } else { - throw error - } + throw error } }, [addTransactionWithType, stakingContract, kyberDaoInfo?.KNCAddress], @@ -155,11 +147,7 @@ export function useKyberDaoStakeActions() { }) return tx.hash } catch (error) { - if (didUserReject(error)) { - throw new Error('Transaction rejected.') - } else { - throw error - } + throw error } }, [addTransactionWithType, migrateContract, kyberDaoInfo], @@ -181,11 +169,7 @@ export function useKyberDaoStakeActions() { }) return tx.hash } catch (error) { - if (didUserReject(error)) { - throw new Error('Transaction rejected.') - } else { - throw error - } + throw error } }, [addTransactionWithType, stakingContract], @@ -208,11 +192,7 @@ export function useKyberDaoStakeActions() { }) return tx.hash } catch (error) { - if (didUserReject(error)) { - throw new Error('Transaction rejected.') - } else { - throw error - } + throw error } }, [addTransactionWithType, stakingContract], @@ -272,11 +252,7 @@ export function useClaimVotingRewards() { }) return tx.hash as string } catch (error) { - if (didUserReject(error)) { - throw new Error('Transaction rejected.') - } else { - throw error - } + throw error } }, [ userRewards, @@ -312,11 +288,7 @@ export const useVotingActions = () => { }) return tx.hash } catch (error) { - if (didUserReject(error)) { - throw new Error('Transaction rejected.') - } else { - throw error - } + throw error } }, [daoContract, addTransactionWithType, kyberDaoInfo?.dao], @@ -619,7 +591,7 @@ export function useGasRefundInfo({ rewardStatus = KNCUtilityTabs.Available }: { } export function useClaimGasRefundRewards() { - const { account, chainId } = useActiveWeb3React() + const { account, chainId, walletKey } = useActiveWeb3React() const { library } = useWeb3React() const addTransactionWithType = useTransactionAdder() const { claimableReward } = useGasRefundInfo({}) @@ -654,7 +626,10 @@ export function useClaimGasRefundRewards() { const rewardContractAddress = response.data.data.ContractAddress const encodedData = response.data.data.EncodedData try { - const tx = await sendEVMTransaction(account, library, rewardContractAddress, encodedData, BigNumber.from(0)) + const tx = await sendEVMTransaction(account, library, rewardContractAddress, encodedData, BigNumber.from(0), { + name: ErrorName.GasRefundClaimError, + wallet: walletKey, + }) if (!tx) throw new Error() addTransactionWithType({ hash: tx.hash, @@ -678,7 +653,7 @@ export function useClaimGasRefundRewards() { }) throw error } - }, [account, addTransactionWithType, chainId, claimableReward, library, notify, refetch]) + }, [account, addTransactionWithType, chainId, claimableReward, library, notify, refetch, walletKey]) return claimGasRefundRewards } diff --git a/src/hooks/useApproveCallback.ts b/src/hooks/useApproveCallback.ts index 209daba3bd..3f8dcfb617 100644 --- a/src/hooks/useApproveCallback.ts +++ b/src/hooks/useApproveCallback.ts @@ -138,7 +138,6 @@ export function useApproveCallback( }, 8000, ) - throw error }) }, [approvalState, token, tokenContract, amountToApprove, spender, addTransactionWithType, forceApprove, notify], diff --git a/src/hooks/useSwapCallbackV3.ts b/src/hooks/useSwapCallbackV3.ts index 1117100bf5..325f96e71a 100644 --- a/src/hooks/useSwapCallbackV3.ts +++ b/src/hooks/useSwapCallbackV3.ts @@ -13,11 +13,12 @@ import { ChargeFeeBy } from 'types/route' import { isAddress, shortenAddress } from 'utils' import { formatCurrencyAmount } from 'utils/formatCurrencyAmount' import { sendEVMTransaction } from 'utils/sendTransaction' +import { ErrorName } from 'utils/sentry' // returns a function that will execute a swap, if the parameters are all valid // and the user has approved the slippage adjusted input amount for the trade const useSwapCallbackV3 = (isPermitSwap?: boolean) => { - const { account, chainId, isEVM } = useActiveWeb3React() + const { account, chainId, isEVM, walletKey } = useActiveWeb3React() const { library } = useWeb3React() const { isSaveGas, recipient: recipientAddressOrName, routeSummary } = useSwapFormContext() @@ -124,12 +125,13 @@ const useSwapCallbackV3 = (isPermitSwap?: boolean) => { routerAddress, encodedSwapData, value, + { name: ErrorName.SwapError, wallet: walletKey }, handleSwapResponse, ) if (response?.hash === undefined) throw new Error('sendTransaction returned undefined.') return response?.hash }, - [account, handleSwapResponse, inputAmount, library], + [account, handleSwapResponse, inputAmount, library, walletKey], ) if (isEVM) { diff --git a/src/hooks/useSwapV2Callback.ts b/src/hooks/useSwapV2Callback.ts index 2b5f75df19..d68a31f5bb 100644 --- a/src/hooks/useSwapV2Callback.ts +++ b/src/hooks/useSwapV2Callback.ts @@ -14,6 +14,7 @@ import { isAddress, shortenAddress } from 'utils' import { Aggregator } from 'utils/aggregator' import { formatCurrencyAmount } from 'utils/formatCurrencyAmount' import { sendEVMTransaction, sendSolanaTransactions } from 'utils/sendTransaction' +import { ErrorName } from 'utils/sentry' import useProvider from './solana/useProvider' @@ -28,7 +29,7 @@ enum SwapCallbackState { export function useSwapV2Callback( trade: Aggregator | undefined, // trade to execute, required ): { state: SwapCallbackState; callback: null | (() => Promise); error: string | null } { - const { account, chainId, isEVM, isSolana, walletSolana } = useActiveWeb3React() + const { account, chainId, isEVM, isSolana, walletSolana, walletKey } = useActiveWeb3React() const { library } = useWeb3React() const { connection } = useWeb3Solana() const provider = useProvider() @@ -115,6 +116,8 @@ export function useSwapV2Callback( } const value = BigNumber.from(trade.inputAmount.currency.isNative ? trade.inputAmount.quotient.toString() : 0) + // swap v2 is unused anymore + // todo: remove this const onSwapWithBackendEncode = async (): Promise => { const response = await sendEVMTransaction( account, @@ -122,6 +125,7 @@ export function useSwapV2Callback( trade.routerAddress, trade.encodedSwapData, value, + { name: ErrorName.SwapError, wallet: walletKey }, onHandleSwapResponse, chainId, ) @@ -165,5 +169,6 @@ export function useSwapV2Callback( addTransactionWithType, extractSwapData, connection, + walletKey, ]) } diff --git a/src/hooks/web3/useActivationWallet.ts b/src/hooks/web3/useActivationWallet.ts index 82a014dda7..d06ea2b1ab 100644 --- a/src/hooks/web3/useActivationWallet.ts +++ b/src/hooks/web3/useActivationWallet.ts @@ -21,20 +21,26 @@ export const useActivationWallet: () => { const wallet = (SUPPORTED_WALLETS as any)[walletKey] if (!isEVMWallet(wallet)) return try { - console.info('Activate EVM start', { wallet, isEagerly }) - // localStorage.removeItem(LOCALSTORAGE_LAST_WALLETKEY_EVM) + console.info('Activate EVM start', { walletKey, isEagerly }) if (isEagerly) { if (wallet.connector.connectEagerly) { await wallet.connector.connectEagerly() + console.info('Activate EVM success with .connectEagerly()', { + walletKey, + isEagerly, + 'wallet.connector': wallet.connector, + }) } else { await wallet.connector.activate() + console.info('Activate EVM success with .activate()', { walletKey, isEagerly }) } } else { await wallet.connector.activate() + console.info('Activate EVM success with .activate()', { walletKey, isEagerly }) } - console.info('Activate EVM success', { walletKey, isEagerly }) localStorage.setItem(LOCALSTORAGE_LAST_WALLETKEY_EVM, walletKey) } catch (error) { + console.error('Activate EVM failed:', { walletKey, wallet, error, isEagerly }) localStorage.removeItem(LOCALSTORAGE_LAST_WALLETKEY_EVM) const e = new Error(`[Wallet] ${error.message}`) e.name = 'Activate EVM failed' @@ -43,7 +49,6 @@ export const useActivationWallet: () => { level: 'warning', extra: { error, walletKey, isEagerly }, }) - console.error('Activate EVM failed:', { walletKey, wallet, error, isEagerly }) throw error } }, diff --git a/src/hooks/web3/useChangeNetwork.ts b/src/hooks/web3/useChangeNetwork.ts index 156adef803..9fbbce060d 100644 --- a/src/hooks/web3/useChangeNetwork.ts +++ b/src/hooks/web3/useChangeNetwork.ts @@ -4,7 +4,7 @@ import { captureException } from '@sentry/react' import { useCallback } from 'react' import { NotificationType } from 'components/Announcement/type' -import { walletConnectV2 } from 'constants/connectors/evm' +import { krystalWalletConnectV2, walletConnectV2 } from 'constants/connectors/evm' import { didUserReject } from 'constants/connectors/utils' import { NETWORKS_INFO, isEVM, isSolana } from 'constants/networks' import { useActiveWeb3React, useWeb3React } from 'hooks' @@ -261,7 +261,7 @@ export function useChangeNetwork() { ) // walletconnect v2 not support add network, so halt execution here - if (didUserReject(error) || connector === walletConnectV2) { + if (didUserReject(error) || connector === walletConnectV2 || connector === krystalWalletConnectV2) { failureCallback(desiredChainId, error, customFailureCallback) return } diff --git a/src/hooks/web3/useDisconnectWallet.ts b/src/hooks/web3/useDisconnectWallet.ts index c6ca1872ca..335856792e 100644 --- a/src/hooks/web3/useDisconnectWallet.ts +++ b/src/hooks/web3/useDisconnectWallet.ts @@ -2,7 +2,7 @@ import { useWallet } from '@solana/wallet-adapter-react' import { Connector } from '@web3-react/types' import { useCallback } from 'react' -import { coinbaseWallet, walletConnectV2 } from 'constants/connectors/evm' +import { coinbaseWallet, krystalWalletConnectV2, walletConnectV2 } from 'constants/connectors/evm' import { LOCALSTORAGE_LAST_WALLETKEY_EVM, LOCALSTORAGE_LAST_WALLETKEY_SOLANA, @@ -20,7 +20,7 @@ const disconnectEvmConnector: (connector: Connector | undefined) => void | Promi } connector.deactivate?.() connector.resetState?.() - if (connector === walletConnectV2) { + if (connector === walletConnectV2 || connector === krystalWalletConnectV2) { // This key should be deleted when disconnected by walletconnect library // But it was deleted slowly, if user call connector.active() again before this key cleared, bug will appear // So we force remove it right after disconnected to preventing bug diff --git a/src/hooks/web3/useWalletSupportedChains.ts b/src/hooks/web3/useWalletSupportedChains.ts index 5817060ff2..4a6b017937 100644 --- a/src/hooks/web3/useWalletSupportedChains.ts +++ b/src/hooks/web3/useWalletSupportedChains.ts @@ -1,7 +1,7 @@ import { ChainId } from '@kyberswap/ks-sdk-core' import { WalletConnect as WalletConnectV2 } from '@web3-react/walletconnect-v2' -import { blocto, bloctoInject, gnosisSafe, walletConnectV2 } from 'constants/connectors/evm' +import { blocto, bloctoInject, gnosisSafe, krystalWalletConnectV2, walletConnectV2 } from 'constants/connectors/evm' import { BLOCTO_SUPPORTED_NETWORKS, SUPPORTED_NETWORKS } from 'constants/networks' import { useWeb3React } from 'hooks' @@ -20,6 +20,7 @@ export function useWalletSupportedChains(): ChainId[] { switch (connector) { case walletConnectV2: + case krystalWalletConnectV2: return [ ...getChainsFromEIP155Accounts((connector as WalletConnectV2).provider?.session?.namespaces?.eip155?.accounts), ] diff --git a/src/pages/Campaign/CampaignButtonWithOptions.tsx b/src/pages/Campaign/CampaignButtonWithOptions.tsx index 5013578ca5..0b0cf4959a 100644 --- a/src/pages/Campaign/CampaignButtonWithOptions.tsx +++ b/src/pages/Campaign/CampaignButtonWithOptions.tsx @@ -33,6 +33,7 @@ import { useTransactionAdder } from 'state/transactions/hooks' import { TRANSACTION_TYPE } from 'state/transactions/type' import { findTx } from 'utils' import { sendEVMTransaction } from 'utils/sendTransaction' +import { ErrorName } from 'utils/sentry' type Size = 'small' | 'large' export default function CampaignButtonWithOptions({ @@ -59,7 +60,7 @@ export default function CampaignButtonWithOptions({ ? campaign[type === 'swap_now' ? 'chainIds' : 'rewardChainIds'].split(',').map(Number) : [] - const { account, walletSolana } = useActiveWeb3React() + const { account, walletSolana, walletKey } = useActiveWeb3React() const { library } = useWeb3React() const rawRewards = campaign?.userInfo?.rewards || [] @@ -195,6 +196,7 @@ export default function CampaignButtonWithOptions({ rewardContractAddress, encodedData, BigNumber.from(0), + { name: ErrorName.ClaimCampaignError, wallet: walletKey }, async transactionResponse => { addClaimTransactionAndAddClaimRef( transactionResponse.hash, diff --git a/src/pages/ElasticSwap/hooks/index.ts b/src/pages/ElasticSwap/hooks/index.ts index 5ed0b37867..5d555c6eb2 100644 --- a/src/pages/ElasticSwap/hooks/index.ts +++ b/src/pages/ElasticSwap/hooks/index.ts @@ -1,12 +1,13 @@ import { Currency, CurrencyAmount, Token, TradeType } from '@kyberswap/ks-sdk-core' import { FeeAmount, Pool, Route, SwapQuoter, SwapRouter, Trade, computePoolAddress } from '@kyberswap/ks-sdk-elastic' +import { t } from '@lingui/macro' import { BigNumber, Contract } from 'ethers' import JSBI from 'jsbi' import { useMemo } from 'react' import { useSearchParams } from 'react-router-dom' +import { NotificationType } from 'components/Announcement/type' import { abi as QuoterABI } from 'constants/abis/v2/ProAmmQuoter.json' -import { didUserReject } from 'constants/connectors/utils' import { INITIAL_ALLOWED_SLIPPAGE } from 'constants/index' import { EVMNetworkInfo } from 'constants/networks/type' import { useActiveWeb3React, useWeb3React } from 'hooks' @@ -14,10 +15,12 @@ import { useAllCurrencyCombinations } from 'hooks/useAllCurrencyCombinations' import { useContractForReading } from 'hooks/useContract' import { PoolState, usePools } from 'hooks/usePools' import useTransactionDeadline from 'hooks/useTransactionDeadline' +import { useNotify } from 'state/application/hooks' import { useSingleContractWithCallData } from 'state/multicall/hooks' import { useTransactionAdder } from 'state/transactions/hooks' import { TRANSACTION_TYPE } from 'state/transactions/type' import { basisPointsToPercent, calculateGasMargin } from 'utils' +import { friendlyError } from 'utils/errorMessage' import { formatCurrencyAmount } from 'utils/formatCurrencyAmount' import { getContract } from 'utils/getContract' import isZero from 'utils/isZero' @@ -451,6 +454,7 @@ export function useSwapCallback( const swapCalls = useSwapCallArguments(trade, allowedSlippage) const addTransactionWithType = useTransactionAdder() + const notify = useNotify() return useMemo(() => { if (!trade || !library || !account || !chainId) { @@ -555,19 +559,21 @@ export function useSwapCallback( return response.hash }) .catch((error: any) => { - // if the user rejected the tx, pass this along - if (didUserReject(error)) { - throw new Error('Transaction rejected.') - } else { - // otherwise, the error was unexpected and we need to convey that - console.error(`Swap failed`, error, address, calldata, value) - throw new Error(`Swap failed: ${error.message}`) - } + const message = friendlyError(error) + console.error('Swap error:', { message, error }) + notify( + { + title: t`Swap Error`, + summary: message, + type: NotificationType.ERROR, + }, + 8000, + ) }) }, error: null, } - }, [trade, library, account, chainId, swapCalls, addTransactionWithType]) + }, [trade, library, account, chainId, swapCalls, addTransactionWithType, notify]) } interface SwapCall { diff --git a/src/pages/MyEarnings/ElasticPools/SinglePosition/CollectFeesPanel.tsx b/src/pages/MyEarnings/ElasticPools/SinglePosition/CollectFeesPanel.tsx index 417ba4dc86..e5e07b8e62 100644 --- a/src/pages/MyEarnings/ElasticPools/SinglePosition/CollectFeesPanel.tsx +++ b/src/pages/MyEarnings/ElasticPools/SinglePosition/CollectFeesPanel.tsx @@ -28,7 +28,7 @@ import { TRANSACTION_TYPE } from 'state/transactions/type' import { updateChainId } from 'state/user/actions' import { useUserSlippageTolerance } from 'state/user/hooks' import { basisPointsToPercent, calculateGasMargin } from 'utils' -import { formatDollarAmount } from 'utils/numbers' +import { formatDisplayNumber } from 'utils/numbers' type Props = { nftId: string @@ -279,7 +279,7 @@ const CollectFeesPanel: React.FC = ({ - {formatDollarAmount(feeUsd)} + {formatDisplayNumber(feeUsd, { style: 'currency', significantDigits: 6 })} } disabled={hasNoFeeToCollect} diff --git a/src/utils/errorMessage.ts b/src/utils/errorMessage.ts index 91eb790c42..2b23253d58 100644 --- a/src/utils/errorMessage.ts +++ b/src/utils/errorMessage.ts @@ -21,6 +21,13 @@ function parseKnownPattern(text: string): string | undefined { ) return t`An error occurred. Try refreshing the price rate or increase max slippage` + if ( + error.includes('insufficient funds for intrinsic transaction cost') || + error.includes('OutOfFund') || + error.includes('insufficient balance for transfer') + ) + return t`Your current balance falls short of covering the required gas fee.` + if (error.includes('header not found') || error.includes('swap failed')) return t`An error occurred. Refresh the page and try again. If the issue still persists, it might be an issue with your RPC node settings in Metamask.` @@ -39,13 +46,18 @@ function parseKnownPattern(text: string): string | undefined { return undefined } +const codeMapping: { [key: string]: string } = { + 'Internal JSON-RPC error.': 'Network Error. Please check your connection and try again.', +} + const patterns: { pattern: RegExp; getMessage: (match: RegExpExecArray) => string }[] = [ + { pattern: /"message": ?"([^"]+?)"/, getMessage: match => codeMapping[match[1]] }, { pattern: /{"originalError":.+"message":"execution reverted: ([^"]+)"/, getMessage: match => match[1], }, { pattern: /^([\w ]*\w+) \(.+?\)$/, getMessage: match => match[1] }, - { pattern: /"message": ?"[^"]+?"/, getMessage: match => match[1] }, + { pattern: /"message": ?"([^"]+?)"/, getMessage: match => match[1] }, ] function parseKnownRegexPattern(text: string): string | undefined { const pattern = patterns.find(pattern => pattern.pattern.exec(text)) diff --git a/src/utils/numbers.ts b/src/utils/numbers.ts index 8762f090be..59e3422b8d 100644 --- a/src/utils/numbers.ts +++ b/src/utils/numbers.ts @@ -22,23 +22,6 @@ export const formatDollarAmount = (num: number | undefined, digits = 2) => { .toLowerCase() } -// todo: deprecated, use formatDisplayNumber instead -export const formatNotDollarAmount = (num: number | undefined, digits = 2) => { - if (num === 0) return '0.00' - if (!num) return '-' - if (num < 0.001 && digits <= 3) { - return '<0.001' - } - const fractionDigits = num > 1000 ? 2 : digits - return Intl.NumberFormat('en-US', { - notation: num < 10000 ? 'standard' : 'compact', - minimumFractionDigits: 0, - maximumFractionDigits: fractionDigits, - }) - .format(num) - .toLowerCase() -} - // stringify number without scientific format // e.g: (123456789123456789123456789).toString() => 1.2345678912345679e+26 // toFixed(123456789123456789123456789) => 123456789123456800000000000 diff --git a/src/utils/sendTransaction.ts b/src/utils/sendTransaction.ts index 51164e6e1c..e85eef0889 100644 --- a/src/utils/sendTransaction.ts +++ b/src/utils/sendTransaction.ts @@ -6,11 +6,12 @@ import { SignerWalletAdapter } from '@solana/wallet-adapter-base' import { Connection, Transaction, VersionedTransaction } from '@solana/web3.js' import { ethers } from 'ethers' +import { SUPPORTED_WALLET } from 'constants/wallets' import { SolanaEncode } from 'state/swap/types' import { TRANSACTION_TYPE, TransactionHistory } from 'state/transactions/type' import { calculateGasMargin } from 'utils' -import { TransactionError } from './sentry' +import { ErrorName, TransactionError } from './sentry' export async function sendEVMTransaction( account: string, @@ -18,6 +19,10 @@ export async function sendEVMTransaction( contractAddress: string, encodedData: string, value: BigNumber, + sentryInfo: { + name: ErrorName + wallet: SUPPORTED_WALLET | undefined + }, handler?: (response: TransactionResponse) => void, chainId?: ChainId, ): Promise { @@ -35,7 +40,14 @@ export async function sendEVMTransaction( gasEstimate = await library.getSigner().estimateGas(estimateGasOption) if (!gasEstimate) throw new Error('gasEstimate is nullish value') } catch (error) { - throw new TransactionError(error?.message, estimateGasOption, { cause: error }) + throw new TransactionError( + sentryInfo.name, + 'estimateGas', + error?.message, + estimateGasOption, + { cause: error }, + sentryInfo.wallet, + ) } const sendTransactionOption = { @@ -51,7 +63,14 @@ export async function sendEVMTransaction( handler?.(response) return response } catch (error) { - throw new TransactionError(error?.message, sendTransactionOption, { cause: error }) + throw new TransactionError( + sentryInfo.name, + 'sendTransaction', + error?.message, + sendTransactionOption, + { cause: error }, + sentryInfo.wallet, + ) } } diff --git a/src/utils/sentry.ts b/src/utils/sentry.ts index 8d9e73c78e..0f8996ecb8 100644 --- a/src/utils/sentry.ts +++ b/src/utils/sentry.ts @@ -3,11 +3,15 @@ import { captureException } from '@sentry/react' import { Deferrable } from 'ethers/lib/utils' import { didUserReject } from 'constants/connectors/utils' +import { SUPPORTED_WALLET } from 'constants/wallets' import { friendlyError } from './errorMessage' export enum ErrorName { - SwappError = 'SwapError', + LimitOrderError = 'LimitOrderError', + SwapError = 'SwapError', + ClaimCampaignError = 'ClaimCampaignError', + GasRefundClaimError = 'GasRefundClaimError', RemoveElasticLiquidityError = 'RemoveElasticLiquidityError', RemoveClassicLiquidityError = 'RemoveClassicLiquidityError', } @@ -18,8 +22,8 @@ export function captureSwapError(error: TransactionError) { const friendlyErrorResult = friendlyError(error) if (friendlyErrorResult.includes('slippage')) return - const e = new Error(friendlyErrorResult, { cause: error }) - e.name = ErrorName.SwappError + const e = new Error(`${error.type}: ${friendlyErrorResult}`, { cause: error }) + e.name = error.name const tmp = JSON.stringify(error) const tag = tmp.includes('minTotalAmountOut') @@ -34,7 +38,7 @@ export function captureSwapError(error: TransactionError) { captureException(e, { level: 'fatal', - extra: error.rawData, + extra: { rawData: error.rawData }, tags: { type: tag, }, @@ -42,12 +46,25 @@ export function captureSwapError(error: TransactionError) { } export class TransactionError extends Error { + name: ErrorName + type: 'estimateGas' | 'sendTransaction' rawData: Deferrable code?: number + wallet: SUPPORTED_WALLET | undefined - constructor(message: string, rawData: Deferrable, options?: ErrorOptions) { + constructor( + name: ErrorName, + type: 'estimateGas' | 'sendTransaction', + message: string, + rawData: Deferrable, + options: ErrorOptions | undefined, + wallet: SUPPORTED_WALLET | undefined, + ) { super(message, options) + this.name = name + this.type = type this.rawData = rawData this.code = (options?.cause as any)?.code + this.wallet = wallet } } diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts index 11f02fe2a0..b1f45c7866 100644 --- a/src/vite-env.d.ts +++ b/src/vite-env.d.ts @@ -1 +1,2 @@ /// +/// diff --git a/tsconfig.json b/tsconfig.json index 8094043b36..1868cc282c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "target": "ESNext", "lib": ["dom", "dom.iterable", "esnext"], - "allowJs": true, + "allowJs": false, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "noEmit": true, @@ -22,7 +22,6 @@ "jsx": "react-jsx", "downlevelIteration": true, "allowSyntheticDefaultImports": true, - "types": ["vite/client", "vite-plugin-svgr/client"], "typeRoots": ["./types"], "baseUrl": "src", "useUnknownInCatchVariables": false, diff --git a/yarn.lock b/yarn.lock index 223ea84028..430039ae3b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2265,6 +2265,16 @@ axios "1.2.1" client-oauth2 "^4.3.3" +"@kyberswap/krystal-walletconnect-v2@0.0.1": + version "0.0.1" + resolved "https://registry.yarnpkg.com/@kyberswap/krystal-walletconnect-v2/-/krystal-walletconnect-v2-0.0.1.tgz#ce9657ca0c8029f06209ea379d89452791210453" + integrity sha512-/vR1nUCazlMH1lFRpI4E5xCA3xk6psd7gvWOnNjgwZqi77aML8KlXnB+PTdgmLtq/APR0FRDOqo2XVI+o11/YA== + dependencies: + "@walletconnect/ethereum-provider" "2.8.1" + "@walletconnect/modal" "2.4.7" + "@web3-react/types" "8.2.0" + eventemitter3 "4.0.7" + "@kyberswap/ks-sdk-classic@^1.0.3": version "1.0.3" resolved "https://registry.yarnpkg.com/@kyberswap/ks-sdk-classic/-/ks-sdk-classic-1.0.3.tgz#8ee8e454b2838359a36aee387729d1d2e5aa9c20" @@ -5397,7 +5407,7 @@ dependencies: tslib "1.14.1" -"@walletconnect/ethereum-provider@^2.8.0": +"@walletconnect/ethereum-provider@2.8.1", "@walletconnect/ethereum-provider@^2.8.0": version "2.8.1" resolved "https://registry.yarnpkg.com/@walletconnect/ethereum-provider/-/ethereum-provider-2.8.1.tgz#1743072f42b5c940648b0303a382e8907a362a00" integrity sha512-YlF8CCiFTSEZRyANIBsop/U+t+d1Z1/UXXoE9+iwjSGKJsaym6PgBLPb2d8XdmS/qR6Tcx7lVodTp4cVtezKnA== @@ -5559,7 +5569,7 @@ resolved "https://registry.yarnpkg.com/@walletconnect/mobile-registry/-/mobile-registry-1.4.0.tgz#502cf8ab87330841d794819081e748ebdef7aee5" integrity sha512-ZtKRio4uCZ1JUF7LIdecmZt7FOLnX72RPSY7aUVu7mj7CSfxDwUn6gBuK6WGtH+NZCldBqDl5DenI5fFSvkKYw== -"@walletconnect/modal@^2.4.5": +"@walletconnect/modal@2.4.7", "@walletconnect/modal@^2.4.5": version "2.4.7" resolved "https://registry.yarnpkg.com/@walletconnect/modal/-/modal-2.4.7.tgz#fd84d6f1ac767865d63153e32150f790739a189a" integrity sha512-kFpvDTT44CgNGcwQVC0jHrYed4xorghKX1DOGo8ZfBSJ5TJx3p6d6SzLxkH1cZupWbljWkYS6SqvZcUBs8vWpg== @@ -9652,7 +9662,7 @@ eventemitter2@6.4.7: resolved "https://registry.yarnpkg.com/eventemitter2/-/eventemitter2-6.4.7.tgz#a7f6c4d7abf28a14c1ef3442f21cb306a054271d" integrity sha512-tYUSVOGeQPKt/eC1ABfhHy5Xd96N3oIijJvN3O9+TsC28T5V9yX9oEfEK5faP0EFSNVOG97qtAS68GBrQB2hDg== -eventemitter3@^4.0.0, eventemitter3@^4.0.1, eventemitter3@^4.0.4, eventemitter3@^4.0.7: +eventemitter3@4.0.7, eventemitter3@^4.0.0, eventemitter3@^4.0.1, eventemitter3@^4.0.4, eventemitter3@^4.0.7: version "4.0.7" resolved "https://registry.yarnpkg.com/eventemitter3/-/eventemitter3-4.0.7.tgz#2de9b68f6528d5644ef5c59526a1b4a07306169f" integrity sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==