diff --git a/.eslintrc.js b/.eslintrc.js index 872ecd51a1..d49432d112 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -62,7 +62,12 @@ module.exports = { '@typescript-eslint/no-var-requires': 'off', '@typescript-eslint/no-unused-vars': [ 'warn', - { ignoreRestSiblings: true, argsIgnorePattern: '^_', caughtErrorsIgnorePattern: '^_' }, + { + ignoreRestSiblings: true, + argsIgnorePattern: '^_', + caughtErrorsIgnorePattern: '^_', + destructuredArrayIgnorePattern: '^_', + }, ], 'no-empty-function': 'off', '@typescript-eslint/no-empty-function': 'off', diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 0f80ebb7bd..cabf110ec8 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -97,11 +97,11 @@ jobs: path: /tmp/.buildx-cache key: ${{ runner.os }}-${{ env.SERVICE }}-buildx - - name: Restore node_modules - uses: actions/cache@v2 - with: - path: '**/node_modules' - key: ${{ runner.os }}-modules-${{ hashFiles('**/yarn.lock') }} + # - name: Restore node_modules + # uses: actions/cache@v2 + # with: + # path: '**/node_modules' + # key: ${{ runner.os }}-modules-${{ hashFiles('**/yarn.lock') }} - name: Install dependences uses: bahmutov/npm-install@HEAD diff --git a/.gitignore b/.gitignore index 019846ceb9..930cb8289b 100644 --- a/.gitignore +++ b/.gitignore @@ -26,7 +26,7 @@ npm-debug.log* yarn-debug.log* yarn-error.log* -notes.txt +notes*.* .idea/ .vscode/ diff --git a/patches/@walletconnect+ethereum-provider+2.8.1.patch b/patches/@walletconnect+ethereum-provider+2.8.1.patch index 3f1eb1b4c8..35f3ecddd5 100644 --- a/patches/@walletconnect+ethereum-provider+2.8.1.patch +++ b/patches/@walletconnect+ethereum-provider+2.8.1.patch @@ -12,7 +12,7 @@ index db2e087..2ba50a0 100644 +++ 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}; ++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;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 @@ -23,7 +23,7 @@ index 83e05d2..7df0974 100644 `:`; `)+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};/*! ++}`;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;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/PoolList/ItemCard/index.tsx b/src/components/PoolList/ItemCard/index.tsx index b9ee672507..33528f141e 100644 --- a/src/components/PoolList/ItemCard/index.tsx +++ b/src/components/PoolList/ItemCard/index.tsx @@ -31,15 +31,16 @@ import { APP_PATHS, DMM_ANALYTICS_URL, ONE_BIPS, SUBGRAPH_AMP_MULTIPLIER } from import { EVMNetworkInfo } from 'constants/networks/type' import { NativeCurrencies } from 'constants/tokens' import { useActiveWeb3React } from 'hooks' +import { ClassicPoolData } from 'hooks/pool/classic/type' import useTheme from 'hooks/useTheme' import { IconWrapper } from 'pages/Pools/styleds' import { useActiveAndUniqueFarmsData } from 'state/farms/classic/hooks' import { Farm } from 'state/farms/classic/types' import { useMultipleContractSingleData } from 'state/multicall/hooks' -import { SubgraphPoolData, UserLiquidityPosition, useSharedPoolIdManager } from 'state/pools/hooks' +import { UserLiquidityPosition, useSharedPoolIdManager } from 'state/pools/hooks' import { tryParseAmount } from 'state/swap/hooks' import { ExternalLink } from 'theme' -import { formattedNum, shortenAddress } from 'utils' +import { shortenAddress } from 'utils' import { currencyId } from 'utils/currencyId' import { feeRangeCalc, @@ -49,6 +50,7 @@ import { priceRangeCalcBySubgraphPool, useFarmApr, } from 'utils/dmm' +import { formatDisplayNumber, parseFraction } from 'utils/numbers' import { getTokenSymbolWithHardcode } from 'utils/tokenInfo' const StyledLink = styled(ExternalLink)` @@ -57,7 +59,7 @@ const StyledLink = styled(ExternalLink)` } ` interface ListItemProps { - poolData: SubgraphPoolData + poolData: ClassicPoolData myLiquidity?: UserLiquidityPosition } @@ -104,7 +106,11 @@ const ItemCard = ({ poolData, myLiquidity }: ListItemProps) => { const [, setSharedPoolId] = useSharedPoolIdManager() - const ampLiquidity = formattedNum(`${parseFloat(amp.toSignificant(5)) * parseFloat(poolData.reserveUSD)}`, true) + const ampLiquidity = formatDisplayNumber(amp.multiply(parseFraction(poolData.reserveUSD)), { + style: 'currency', + significantDigits: 7, + fractionDigits: 4, + }) const volume = poolData.oneDayVolumeUSD ? poolData.oneDayVolumeUSD : poolData.oneDayVolumeUntracked const fee24H = poolData.oneDayFeeUSD ? poolData.oneDayFeeUSD : poolData.oneDayFeeUntracked const oneYearFL = getTradingFeeAPR(poolData.reserveUSD, fee24H).toFixed(2) @@ -131,7 +137,7 @@ const ItemCard = ({ poolData, myLiquidity }: ListItemProps) => { {currency0Symbol} - {currency1Symbol} - AMP {formattedNum(amp.toSignificant(5))} + AMP {formatDisplayNumber(amp, { significantDigits: 5 })} {isFarmingPool && ( { - {formattedNum(volume, true)} - {formattedNum(fee24H, true)} + {formatDisplayNumber(volume, { style: 'currency', significantDigits: 5 })} + {formatDisplayNumber(fee24H, { style: 'currency', significantDigits: 5 })} @@ -327,7 +333,9 @@ const ItemCard = ({ poolData, myLiquidity }: ListItemProps) => { fontWeight="500" marginTop="0.25rem" > - {formattedNum(poolData.reserveUSD, true)} + + {formatDisplayNumber(poolData.reserveUSD, { style: 'currency', significantDigits: 7, fractionDigits: 4 })} + {ampLiquidity} {myLiquidity ? getMyLiquidity(myLiquidity) : '-'} @@ -491,10 +499,7 @@ const ItemCard = ({ poolData, myLiquidity }: ListItemProps) => { } const FarmCalculator = ({ farm, onUpdate }: { farm: Farm; onUpdate: (value: number) => void }) => { - const lpTokenRatio = new Fraction( - farm.totalStake.toString(), - JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(18)), - ).divide( + const lpTokenRatio = farm.totalStake.divide( new Fraction(parseUnits(farm.totalSupply, 18).toString(), JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(18))), ) const liquidity = parseFloat(lpTokenRatio.toSignificant(6)) * parseFloat(farm.reserveUSD) diff --git a/src/components/PoolList/ListItem.tsx b/src/components/PoolList/ListItem.tsx index cf8c864445..d38227715b 100644 --- a/src/components/PoolList/ListItem.tsx +++ b/src/components/PoolList/ListItem.tsx @@ -19,19 +19,21 @@ import { FeeTag } from 'components/YieldPools/ElasticFarmGroup/styleds' import { ClassicFarmingPoolAPRCell } from 'components/YieldPools/FarmingPoolAPRCell' import { APP_PATHS, MAX_ALLOW_APY } from 'constants/index' import { useActiveWeb3React } from 'hooks' +import { ClassicPoolData } from 'hooks/pool/classic/type' import useTheme from 'hooks/useTheme' import { IconWrapper } from 'pages/Pools/styleds' import { usePoolDetailModalToggle } from 'state/application/hooks' import { useActiveAndUniqueFarmsData } from 'state/farms/classic/hooks' import { setSelectedPool } from 'state/pools/actions' -import { SubgraphPoolData, UserLiquidityPosition, useSharedPoolIdManager } from 'state/pools/hooks' -import { formattedNum, shortenAddress } from 'utils' +import { UserLiquidityPosition, useSharedPoolIdManager } from 'state/pools/hooks' +import { shortenAddress } from 'utils' import { currencyId } from 'utils/currencyId' import { getMyLiquidity, getTradingFeeAPR, parseSubgraphPoolData } from 'utils/dmm' +import { formatDisplayNumber, parseFraction } from 'utils/numbers' import { getTokenSymbolWithHardcode } from 'utils/tokenInfo' interface ListItemGroupProps { - poolData: SubgraphPoolData + poolData: ClassicPoolData userLiquidityPositions: { [key: string]: UserLiquidityPosition } } @@ -57,7 +59,6 @@ const ListItem = ({ poolData, userLiquidityPositions }: ListItemGroupProps) => { ) const currency0Symbol = getTokenSymbolWithHardcode(chainId, currency0.wrapped.address, currency0.symbol) const currency1Symbol = getTokenSymbolWithHardcode(chainId, currency1.wrapped.address, currency1.symbol) - const realPercentToken0 = reserve0 && virtualReserve0 && reserve1 && virtualReserve1 ? reserve0.asFraction @@ -73,8 +74,16 @@ const ListItem = ({ poolData, userLiquidityPositions }: ListItemGroupProps) => { const oneYearFL = getTradingFeeAPR(poolData.reserveUSD, fee24H).toFixed(2) - const ampLiquidity = formattedNum(`${parseFloat(amp.toSignificant(5)) * parseFloat(poolData.reserveUSD)}`, true) - const totalValueLocked = formattedNum(`${parseFloat(poolData.reserveUSD)}`, true) + const ampLiquidity = formatDisplayNumber(amp.multiply(parseFraction(poolData.reserveUSD)), { + style: 'currency', + significantDigits: 7, + fractionDigits: 4, + }) + const totalValueLocked = formatDisplayNumber(poolData.reserveUSD, { + style: 'currency', + significantDigits: 7, + fractionDigits: 4, + }) const onTogglePoolDetailModal = (event: React.MouseEvent) => { event.stopPropagation() @@ -111,7 +120,7 @@ const ListItem = ({ poolData, userLiquidityPositions }: ListItemGroupProps) => { paddingRight: '20px', // to make all the APR numbers vertically align }} > - {oneYearFL}% + {formatDisplayNumber(Number(oneYearFL) / 100, { style: 'percent', fractionDigits: 2 })} ) } @@ -124,7 +133,7 @@ const ListItem = ({ poolData, userLiquidityPositions }: ListItemGroupProps) => { {currency0Symbol} - {currency1Symbol} - AMP {formattedNum(amp.toSignificant(5))} + AMP {formatDisplayNumber(amp, { significantDigits: 5 })} {isFarmingPool && ( @@ -185,8 +194,12 @@ const ListItem = ({ poolData, userLiquidityPositions }: ListItemGroupProps) => { > {renderAPR()} - {!poolData ? : formattedNum(volume, true)} - {!poolData ? : formattedNum(fee24H, true)} + + {!poolData ? : formatDisplayNumber(volume, { style: 'currency', significantDigits: 6 })} + + + {!poolData ? : formatDisplayNumber(fee24H, { style: 'currency', significantDigits: 6 })} + {getMyLiquidity(myLiquidity)} `1px solid ${theme.border}`}; text-align: right; + ${({ theme }) => theme.mediaWidth.upToLarge` + grid-template-columns: 3fr 120px 80px 1fr 1fr 1fr 1fr; + `}; ` const Grid = styled.div` padding: 24px; @@ -101,8 +105,9 @@ const ITEM_PER_PAGE = 12 const PoolList = ({ currencies, searchValue, isShowOnlyActiveFarmPools, onlyShowStable }: PoolListProps) => { const above1000 = useMedia('(min-width: 1000px)') + const upToLarge = useMedia(`(max-width: ${MEDIA_WIDTHS.upToLarge}px)`) - const { loading: loadingPoolsData, data: subgraphPoolsData } = useAllPoolsData() + const { loading: loadingPoolsData, data: classicPoolsData } = useGetClassicPools() const { account, chainId, networkInfo, isEVM } = useActiveWeb3React() const [viewMode] = useViewMode() @@ -134,7 +139,7 @@ const PoolList = ({ currencies, searchValue, isShowOnlyActiveFarmPools, onlyShow const sortDirection = sortOrder === SORT_DIRECTION.DESC const listComparator = useCallback( - (poolA: SubgraphPoolData, poolB: SubgraphPoolData): number => { + (poolA: ClassicPoolData, poolB: ClassicPoolData): number => { const feeA = poolA?.oneDayFeeUSD ? poolA?.oneDayFeeUSD : poolA?.oneDayFeeUntracked const feeB = poolB?.oneDayFeeUSD ? poolB?.oneDayFeeUSD : poolB?.oneDayFeeUntracked const a = transformedUserLiquidityPositions[poolA.id] @@ -199,20 +204,29 @@ const PoolList = ({ currencies, searchValue, isShowOnlyActiveFarmPools, onlyShow - handleSort(SORT_FIELD.TVL)} style={{ textAlign: 'right' }}> - AMP LIQUIDITY - - | - TVL - {sortedColumn === SORT_FIELD.TVL ? ( - !sortDirection ? ( - + handleSort(SORT_FIELD.TVL)} + style={{ textAlign: 'right' }} + flexDirection={upToLarge ? 'column' : 'row'} + alignItems="flex-end" + > + + AMP LIQUIDITY + + + {upToLarge ? : |} + + TVL + {sortedColumn === SORT_FIELD.TVL ? ( + !sortDirection ? ( + + ) : ( + + ) ) : ( - - ) - ) : ( - '' - )} + '' + )} + { - let res = [...subgraphPoolsData] + const sortedFilteredClassicPoolsData = useMemo(() => { + let res = [...classicPoolsData] if (isShowOnlyActiveFarmPools) { const farmAddresses = farms.map(farm => farm.id) @@ -320,7 +334,7 @@ const PoolList = ({ currencies, searchValue, isShowOnlyActiveFarmPools, onlyShow const wca = ca.wrapped const wcaAddress = wca && wca.address.toLowerCase() res = res.filter( - poolData => wcaAddress && (poolData.token0.id === wcaAddress || poolData.token1.id === wcaAddress), + poolData => wcaAddress && (poolData.token0.address === wcaAddress || poolData.token1.address === wcaAddress), ) } @@ -328,7 +342,7 @@ const PoolList = ({ currencies, searchValue, isShowOnlyActiveFarmPools, onlyShow const wcb = cb.wrapped const wcbAddress = wcb && wcb.address.toLowerCase() res = res.filter( - poolData => wcbAddress && (poolData.token0.id === wcbAddress || poolData.token1.id === wcbAddress), + poolData => wcbAddress && (poolData.token0.address === wcbAddress || poolData.token1.address === wcbAddress), ) } @@ -336,8 +350,8 @@ const PoolList = ({ currencies, searchValue, isShowOnlyActiveFarmPools, onlyShow const search = searchValue.toLowerCase() return ( - poolData.token0.symbol.toLowerCase().includes(search) || - poolData.token1.symbol.toLowerCase().includes(search) || + poolData.token0.symbol?.toLowerCase().includes(search) || + poolData.token1.symbol?.toLowerCase().includes(search) || poolData.id.includes(search) ) }) @@ -346,14 +360,15 @@ const PoolList = ({ currencies, searchValue, isShowOnlyActiveFarmPools, onlyShow const stableList = isEVM ? stableCoins?.map(item => item.address.toLowerCase()) || [] : [] res = res.filter(poolData => { return ( - stableList.includes(poolData.token0.id.toLowerCase()) && stableList.includes(poolData.token1.id.toLowerCase()) + stableList.includes(poolData.token0.address.toLowerCase()) && + stableList.includes(poolData.token1.address.toLowerCase()) ) }) } return res.sort(listComparator) }, [ - subgraphPoolsData, + classicPoolsData, listComparator, isShowOnlyActiveFarmPools, currencies, @@ -366,11 +381,11 @@ const PoolList = ({ currencies, searchValue, isShowOnlyActiveFarmPools, onlyShow const startIndex = (currentPage - 1) * ITEM_PER_PAGE const endIndex = currentPage * ITEM_PER_PAGE - const pageData = sortedFilteredSubgraphPoolsData.slice(startIndex, endIndex) + const pageData = sortedFilteredClassicPoolsData.slice(startIndex, endIndex) useEffect(() => { setCurrentPage(1) - }, [chainId, subgraphPoolsData, currencies, searchValue, isShowOnlyActiveFarmPools, onlyShowStable]) + }, [chainId, classicPoolsData, currencies, searchValue, isShowOnlyActiveFarmPools, onlyShowStable]) const [sharedPoolId, setSharedPoolId] = useSharedPoolIdManager() const openShareModal = useOpenModal(ApplicationModal.SHARE) @@ -395,7 +410,7 @@ const PoolList = ({ currencies, searchValue, isShowOnlyActiveFarmPools, onlyShow if (loadingUserLiquidityPositions || loadingPoolsData) return - if (sortedFilteredSubgraphPoolsData.length === 0) + if (sortedFilteredClassicPoolsData.length === 0) return (
@@ -435,7 +450,7 @@ const PoolList = ({ currencies, searchValue, isShowOnlyActiveFarmPools, onlyShow pageSize={ITEM_PER_PAGE} onPageChange={newPage => setCurrentPage(newPage)} currentPage={currentPage} - totalCount={sortedFilteredSubgraphPoolsData.length} + totalCount={sortedFilteredClassicPoolsData.length} haveBg={above1000} /> diff --git a/src/components/PoolList/styled.tsx b/src/components/PoolList/styled.tsx index f53d56401a..d9d15dffaa 100644 --- a/src/components/PoolList/styled.tsx +++ b/src/components/PoolList/styled.tsx @@ -18,6 +18,9 @@ export const TableRow = styled.div` border-bottom-right-radius: 20px; border-bottom-left-radius: 20px; } + ${({ theme }) => theme.mediaWidth.upToLarge` + grid-template-columns: 3fr 120px 1fr 1fr 1fr 1fr 1fr; + `}; ` export const DataText = styled(Flex)` diff --git a/src/components/SwapForm/hooks/useGetSwapFeeConfig.ts b/src/components/SwapForm/hooks/useGetSwapFeeConfig.ts index ccf88fb54b..0e3f030538 100644 --- a/src/components/SwapForm/hooks/useGetSwapFeeConfig.ts +++ b/src/components/SwapForm/hooks/useGetSwapFeeConfig.ts @@ -88,7 +88,7 @@ const useGetSwapFeeConfig = () => { try { const result = await Promise.race([getSingleTokenScore(chainId, tokenAddress), timeoutReject(1_000)]) if (result) { - return result as string + return result } return undefined diff --git a/src/components/YieldPools/ElasticFarmGroup/index.tsx b/src/components/YieldPools/ElasticFarmGroup/index.tsx index 9c26bdb5c0..a073492216 100644 --- a/src/components/YieldPools/ElasticFarmGroup/index.tsx +++ b/src/components/YieldPools/ElasticFarmGroup/index.tsx @@ -20,7 +20,7 @@ import { NETWORKS_INFO, isEVM } from 'constants/networks' import { useActiveWeb3React } from 'hooks' import { useProAmmNFTPositionManagerContract } from 'hooks/useContract' import useTheme from 'hooks/useTheme' -import { Dots } from 'pages/Pool/styleds' +import { Dots } from 'pages/MyPool/styleds' import { useWalletModalToggle } from 'state/application/hooks' import { useDepositedNftsByFarm, useElasticFarms, useFarmAction, useUserInfoByFarm } from 'state/farms/elastic/hooks' import { FarmingPool } from 'state/farms/elastic/types' diff --git a/src/components/YieldPools/ElasticFarmGroup/styleds.tsx b/src/components/YieldPools/ElasticFarmGroup/styleds.tsx index 265977795e..fba3531bb1 100644 --- a/src/components/YieldPools/ElasticFarmGroup/styleds.tsx +++ b/src/components/YieldPools/ElasticFarmGroup/styleds.tsx @@ -33,7 +33,8 @@ export const FarmList = styled.div<{ gridMode: boolean }>` ` export const FeeTag = styled.div` - width: fit-content; + min-width: max-content; + width: max-content; border-radius: 999px; background: ${({ theme }) => theme.darkBlue + '33'}; color: ${({ theme }) => theme.darkBlue}; @@ -41,7 +42,6 @@ export const FeeTag = styled.div` font-weight: 500; padding: 2px 6px; margin-left: 6px; - min-width: 36px; display: flex; align-items: center; gap: 4px; diff --git a/src/components/YieldPools/FairLaunchPools.tsx b/src/components/YieldPools/FairLaunchPools.tsx index efc5084a43..77da2a76c0 100644 --- a/src/components/YieldPools/FairLaunchPools.tsx +++ b/src/components/YieldPools/FairLaunchPools.tsx @@ -11,7 +11,6 @@ import Row, { RowBetween, RowFit } from 'components/Row' import { AMP_HINT } from 'constants/index' import { EVMNetworkInfo } from 'constants/networks/type' import { useActiveWeb3React } from 'hooks' -import { useFairLaunchVersion } from 'hooks/useContract' import useFairLaunch from 'hooks/useFairLaunch' import useMixpanel, { MIXPANEL_TYPE } from 'hooks/useMixpanel' import useTheme from 'hooks/useTheme' @@ -60,7 +59,6 @@ const FairLaunchPools = ({ fairLaunchAddress, farms, active }: FarmsListProps) = const theme = useTheme() const blockNumber = useBlockNumber() const totalRewards = useFarmRewards(farms) - const fairLaunchVersion = useFairLaunchVersion(fairLaunchAddress) const { harvestMultiplePools } = useFairLaunch(fairLaunchAddress) const { mixpanelHandler } = useMixpanel() @@ -115,48 +113,49 @@ const FairLaunchPools = ({ fairLaunchAddress, farms, active }: FarmsListProps) = const currentTimestamp = Math.floor(Date.now() / 1000) - const farmsList = - fairLaunchVersion === FairLaunchVersion.V1 - ? (farms || []).map(farm => { - const isFarmStarted = farm && blockNumber && farm.startBlock < blockNumber - const isFarmEnded = farm && blockNumber && farm.endBlock < blockNumber - - let remainingBlocks: number | false | undefined - - if (!isFarmStarted) { - remainingBlocks = farm && blockNumber && farm.startBlock - blockNumber - } else { - remainingBlocks = farm && blockNumber && farm.endBlock - blockNumber - } - const estimatedRemainingSeconds = - remainingBlocks && remainingBlocks * (networkInfo as EVMNetworkInfo).averageBlockTimeInSeconds - const formattedEstimatedRemainingTime = - estimatedRemainingSeconds && getFormattedTimeFromSecond(estimatedRemainingSeconds) - - return { - ...farm, - time: `${isFarmEnded ? 'Ended' : 'Starting in ' + formattedEstimatedRemainingTime}`, - } - }) - : (farms || []).map(farm => { - const isFarmStarted = farm && currentTimestamp && farm.startTime < currentTimestamp - const isFarmEnded = farm && currentTimestamp && farm.endTime < currentTimestamp - - let formattedEstimatedRemainingTime: string - - if (!isFarmStarted) { - formattedEstimatedRemainingTime = getFormattedTimeFromSecond(farm.startTime - currentTimestamp) - } else { - formattedEstimatedRemainingTime = getFormattedTimeFromSecond(farm.endTime - currentTimestamp) - } - - return { - ...farm, - time: `${isFarmEnded ? 'Ended' : (isFarmStarted ? '' : 'Starting in ') + formattedEstimatedRemainingTime}`, - } - }) + const farmsList: Farm[] = (farms || [])?.map(farm => { + if (farm.version === FairLaunchVersion.V1) { + const isFarmStarted = farm && blockNumber && farm.startBlock < blockNumber + const isFarmEnded = farm && blockNumber && farm.endBlock < blockNumber + + let remainingBlocks: number | false | undefined + + if (!isFarmStarted) { + remainingBlocks = farm && blockNumber && farm.startBlock - blockNumber + } else { + remainingBlocks = farm && blockNumber && farm.endBlock - blockNumber + } + const estimatedRemainingSeconds = + remainingBlocks && remainingBlocks * (networkInfo as EVMNetworkInfo).averageBlockTimeInSeconds + const formattedEstimatedRemainingTime = + estimatedRemainingSeconds && getFormattedTimeFromSecond(estimatedRemainingSeconds) + + return { + ...farm, + time: `${isFarmEnded ? 'Ended' : 'Starting in ' + formattedEstimatedRemainingTime}`, + } + } else { + const isFarmStarted = farm && currentTimestamp && farm.startTime < currentTimestamp + const isFarmEnded = farm && currentTimestamp && farm.endTime < currentTimestamp + + let formattedEstimatedRemainingTime: string - const displayFarms = farmsList.sort((a, b) => b.endBlock - a.endBlock) + if (!isFarmStarted) { + formattedEstimatedRemainingTime = getFormattedTimeFromSecond(farm.startTime - currentTimestamp) + } else { + formattedEstimatedRemainingTime = getFormattedTimeFromSecond(farm.endTime - currentTimestamp) + } + + return { + ...farm, + time: `${isFarmEnded ? 'Ended' : (isFarmStarted ? '' : 'Starting in ') + formattedEstimatedRemainingTime}`, + } + } + }) + + const displayFarms = farmsList.sort((a, b) => + a.version === FairLaunchVersion.V1 && b.version === FairLaunchVersion.V1 ? b.endBlock - a.endBlock : 0, + ) const ConditionListWrapper = viewMode === VIEW_MODE.LIST && above1200 ? ListItemWrapper : ClassicFarmGridWrapper if (!isEVM) return diff --git a/src/components/YieldPools/FarmingPoolAPRCell.tsx b/src/components/YieldPools/FarmingPoolAPRCell.tsx index c3013b2994..8c347c3063 100644 --- a/src/components/YieldPools/FarmingPoolAPRCell.tsx +++ b/src/components/YieldPools/FarmingPoolAPRCell.tsx @@ -176,10 +176,7 @@ const FarmingPoolAPRCell: React.FC = ({ export const ClassicFarmingPoolAPRCell = ({ poolAPR, farm }: { poolAPR: number; farm: Farm }) => { const theme = useTheme() - const lpTokenRatio = new Fraction( - farm.totalStake.toString(), - JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(18)), - ).divide( + const lpTokenRatio = farm.totalStake.divide( new Fraction(parseUnits(farm.totalSupply, 18).toString(), JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(18))), ) const liquidity = parseFloat(lpTokenRatio.toSignificant(6)) * parseFloat(farm.reserveUSD) diff --git a/src/components/YieldPools/HarvestAll.tsx b/src/components/YieldPools/HarvestAll.tsx index 149f8dbc63..a3a691423c 100644 --- a/src/components/YieldPools/HarvestAll.tsx +++ b/src/components/YieldPools/HarvestAll.tsx @@ -19,7 +19,7 @@ import { Reward } from 'state/farms/classic/types' import { formattedNum } from 'utils' import { useFarmRewardsUSD } from 'utils/dmm' import { fixedFormatting, getFullDisplayBalance } from 'utils/formatBalance' -import { formatDollarAmount } from 'utils/numbers' +import { formatDisplayNumber } from 'utils/numbers' import { ModalContentWrapper } from './ElasticFarmModals/styled' import { RewardBalanceWrapper } from './styleds' @@ -112,7 +112,7 @@ const HarvestAll = ({ totalRewards, onHarvestAll }: { totalRewards: Reward[]; on padding="4px 0" content={ - {formatDollarAmount(totalRewardsUSD)} + {formatDisplayNumber(totalRewardsUSD, { style: 'currency', significantDigits: 4 })} } dropdownContent={ @@ -181,7 +181,7 @@ const HarvestAll = ({ totalRewards, onHarvestAll }: { totalRewards: Reward[]; on padding="4px 0" content={ - {formatDollarAmount(totalRewardsUSD)} + {formatDisplayNumber(totalRewardsUSD, { style: 'currency', significantDigits: 4 })} } dropdownContent={ diff --git a/src/components/YieldPools/ListItem.tsx b/src/components/YieldPools/ListItem.tsx index 8bffef527c..19352a890d 100644 --- a/src/components/YieldPools/ListItem.tsx +++ b/src/components/YieldPools/ListItem.tsx @@ -25,7 +25,6 @@ import Row, { RowBetween, RowFit } from 'components/Row' import { MouseoverTooltip } from 'components/Tooltip' import { APP_PATHS, DMM_ANALYTICS_URL, MAX_ALLOW_APY } from 'constants/index' import { useActiveWeb3React } from 'hooks' -import { useToken } from 'hooks/Tokens' import { ApprovalState, useApproveCallback } from 'hooks/useApproveCallback' import useFairLaunch from 'hooks/useFairLaunch' import useMixpanel, { MIXPANEL_TYPE } from 'hooks/useMixpanel' @@ -36,17 +35,17 @@ import useTokenBalance from 'hooks/useTokenBalance' import { useWalletModalToggle } from 'state/application/hooks' import { setAttemptingTxn, setShowConfirm, setTxHash, setYieldPoolsError } from 'state/farms/classic/actions' import { useShareFarmAddress } from 'state/farms/classic/hooks' -import { Farm, Reward } from 'state/farms/classic/types' +import { FairLaunchVersion, Farm, Reward } from 'state/farms/classic/types' import { useAppDispatch } from 'state/hooks' import { useViewMode } from 'state/user/hooks' import { VIEW_MODE } from 'state/user/reducer' import { ExternalLink } from 'theme' -import { formattedNum, isAddressString, shortenAddress } from 'utils' +import { isAddressString, shortenAddress } from 'utils' import { currencyIdFromAddress } from 'utils/currencyId' import { getTradingFeeAPR, useFarmApr, useFarmRewards, useFarmRewardsUSD } from 'utils/dmm' -import { formatTokenBalance, getFullDisplayBalance } from 'utils/formatBalance' +import { getFullDisplayBalance } from 'utils/formatBalance' import { getFormattedTimeFromSecond } from 'utils/formatTime' -import { formatDollarAmount } from 'utils/numbers' +import { formatDisplayNumber, parseFraction } from 'utils/numbers' import { unwrappedToken } from 'utils/wrappedCurrency' import { ModalContentWrapper } from './ElasticFarmModals/styled' @@ -79,23 +78,20 @@ const ListItem = ({ farm }: ListItemProps) => { const above1200 = useMedia('(min-width: 1200px)') const dispatch = useAppDispatch() - const currency0 = useToken(farm.token0?.id) as Token - const currency1 = useToken(farm.token1?.id) as Token + const currency0 = unwrappedToken(farm.token0) + const currency1 = unwrappedToken(farm.token1) const poolAddressChecksum = isAddressString(chainId, farm.id) const { value: userTokenBalance, decimals: lpTokenDecimals } = useTokenBalance(poolAddressChecksum) const userStakedBalance = farm.userData?.stakedBalance - ? BigNumber.from(farm.userData?.stakedBalance) + ? BigNumber.from(farm.userData.stakedBalance) : BigNumber.from(0) const farmRewards = useFarmRewards([farm]) // Ratio in % of LP tokens that are staked in the MC, vs the total number in circulation - const lpTokenRatio = new Fraction( - farm.totalStake.toString(), - JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(lpTokenDecimals)), - ).divide( + const lpTokenRatio = farm.totalStake.divide( new Fraction( ethers.utils.parseUnits(farm.totalSupply, lpTokenDecimals).toString(), JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(lpTokenDecimals)), @@ -130,8 +126,8 @@ const ListItem = ({ farm }: ListItemProps) => { const userStakedToken0Balance = parseFloat(lpUserStakedTokenRatio.toSignificant(6)) * parseFloat(farm.reserve0) const userStakedToken1Balance = parseFloat(lpUserStakedTokenRatio.toSignificant(6)) * parseFloat(farm.reserve1) - const userLPBalanceUSD = parseFloat(lpUserLPBalanceRatio.toSignificant(6)) * parseFloat(farm.reserveUSD) - const userStakedBalanceUSD = parseFloat(lpUserStakedTokenRatio.toSignificant(6)) * parseFloat(farm.reserveUSD) + const userLPBalanceUSD = lpUserLPBalanceRatio.multiply(parseFraction(farm.reserveUSD)) + const userStakedBalanceUSD = lpUserStakedTokenRatio.multiply(parseFraction(farm.reserveUSD)) const liquidity = parseFloat(lpTokenRatio.toSignificant(6)) * parseFloat(farm.reserveUSD) @@ -146,12 +142,9 @@ const ListItem = ({ farm }: ListItemProps) => { const amp = farm.amp / 10000 - const pairSymbol = - currency0 && currency1 - ? `${unwrappedToken(currency0).symbol}-${unwrappedToken(currency1).symbol} LP` - : `${farm.token0.symbol} - ${farm.token1.symbol} LP` - const symbol0 = currency0 ? unwrappedToken(currency0).symbol : farm.token0.symbol - const symbol1 = currency1 ? unwrappedToken(currency1).symbol : farm.token1.symbol + const symbol0 = currency0 ? currency0.symbol : farm.token0.symbol + const symbol1 = currency1 ? currency1.symbol : farm.token1.symbol + const pairSymbol = `${symbol0}-${symbol1} LP` const [depositValue, setDepositValue] = useState('') const [withdrawValue, setWithdrawValue] = useState('') @@ -299,11 +292,11 @@ const ListItem = ({ farm }: ListItemProps) => { const usd = () => { switch (modalType) { case 'stake': - return formattedNum(userLPBalanceUSD.toString(), true) + return formatDisplayNumber(userLPBalanceUSD, { style: 'currency', significantDigits: 4 }) case 'unstake': - return formattedNum(userStakedBalanceUSD.toString(), true) + return formatDisplayNumber(userStakedBalanceUSD, { style: 'currency', significantDigits: 4 }) default: - return formattedNum(rewardUSD.toString(), true) + return formatDisplayNumber(rewardUSD, { style: 'currency', significantDigits: 4 }) } } @@ -315,16 +308,16 @@ const ListItem = ({ farm }: ListItemProps) => { <> {viewMode === VIEW_MODE.LIST && above1200 && ( <> - + {/* POOLS | AMP */} {symbol0} - {symbol1} @@ -372,12 +365,12 @@ const ListItem = ({ farm }: ListItemProps) => { {/* STAKED TVL */} - {formatDollarAmount(liquidity)} + {formatDisplayNumber(liquidity, { style: 'currency', significantDigits: 6 })} {/* AVG APR */} - {apr.toFixed(2)}% + {formatDisplayNumber(apr / 100, { style: 'percent', fractionDigits: 2 })} {apr !== 0 && ( { {/* ENDING IN */} - {farm.startTime > currentTimestamp ? ( + {(farm.version === FairLaunchVersion.V2 || farm.version === FairLaunchVersion.V3) && + farm.startTime > currentTimestamp ? ( <> New phase will start in {getFormattedTimeFromSecond(farm.startTime - currentTimestamp)} - ) : farm.endTime > currentTimestamp ? ( + ) : (farm.version === FairLaunchVersion.V2 || farm.version === FairLaunchVersion.V3) && + farm.endTime > currentTimestamp ? ( <> Current phase will end in @@ -415,7 +410,7 @@ const ListItem = ({ farm }: ListItemProps) => { )} {/* MY DEPOSIT | TARGET VOLUME */} - {formattedNum(userStakedBalanceUSD.toString(), true)} + {formatDisplayNumber(userStakedBalanceUSD, { style: 'currency', significantDigits: 4 })} {/* MY REWARDS */} {farmRewards.map(reward => { @@ -425,7 +420,10 @@ const ListItem = ({ farm }: ListItemProps) => { {chainId && reward.token.wrapped.address && ( )} - {getFullDisplayBalance(reward.amount, reward.token.decimals)} + {formatDisplayNumber(parseFraction(reward.amount).divide(10 ** reward.token.decimals), { + style: 'decimal', + fractionDigits: 6, + })}
) @@ -471,14 +469,14 @@ const ListItem = ({ farm }: ListItemProps) => { )} {(viewMode === VIEW_MODE.GRID || !above1200) && ( - + @@ -532,18 +530,20 @@ const ListItem = ({ farm }: ListItemProps) => { - {!!apr ? apr.toFixed(2) + '%' : '--'} + {formatDisplayNumber(apr / 100, { style: 'percent', fractionDigits: 2 })} Staked TVL - {farm.startTime > currentTimestamp ? ( + {(farm.version === FairLaunchVersion.V2 || farm.version === FairLaunchVersion.V3) && + farm.startTime > currentTimestamp ? ( New phase will start in - ) : farm.endTime > currentTimestamp ? ( + ) : (farm.version === FairLaunchVersion.V2 || farm.version === FairLaunchVersion.V3) && + farm.endTime > currentTimestamp ? ( Current phase will end in @@ -555,9 +555,9 @@ const ListItem = ({ farm }: ListItemProps) => { - {formatDollarAmount(liquidity)} + {formatDisplayNumber(liquidity, { style: 'currency', significantDigits: 6 })} - {farm.startTime !== undefined ? ( + {farm.version === FairLaunchVersion.V2 || farm.version === FairLaunchVersion.V3 ? ( farm.startTime > currentTimestamp ? ( {getFormattedTimeFromSecond(farm.startTime - currentTimestamp)} ) : farm.endTime > currentTimestamp ? ( @@ -577,7 +577,7 @@ const ListItem = ({ farm }: ListItemProps) => { - {!!userStakedBalanceUSD ? formatDollarAmount(userStakedBalanceUSD) : '--'} + {formatDisplayNumber(userStakedBalanceUSD, { style: 'currency', significantDigits: 6, allowZero: false })} @@ -593,7 +593,10 @@ const ListItem = ({ farm }: ListItemProps) => { {chainId && reward.token.wrapped.address && ( )} - {!!reward.amount && getFullDisplayBalance(reward.amount, reward.token.decimals)} + {formatDisplayNumber(parseFraction(reward.amount).divide(10 ** reward.token.decimals), { + style: 'decimal', + fractionDigits: 6, + })} {index !== arr.length - 1 && (
@@ -664,7 +667,10 @@ const ListItem = ({ farm }: ListItemProps) => { {chainId && reward.token.wrapped.address && } - {getFullDisplayBalance(reward.amount, reward.token.decimals)} + {formatDisplayNumber(parseFraction(reward.amount).divide(10 ** reward.token.decimals), { + style: 'decimal', + fractionDigits: 6, + })} {index !== farmRewards.length - 1 && |} @@ -676,7 +682,10 @@ const ListItem = ({ farm }: ListItemProps) => { - {formatTokenBalance(modalType === 'stake' ? userToken0Balance : userStakedToken0Balance)} + {formatDisplayNumber(modalType === 'stake' ? userToken0Balance : userStakedToken0Balance, { + style: 'decimal', + fractionDigits: 6, + })} | @@ -684,7 +693,10 @@ const ListItem = ({ farm }: ListItemProps) => { - {formatTokenBalance(modalType === 'stake' ? userToken1Balance : userStakedToken1Balance)} + {formatDisplayNumber(modalType === 'stake' ? userToken1Balance : userStakedToken1Balance, { + style: 'decimal', + fractionDigits: 6, + })} @@ -705,7 +717,7 @@ const ListItem = ({ farm }: ListItemProps) => { ) : ( <> - + {!account ? ( Connect @@ -794,9 +806,9 @@ const ListItem = ({ farm }: ListItemProps) => { diff --git a/src/components/YieldPools/index.tsx b/src/components/YieldPools/index.tsx index 8858e5743c..05867e857c 100644 --- a/src/components/YieldPools/index.tsx +++ b/src/components/YieldPools/index.tsx @@ -12,7 +12,7 @@ import useParsedQueryString from 'hooks/useParsedQueryString' import useTheme from 'hooks/useTheme' import { useBlockNumber } from 'state/application/hooks' import { useFarmsData } from 'state/farms/classic/hooks' -import { Farm } from 'state/farms/classic/types' +import { FairLaunchVersion, Farm } from 'state/farms/classic/types' import ConfirmHarvestingModal from './ConfirmHarvestingModal' @@ -41,23 +41,24 @@ const YieldPools = ({ loading, active }: { loading: boolean; active?: boolean }) const filterFarm = useCallback( (farm: Farm) => { - const filterByTime = farm.rewardPerSeconds - ? currentTimestampRef.current && - (qs.type === FARM_TAB.MY_FARMS - ? true - : active - ? farm.endTime >= currentTimestampRef.current - : farm.endTime < currentTimestampRef.current) - : blockNumberRef.current && - (qs.type === FARM_TAB.MY_FARMS - ? true - : active - ? farm.endBlock >= blockNumberRef.current - : farm.endBlock < blockNumberRef.current) + const filterByTime = + farm.version === FairLaunchVersion.V1 + ? blockNumberRef.current && + (qs.type === FARM_TAB.MY_FARMS + ? true + : active + ? farm.endBlock >= blockNumberRef.current + : farm.endBlock < blockNumberRef.current) + : currentTimestampRef.current && + (qs.type === FARM_TAB.MY_FARMS + ? true + : active + ? farm.endTime >= currentTimestampRef.current + : farm.endTime < currentTimestampRef.current) const filterBySearchText = debouncedSearchText - ? farm.token0?.symbol.toLowerCase().includes(debouncedSearchText) || - farm.token1?.symbol.toLowerCase().includes(debouncedSearchText) || + ? farm.token0?.symbol?.toLowerCase().includes(debouncedSearchText) || + farm.token1?.symbol?.toLowerCase().includes(debouncedSearchText) || farm.id === debouncedSearchText : true @@ -67,12 +68,12 @@ const YieldPools = ({ loading, active }: { loading: boolean; active?: boolean }) : true const filterByToken0 = token0 - ? farm.token0?.id.toLowerCase() === token0.toLowerCase() || - farm.token1?.id.toLowerCase() === token0.toLowerCase() + ? farm.token0?.address.toLowerCase() === token0.toLowerCase() || + farm.token1?.address.toLowerCase() === token0.toLowerCase() : true const filterByToken1 = token1 - ? farm.token0?.id.toLowerCase() === token1.toLowerCase() || - farm.token1?.id.toLowerCase() === token1.toLowerCase() + ? farm.token0?.address.toLowerCase() === token1.toLowerCase() || + farm.token1?.address.toLowerCase() === token1.toLowerCase() : true return filterByTime && filterBySearchText && filterByStakedOnly && filterByToken0 && filterByToken1 @@ -105,7 +106,7 @@ const YieldPools = ({ loading, active }: { loading: boolean; active?: boolean }) backgroundColor={theme.background} justifyContent="center" padding="32px" - style={{ borderBottomLeftRadius: '20px', borderBottomRightRadius: '20px' }} + style={{ borderRadius: '20px' }} > {debouncedSearchText ? No Farms found : Currently there are no Farms.} diff --git a/src/constants/abis/fairlaunch-v2.json b/src/constants/abis/fairlaunch-v2.json index 5f9e5b2914..31979a4bbc 100644 --- a/src/constants/abis/fairlaunch-v2.json +++ b/src/constants/abis/fairlaunch-v2.json @@ -426,56 +426,16 @@ "name": "getPoolInfo", "outputs": [ - { - "internalType": "uint256", - "name": "totalStake", - "type": "uint256" - }, - { - "internalType": "address", - "name": "stakeToken", - "type": "address" - }, - { - "internalType": "address", - "name": "generatedToken", - "type": "address" - }, - { - "internalType": "uint32", - "name": "startTime", - "type": "uint32" - }, - { - "internalType": "uint32", - "name": "endTime", - "type": "uint32" - }, - { - "internalType": "uint32", - "name": "lastRewardTime", - "type": "uint32" - }, - { - "internalType": "uint32", - "name": "vestingDuration", - "type": "uint32" - }, - { - "internalType": "uint256[]", - "name": "rewardPerSeconds", - "type": "uint256[]" - }, - { - "internalType": "uint256[]", - "name": "rewardMultipliers", - "type": "uint256[]" - }, - { - "internalType": "uint256[]", - "name": "accRewardPerShares", - "type": "uint256[]" - } + { "internalType": "uint256", "name": "totalStake", "type": "uint256" }, + { "internalType": "address", "name": "stakeToken", "type": "address" }, + { "internalType": "address", "name": "generatedToken", "type": "address" }, + { "internalType": "uint32", "name": "startTime", "type": "uint32" }, + { "internalType": "uint32", "name": "endTime", "type": "uint32" }, + { "internalType": "uint32", "name": "lastRewardTime", "type": "uint32" }, + { "internalType": "uint32", "name": "vestingDuration", "type": "uint32" }, + { "internalType": "uint256[]", "name": "rewardPerSeconds", "type": "uint256[]" }, + { "internalType": "uint256[]", "name": "rewardMultipliers", "type": "uint256[]" }, + { "internalType": "uint256[]", "name": "accRewardPerShares", "type": "uint256[]" } ], "stateMutability": "view", "type": "function" diff --git a/src/constants/index.ts b/src/constants/index.ts index 75385353b7..f3720bdf37 100644 --- a/src/constants/index.ts +++ b/src/constants/index.ts @@ -302,6 +302,8 @@ export const RTK_QUERY_TAGS = { // limit order GET_LIST_ORDERS: 'GET_LIST_ORDERS', + + GET_FARM_V2: 'GET_FARM_V2', } export const TRANSACTION_STATE_DEFAULT: TransactionFlowState = { diff --git a/src/hooks/pool/classic/index.ts b/src/hooks/pool/classic/index.ts new file mode 100644 index 0000000000..39576a83cf --- /dev/null +++ b/src/hooks/pool/classic/index.ts @@ -0,0 +1,19 @@ +import { useKyberSwapConfig } from 'state/application/hooks' +import { useGetClassicPoolsSubgraph } from 'state/pools/hooks' + +import { CommonReturn } from './type' +import useGetClassicPoolsKN from './useGetClassicPoolsKN' + +const useGetClassicPools = (): CommonReturn => { + const { isEnableKNProtocol } = useKyberSwapConfig() + const responseSubgraph = useGetClassicPoolsSubgraph() + const responseKN = useGetClassicPoolsKN() + + if (isEnableKNProtocol) { + return responseKN + } + + return responseSubgraph +} + +export default useGetClassicPools diff --git a/src/hooks/pool/classic/type.ts b/src/hooks/pool/classic/type.ts new file mode 100644 index 0000000000..b156d4845b --- /dev/null +++ b/src/hooks/pool/classic/type.ts @@ -0,0 +1,27 @@ +import { Token } from '@kyberswap/ks-sdk-core' + +export interface ClassicPoolData { + id: string + amp: string + fee: number + reserve0: string + reserve1: string + vReserve0: string + vReserve1: string + totalSupply: string + reserveUSD: string + volumeUSD: string + feeUSD: string + oneDayVolumeUSD: string + oneDayVolumeUntracked: string + oneDayFeeUSD: string + oneDayFeeUntracked: string + token0: Token + token1: Token +} + +export type CommonReturn = { + loading: boolean + error: Error | undefined + data: ClassicPoolData[] +} diff --git a/src/hooks/pool/classic/useGetClassicPoolsKN.ts b/src/hooks/pool/classic/useGetClassicPoolsKN.ts new file mode 100644 index 0000000000..40c5082a08 --- /dev/null +++ b/src/hooks/pool/classic/useGetClassicPoolsKN.ts @@ -0,0 +1,72 @@ +import { Token, WETH } from '@kyberswap/ks-sdk-core' +import { useMemo } from 'react' +import { useGetPoolClassicQuery } from 'services/knprotocol' + +import { ZERO_ADDRESS } from 'constants/index' +import { useActiveWeb3React } from 'hooks' +import { useKyberSwapConfig } from 'state/application/hooks' +import { get24hValue } from 'utils' +import { toString } from 'utils/numbers' + +import { ClassicPoolData, CommonReturn } from './type' + +const useGetClassicPoolsKN = (): CommonReturn => { + const { chainId } = useActiveWeb3React() + const { isEnableKNProtocol } = useKyberSwapConfig() + + const { currentData, error, isFetching } = useGetPoolClassicQuery(chainId, { skip: !isEnableKNProtocol }) + const poolData: ClassicPoolData[] | undefined = useMemo( + () => + currentData?.data?.pools.map(pool => { + const oneDayVolumeUSD = toString(get24hValue(pool.volumeUsd, pool.volumeUsdOneDayAgo)) + const oneDayFeeUSD = toString(get24hValue(pool.feeUSD, pool.feesUsdOneDayAgo)) + + return { + id: pool.id, + amp: pool.amp, + fee: Number(pool.fee), + reserve0: pool.reserve0, + reserve1: pool.reserve1, + vReserve0: pool.vReserve0, + vReserve1: pool.vReserve1, + + totalSupply: pool.totalSupply, + reserveUSD: pool.reserveUSD, + volumeUSD: pool.volumeUsd, + feeUSD: pool.feeUSD, + oneDayVolumeUSD, + oneDayVolumeUntracked: '0', + oneDayFeeUSD, + oneDayFeeUntracked: '0', + + token0: + pool.token0.id === ZERO_ADDRESS + ? WETH[chainId] + : new Token(chainId, pool.token0.id, Number(pool.token0.decimals), pool.token0.symbol, pool.token0.name), + token1: + pool.token1.id === ZERO_ADDRESS + ? WETH[chainId] + : new Token(chainId, pool.token1.id, Number(pool.token1.decimals), pool.token1.symbol, pool.token1.name), + } + }) ?? [], + [currentData?.data?.pools, chainId], + ) + const fetchError = useMemo( + () => + //https://redux-toolkit.js.org/rtk-query/usage-with-typescript#error-result-example + error + ? 'status' in error + ? new Error('error' in error ? error.error : JSON.stringify(error.data)) + : new Error(error.message) + : undefined, + [error], + ) + + return { + loading: isFetching, + error: fetchError, + data: poolData, + } +} + +export default useGetClassicPoolsKN diff --git a/src/hooks/useContract.ts b/src/hooks/useContract.ts index 81aafdbc92..02d1f6653f 100644 --- a/src/hooks/useContract.ts +++ b/src/hooks/useContract.ts @@ -215,7 +215,7 @@ export function useProMMFarmContract(address: string): Contract | null { return useContract(address, PROMM_FARM_ABI) } -function useFairLaunchV1Contracts(withSignerIfPossible?: boolean): { +function useFairLaunchV1Contracts(): { [key: string]: Contract } | null { const { isEVM, networkInfo } = useActiveWeb3React() @@ -223,11 +223,11 @@ function useFairLaunchV1Contracts(withSignerIfPossible?: boolean): { return useMultipleContracts( isEVM ? (networkInfo as EVMNetworkInfo).classic.fairlaunch : undefined, FAIRLAUNCH_ABI, - withSignerIfPossible, + false, ) } -function useFairLaunchV2Contracts(withSignerIfPossible?: boolean): { +function useFairLaunchV2Contracts(): { [key: string]: Contract } | null { const { networkInfo, isEVM } = useActiveWeb3React() @@ -235,11 +235,11 @@ function useFairLaunchV2Contracts(withSignerIfPossible?: boolean): { return useMultipleContracts( isEVM ? (networkInfo as EVMNetworkInfo).classic.fairlaunchV2 : undefined, FAIRLAUNCH_V2_ABI, - withSignerIfPossible, + false, ) } -function useFairLaunchV3Contracts(withSignerIfPossible?: boolean): { +function useFairLaunchV3Contracts(): { [key: string]: Contract } | null { const { networkInfo, isEVM } = useActiveWeb3React() @@ -249,16 +249,16 @@ function useFairLaunchV3Contracts(withSignerIfPossible?: boolean): { ? (networkInfo as EVMNetworkInfo).classic.fairlaunchV3 : undefined, FAIRLAUNCH_V3_ABI, - withSignerIfPossible, + false, ) } -export function useFairLaunchContracts(withSignerIfPossible?: boolean): { +export function useFairLaunchContracts(): { [key: string]: Contract } | null { - const fairLaunchV1Contracts = useFairLaunchV1Contracts(withSignerIfPossible) - const fairLaunchV2Contracts = useFairLaunchV2Contracts(withSignerIfPossible) - const fairLaunchV3Contracts = useFairLaunchV3Contracts(withSignerIfPossible) + const fairLaunchV1Contracts = useFairLaunchV1Contracts() + const fairLaunchV2Contracts = useFairLaunchV2Contracts() + const fairLaunchV3Contracts = useFairLaunchV3Contracts() const fairLaunchContracts = useMemo(() => { return { ...fairLaunchV1Contracts, ...fairLaunchV2Contracts, ...fairLaunchV3Contracts } diff --git a/src/hooks/useFairLaunch.ts b/src/hooks/useFairLaunch.ts index 5cd866f6f2..47ea6ddf18 100644 --- a/src/hooks/useFairLaunch.ts +++ b/src/hooks/useFairLaunch.ts @@ -12,8 +12,8 @@ import { getFullDisplayBalance } from 'utils/formatBalance' const getTransactionExtraInfo = (farm: Farm | null, farmRewards: Reward[]): TransactionExtraInfoHarvestFarm => { return { contract: farm?.id, - tokenAddressIn: farm?.token0?.id, - tokenAddressOut: farm?.token1?.id, + tokenAddressIn: farm?.token0?.address, + tokenAddressOut: farm?.token1?.address, tokenSymbolIn: farm?.token0?.symbol, tokenSymbolOut: farm?.token1?.symbol, rewards: farmRewards diff --git a/src/pages/AddLiquidity/TokenPair.tsx b/src/pages/AddLiquidity/TokenPair.tsx index 17d934722c..53a92fb7cc 100644 --- a/src/pages/AddLiquidity/TokenPair.tsx +++ b/src/pages/AddLiquidity/TokenPair.tsx @@ -34,7 +34,7 @@ import { ApprovalState, useApproveCallback } from 'hooks/useApproveCallback' import useTheme from 'hooks/useTheme' import useTransactionDeadline from 'hooks/useTransactionDeadline' import DisclaimerERC20 from 'pages/AddLiquidityV2/components/DisclaimerERC20' -import { Dots, Wrapper } from 'pages/Pool/styleds' +import { Dots, Wrapper } from 'pages/MyPool/styleds' import { useWalletModalToggle } from 'state/application/hooks' import { Field } from 'state/mint/actions' import { useDerivedMintInfo, useMintActionHandlers, useMintState } from 'state/mint/hooks' diff --git a/src/pages/AddLiquidity/ZapIn.tsx b/src/pages/AddLiquidity/ZapIn.tsx index 25db3f3be8..a0da12406a 100644 --- a/src/pages/AddLiquidity/ZapIn.tsx +++ b/src/pages/AddLiquidity/ZapIn.tsx @@ -35,7 +35,7 @@ import { useCurrency } from 'hooks/Tokens' import { ApprovalState, useApproveCallback } from 'hooks/useApproveCallback' import useTheme from 'hooks/useTheme' import useTransactionDeadline from 'hooks/useTransactionDeadline' -import { Dots, Wrapper } from 'pages/Pool/styleds' +import { Dots, Wrapper } from 'pages/MyPool/styleds' import { useWalletModalToggle } from 'state/application/hooks' import { Field } from 'state/mint/actions' import { useDerivedZapInInfo, useMintState, useZapInActionHandlers } from 'state/mint/hooks' diff --git a/src/pages/AddLiquidityV2/index.tsx b/src/pages/AddLiquidityV2/index.tsx index b959f9bf0a..d3aeb052ca 100644 --- a/src/pages/AddLiquidityV2/index.tsx +++ b/src/pages/AddLiquidityV2/index.tsx @@ -87,7 +87,7 @@ import { basisPointsToPercent, calculateGasMargin, formattedNum } from 'utils' import { currencyId } from 'utils/currencyId' import { friendlyError } from 'utils/errorMessage' import { maxAmountSpend } from 'utils/maxAmountSpend' -import { formatDisplayNumber, toFixed } from 'utils/numbers' +import { formatDisplayNumber, toString } from 'utils/numbers' import { SLIPPAGE_STATUS, checkRangeSlippage } from 'utils/slippage' import { unwrappedToken } from 'utils/wrappedCurrency' @@ -631,7 +631,7 @@ export default function AddLiquidity() { useEffect(() => { if (waitForMarketPrice && marketPrice) { - onStartPriceInput(toFixed(marketPrice)) + onStartPriceInput(toString(marketPrice)) setWaitForMarketPrice(false) } }, [waitForMarketPrice, marketPrice, onStartPriceInput]) diff --git a/src/pages/App.tsx b/src/pages/App.tsx index 7395ba1e70..7436172284 100644 --- a/src/pages/App.tsx +++ b/src/pages/App.tsx @@ -52,7 +52,7 @@ const SwapV2 = lazy(() => import('./SwapV2')) const SwapV3 = lazy(() => import('./SwapV3')) // const Bridge = lazy(() => import('./Bridge')) const Pools = lazy(() => import('./Pools')) -const MyPools = lazy(() => import('./Pool')) +const MyPool = lazy(() => import('./MyPool')) const MyEarnings = lazy(() => import('./MyEarnings')) const Farm = lazy(() => import('./Farm')) @@ -346,7 +346,7 @@ export default function App() { <> {/* My Pools Routes */} } /> - } /> + } /> <> diff --git a/src/pages/Bridge/helpers.ts b/src/pages/Bridge/helpers.ts index d25b756b84..2b82bac305 100644 --- a/src/pages/Bridge/helpers.ts +++ b/src/pages/Bridge/helpers.ts @@ -166,7 +166,7 @@ export const formatPoolValue = (amount: PoolBridgeValue) => { 123456789012.123456 => 123.457B 1234567890123.123456 => 1.23457T */ -// todo: deprecated, use formatDisplayNumber instead +/** @deprecated use formatDisplayNumber instead */ export const formatAmountBridge = (rawAmount: string) => { const amount = parseFloat(String(rawAmount) ?? '0') if (amount > 100_000_000) { diff --git a/src/pages/Campaign/CampaignButtonWithOptions.tsx b/src/pages/Campaign/CampaignButtonWithOptions.tsx index e5c310f737..71fa5e655c 100644 --- a/src/pages/Campaign/CampaignButtonWithOptions.tsx +++ b/src/pages/Campaign/CampaignButtonWithOptions.tsx @@ -20,7 +20,7 @@ import useMixpanel, { MIXPANEL_TYPE } from 'hooks/useMixpanel' import { useOnClickOutside } from 'hooks/useOnClickOutside' import useTheme from 'hooks/useTheme' import { useChangeNetwork } from 'hooks/web3/useChangeNetwork' -import { Dots } from 'pages/Pool/styleds' +import { Dots } from 'pages/MyPool/styleds' import { AppState } from 'state' import { CampaignData, diff --git a/src/pages/CreatePool/index.tsx b/src/pages/CreatePool/index.tsx index 98ded952d9..c5696b7ddc 100644 --- a/src/pages/CreatePool/index.tsx +++ b/src/pages/CreatePool/index.tsx @@ -34,7 +34,7 @@ import useMixpanel, { MIXPANEL_TYPE } from 'hooks/useMixpanel' import useTheme from 'hooks/useTheme' import useTransactionDeadline from 'hooks/useTransactionDeadline' import DisclaimerERC20 from 'pages/AddLiquidityV2/components/DisclaimerERC20' -import { Dots, Wrapper } from 'pages/Pool/styleds' +import { Dots, Wrapper } from 'pages/MyPool/styleds' import { useWalletModalToggle } from 'state/application/hooks' import { Field } from 'state/mint/actions' import { useDerivedMintInfo, useMintActionHandlers, useMintState } from 'state/mint/hooks' diff --git a/src/pages/Farm/ElasticFarmv2/index.tsx b/src/pages/Farm/ElasticFarmv2/index.tsx index 908871de0f..e828270281 100644 --- a/src/pages/Farm/ElasticFarmv2/index.tsx +++ b/src/pages/Farm/ElasticFarmv2/index.tsx @@ -23,7 +23,7 @@ import { SORT_DIRECTION } from 'constants/index' import { useActiveWeb3React } from 'hooks' import { useProAmmNFTPositionManagerContract } from 'hooks/useContract' import useTheme from 'hooks/useTheme' -import { Dots } from 'pages/Pool/styleds' +import { Dots } from 'pages/MyPool/styleds' import { useWalletModalToggle } from 'state/application/hooks' import { SORT_FIELD, useFarmV2Action, useFilteredFarmsV2 } from 'state/farms/elasticv2/hooks' import { ElasticFarmV2 } from 'state/farms/elasticv2/types' diff --git a/src/pages/Farm/index.tsx b/src/pages/Farm/index.tsx index c0db8094e3..c7ada89c46 100644 --- a/src/pages/Farm/index.tsx +++ b/src/pages/Farm/index.tsx @@ -47,6 +47,7 @@ import { AppState } from 'state' import { ApplicationModal } from 'state/application/actions' import { useBlockNumber, useOpenModal } from 'state/application/hooks' import { useFarmsData } from 'state/farms/classic/hooks' +import { FairLaunchVersion } from 'state/farms/classic/types' import ClassicFarmUpdater from 'state/farms/classic/updater' import { FarmUpdater, useElasticFarms } from 'state/farms/elastic/hooks' import { useElasticFarmsV2 } from 'state/farms/elasticv2/hooks' @@ -130,8 +131,9 @@ const Farm = () => { .flat() .filter( item => - (item.endTime && item.endTime > currentTimestamp) || - (blockNumber && item.endBlock && item.endBlock > blockNumber), + ((item.version === FairLaunchVersion.V2 || item.version === FairLaunchVersion.V3) && + item.endTime > currentTimestamp) || + (blockNumber && item.version === FairLaunchVersion.V1 && item.endBlock > blockNumber), ) .forEach(current => { current.rewardTokens?.forEach(token => { diff --git a/src/pages/MyEarnings/PoolEarningsSection.tsx b/src/pages/MyEarnings/PoolEarningsSection.tsx index c2f1d3d60e..b6cedb52da 100644 --- a/src/pages/MyEarnings/PoolEarningsSection.tsx +++ b/src/pages/MyEarnings/PoolEarningsSection.tsx @@ -16,7 +16,7 @@ import { WrappedTokenInfo } from 'state/lists/wrappedTokenInfo' import { MEDIA_WIDTHS } from 'theme' import { EarningStatsTick, EarningsBreakdown } from 'types/myEarnings' import { isAddressString } from 'utils' -import { toFixed } from 'utils/numbers' +import { toString } from 'utils/numbers' import OriginalEarningsBreakdownPanel from './EarningsBreakdownPanel' import OriginalMyEarningsOverTimePanel from './MyEarningsOverTimePanel' @@ -151,19 +151,19 @@ const PoolEarningsSection: React.FC = ({ historicalEarning, chainId }) => ? latestData.map(data => ({ logoUrl: data.logoUrl, symbol: data.symbol, - value: toFixed(data.amountUSD), + value: toString(data.amountUSD), percent: isAllZero ? (1 / visibleItems) * 100 : (data.amountUSD / totalValue) * 100, })) : [ ...latestData.slice(0, 9).map(data => ({ logoUrl: data.logoUrl, symbol: data.symbol, - value: toFixed(data.amountUSD), + value: toString(data.amountUSD), percent: isAllZero ? 10 : (data.amountUSD / totalValue) * 100, })), { symbol: t`Others`, - value: toFixed(totalValueOfOthers), + value: toString(totalValueOfOthers), percent: isAllZero ? 10 : (totalValueOfOthers / totalValue) * 100, }, ] diff --git a/src/pages/Pool/index.tsx b/src/pages/MyPool/index.tsx similarity index 96% rename from src/pages/Pool/index.tsx rename to src/pages/MyPool/index.tsx index 0940d3757d..ad0582548d 100644 --- a/src/pages/Pool/index.tsx +++ b/src/pages/MyPool/index.tsx @@ -26,7 +26,6 @@ import { APP_PATHS, DMM_ANALYTICS_URL } from 'constants/index' import { VERSION } from 'constants/v2' import { usePairByAddress, usePairsByAddress } from 'data/Reserves' import { useActiveWeb3React } from 'hooks' -import { useToken } from 'hooks/Tokens' import useDebounce from 'hooks/useDebounce' import useMixpanel, { MIXPANEL_TYPE } from 'hooks/useMixpanel' import useParsedQueryString from 'hooks/useParsedQueryString' @@ -179,7 +178,7 @@ export default function PoolCombination() { ) : tab === VERSION.ELASTIC_LEGACY ? ( ) : ( - + )} @@ -187,7 +186,7 @@ export default function PoolCombination() { ) } -function Pool() { +function MyPoolClassic() { const theme = useTheme() const { account, chainId, isEVM, networkInfo } = useActiveWeb3React() @@ -456,8 +455,8 @@ function Pool() { {userFarms .filter( farm => - farm.token0.symbol.toLowerCase().includes(debouncedSearchText) || - farm.token1.symbol.toLowerCase().includes(debouncedSearchText) || + farm.token0.symbol?.toLowerCase().includes(debouncedSearchText) || + farm.token1.symbol?.toLowerCase().includes(debouncedSearchText) || farm.id.toLowerCase() === debouncedSearchText, ) .map(farm => ( @@ -502,8 +501,8 @@ function Pool() { {userFarms .filter( farm => - farm.token0.symbol.toLowerCase().includes(debouncedSearchText) || - farm.token1.symbol.toLowerCase().includes(debouncedSearchText) || + farm.token0.symbol?.toLowerCase().includes(debouncedSearchText) || + farm.token1.symbol?.toLowerCase().includes(debouncedSearchText) || farm.id.toLowerCase() === debouncedSearchText, ) .map(farm => ( @@ -550,11 +549,9 @@ const StakedPool = ({ tab: 'ALL' | 'STAKED' userLiquidityPositions?: UserLiquidityPosition[] }) => { - const token0 = useToken(farm.token0?.id) || undefined - const token1 = useToken(farm.token1?.id) || undefined const { farmAPR } = useTotalApr(farm) - const pair = usePairByAddress(token0?.wrapped, token1?.wrapped, farm.id)[1] + const pair = usePairByAddress(farm.token0?.wrapped, farm.token1?.wrapped, farm.id)[1] if (!pair) return diff --git a/src/pages/Pool/styleds.tsx b/src/pages/MyPool/styleds.tsx similarity index 100% rename from src/pages/Pool/styleds.tsx rename to src/pages/MyPool/styleds.tsx diff --git a/src/pages/PoolFinder/index.tsx b/src/pages/PoolFinder/index.tsx index 5344c71515..f90b0dc9f1 100644 --- a/src/pages/PoolFinder/index.tsx +++ b/src/pages/PoolFinder/index.tsx @@ -21,7 +21,7 @@ import { PairState, usePair } from 'data/Reserves' import { useActiveWeb3React } from 'hooks' import useMixpanel, { MIXPANEL_TYPE } from 'hooks/useMixpanel' import AppBody from 'pages/AppBody' -import { Dots } from 'pages/Pool/styleds' +import { Dots } from 'pages/MyPool/styleds' import { usePairAdderByTokens } from 'state/user/hooks' import { useTokenBalances } from 'state/wallet/hooks' import { StyledInternalLink } from 'theme' diff --git a/src/pages/Pools/FarmingPoolsMarquee.tsx b/src/pages/Pools/FarmingPoolsMarquee.tsx index b8eea90843..2b70aaad0e 100644 --- a/src/pages/Pools/FarmingPoolsMarquee.tsx +++ b/src/pages/Pools/FarmingPoolsMarquee.tsx @@ -109,8 +109,8 @@ const FarmingPoolsMarquee = ({ tab }: { tab: string }) => { ? uniqueAndActiveFarms.map(farm => ( )) : activePrommFarm.map(farm => ( diff --git a/src/pages/ProAmmPool/index.tsx b/src/pages/ProAmmPool/index.tsx index 71fbbf19eb..820a286d7d 100644 --- a/src/pages/ProAmmPool/index.tsx +++ b/src/pages/ProAmmPool/index.tsx @@ -24,7 +24,7 @@ import { MIXPANEL_TYPE } from 'hooks/useMixpanel' import useParsedQueryString from 'hooks/useParsedQueryString' import { useFarmPositions, useProAmmPositions } from 'hooks/useProAmmPositions' import useTheme from 'hooks/useTheme' -import { FilterRow, InstructionText, PageWrapper, PositionCardGrid, Tab } from 'pages/Pool' +import { FilterRow, InstructionText, PageWrapper, PositionCardGrid, Tab } from 'pages/MyPool' import { FarmUpdater } from 'state/farms/elastic/hooks' import { useElasticFarmsV2 } from 'state/farms/elasticv2/hooks' import ElasticFarmV2Updater from 'state/farms/elasticv2/updater' diff --git a/src/pages/RemoveLiquidity/TokenPair.tsx b/src/pages/RemoveLiquidity/TokenPair.tsx index f622f9924c..2334b85e70 100644 --- a/src/pages/RemoveLiquidity/TokenPair.tsx +++ b/src/pages/RemoveLiquidity/TokenPair.tsx @@ -35,7 +35,7 @@ import { usePairContract } from 'hooks/useContract' import useIsArgentWallet from 'hooks/useIsArgentWallet' import useTheme from 'hooks/useTheme' import useTransactionDeadline from 'hooks/useTransactionDeadline' -import { Wrapper } from 'pages/Pool/styleds' +import { Wrapper } from 'pages/MyPool/styleds' import { useWalletModalToggle } from 'state/application/hooks' import { Field } from 'state/burn/actions' import { useBurnActionHandlers, useBurnState, useDerivedBurnInfo } from 'state/burn/hooks' diff --git a/src/pages/RemoveLiquidity/ZapOut.tsx b/src/pages/RemoveLiquidity/ZapOut.tsx index ec772c21af..3185c5a04f 100644 --- a/src/pages/RemoveLiquidity/ZapOut.tsx +++ b/src/pages/RemoveLiquidity/ZapOut.tsx @@ -46,7 +46,7 @@ import { usePairContract } from 'hooks/useContract' import useIsArgentWallet from 'hooks/useIsArgentWallet' import useTheme from 'hooks/useTheme' import useTransactionDeadline from 'hooks/useTransactionDeadline' -import { Wrapper } from 'pages/Pool/styleds' +import { Wrapper } from 'pages/MyPool/styleds' import { useWalletModalToggle } from 'state/application/hooks' import { Field } from 'state/burn/actions' import { useBurnState, useDerivedZapOutInfo, useZapOutActionHandlers } from 'state/burn/hooks' diff --git a/src/services/knprotocol.ts b/src/services/knprotocol.ts index fe1d7c0ee7..c64c9ad1a1 100644 --- a/src/services/knprotocol.ts +++ b/src/services/knprotocol.ts @@ -2,13 +2,90 @@ import { ChainId } from '@kyberswap/ks-sdk-core' import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' import { POOL_FARM_BASE_URL } from 'constants/env' -import { NETWORKS_INFO } from 'constants/networks' +import { RTK_QUERY_TAGS } from 'constants/index' +import { EVM_NETWORK, NETWORKS_INFO } from 'constants/networks' import { EVMNetworkInfo } from 'constants/networks/type' import { SubgraphFarmV2 } from 'state/farms/elasticv2/types' +type Token = { + id: string + symbol: string + name: string + decimals: string + priceUSD: string +} + +export type ClassicPoolKN = { + id: string + fee: string + feeUSD: string + feesUsdOneDayAgo: string + feesUsdTwoDaysAgo: string + feeUSD0: string + feeUSD1: string + feeAmount0: string + feeAmount1: string + token0: Token + token1: Token + reserve0: string + reserve1: string + vReserve0: string + vReserve1: string + totalSupply: string + pair: string + reserveUSD: string + volumeUsd: string + volumeUsdOneDayAgo: string + volumeUsdTwoDaysAgo: string + amp: string + apr: string + farmApr: string +} + +export type ClassicFarmKN = { + id: string + pid: string + start: string + end: string + rewardTokensIds: string[] + pool: { + id: string + feeUSD: string + feesUsdOneDayAgo: string + feesUsdTwoDaysAgo: string + feeUSD0: string + feeUSD1: string + feeAmount0: string + feeAmount1: string + token0: Token + token1: Token + reserve0: string + reserve1: string + vReserve0: string + vReserve1: string + totalSupply: string + pair: string + reserveUSD: string + volumeUsd: string + volumeUsdOneDayAgo: string + volumeUsdTwoDaysAgo: string + fee: string + amp: string + apr: string + farmApr: string + } + rewardTokens: Token[] + rewardPerUnits: number[] + stakedAmount: string + stakedTvl: string + apr: string + version: 1 | 2 | 3 +} + const knProtocolApi = createApi({ reducerPath: 'knProtocol', baseQuery: fetchBaseQuery({ baseUrl: POOL_FARM_BASE_URL }), + tagTypes: [RTK_QUERY_TAGS.GET_FARM_V2], endpoints: builder => ({ getFarmV2: builder.query<{ data: { data: SubgraphFarmV2[] } }, ChainId>({ query: (chainId: ChainId) => ({ @@ -16,9 +93,20 @@ const knProtocolApi = createApi({ (NETWORKS_INFO[chainId] as EVMNetworkInfo).poolFarmRoute }/api/v1/elastic-new/farm-v2?perPage=1000&page=1`, }), + providesTags: [RTK_QUERY_TAGS.GET_FARM_V2], + }), + getPoolClassic: builder.query<{ data: { pools: ClassicPoolKN[] } }, ChainId>({ + query: (chainId: EVM_NETWORK) => ({ + url: `/${NETWORKS_INFO[chainId].poolFarmRoute}/api/v1/classic/pools?includeLowTvl=true&perPage=10000&page=1`, + }), + }), + getFarmClassic: builder.query<{ data: { farmPools: ClassicFarmKN[] } }, ChainId>({ + query: (chainId: EVM_NETWORK) => ({ + url: `/${NETWORKS_INFO[chainId].poolFarmRoute}/api/v1/classic/farm-pools?perPage=1000&page=1`, + }), }), }), }) export default knProtocolApi -export const { useLazyGetFarmV2Query } = knProtocolApi +export const { useLazyGetFarmV2Query, useLazyGetFarmClassicQuery, useGetPoolClassicQuery } = knProtocolApi diff --git a/src/state/about/hooks.ts b/src/state/about/hooks.ts index b0510086dc..024272f763 100644 --- a/src/state/about/hooks.ts +++ b/src/state/about/hooks.ts @@ -52,7 +52,6 @@ export function useGlobalData() { .toString() } const getResultByChainIds = async (chainIds: readonly ChainId[]) => { - // todo namgold: add aggregator API for solana const elasticChains = chainIds.filter(id => isEVM(id)).filter(id => !ELASTIC_NOT_SUPPORTED[id]) const elasticPromises = elasticChains.map(chain => diff --git a/src/state/application/hooks.ts b/src/state/application/hooks.ts index 1572fc41fe..5063fd4508 100644 --- a/src/state/application/hooks.ts +++ b/src/state/application/hooks.ts @@ -314,6 +314,7 @@ const getPrommEthPrice = async ( return [ethPrice, ethPriceOneDay, priceChangeETH] } +// todo: should fetch from price service export function useETHPrice(version: string = VERSION.CLASSIC): AppState['application']['ethPrice'] { const dispatch = useDispatch() const { isEVM, chainId } = useActiveWeb3React() @@ -324,7 +325,6 @@ export function useETHPrice(version: string = VERSION.CLASSIC): AppState['applic ) useEffect(() => { - const controller = new AbortController() if (!isEVM) return async function checkForEthPrice() { @@ -351,9 +351,6 @@ export function useETHPrice(version: string = VERSION.CLASSIC): AppState['applic } } checkForEthPrice() - return () => { - controller.abort() - } }, [dispatch, chainId, version, isEVM, elasticClient, classicClient, blockClient, isEnableBlockService]) return ethPrice diff --git a/src/state/farms/classic/hooks.ts b/src/state/farms/classic/hooks.ts index 977bf2bd4d..ffcb9939b0 100644 --- a/src/state/farms/classic/hooks.ts +++ b/src/state/farms/classic/hooks.ts @@ -100,10 +100,7 @@ export const useTotalApr = (farm: Farm) => { const poolAddressChecksum = isAddressString(chainId, farm.id) const { decimals: lpTokenDecimals } = useTokenBalance(poolAddressChecksum) // Ratio in % of LP tokens that are staked in the MC, vs the total number in circulation - const lpTokenRatio = new Fraction( - farm.totalStake.toString(), - JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(lpTokenDecimals)), - ).divide( + const lpTokenRatio = farm.totalStake.divide( new Fraction( ethers.utils.parseUnits(farm.totalSupply, lpTokenDecimals).toString(), JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(lpTokenDecimals)), diff --git a/src/state/farms/classic/knUpdater.tsx b/src/state/farms/classic/knUpdater.tsx new file mode 100644 index 0000000000..9f2addd25d --- /dev/null +++ b/src/state/farms/classic/knUpdater.tsx @@ -0,0 +1,223 @@ +import { BigNumber } from '@ethersproject/bignumber' +import { Token, WETH } from '@kyberswap/ks-sdk-core' +import { parseUnits } from 'ethers/lib/utils' +import { useEffect } from 'react' +import { ClassicFarmKN, useLazyGetFarmClassicQuery } from 'services/knprotocol' + +import FAIRLAUNCH_V2_ABI from 'constants/abis/fairlaunch-v2.json' +import FAIRLAUNCH_V3_ABI from 'constants/abis/fairlaunch-v3.json' +import FAIRLAUNCH_ABI from 'constants/abis/fairlaunch.json' +import { AbortedError, ZERO_ADDRESS } from 'constants/index' +import { isEVM } from 'constants/networks' +import { useActiveWeb3React } from 'hooks' +import { useKyberSwapConfig } from 'state/application/hooks' +import { setFarmsData, setLoading, setYieldPoolsError } from 'state/farms/classic/actions' +import { FairLaunchVersion, Farm, FarmV1, FarmV2 } from 'state/farms/classic/types' +import { useAppDispatch } from 'state/hooks' +import { getContractForReading } from 'utils/getContract' +import { parseFraction, toString } from 'utils/numbers' + +const KNUpdater = ({ isInterval = true }: { isInterval?: boolean }) => { + const dispatch = useAppDispatch() + const { chainId, account } = useActiveWeb3React() + const { isEnableKNProtocol, readProvider } = useKyberSwapConfig() + const [fetchFarmKN] = useLazyGetFarmClassicQuery() + + useEffect(() => { + const abortController = new AbortController() + + async function getListFarmsKN(): Promise { + try { + if (!isEVM(chainId)) return [] + const farmsKN: ClassicFarmKN[] | undefined = (await fetchFarmKN(chainId)).data?.data.farmPools + if (!farmsKN) return [] + + const mapping = await Promise.all( + farmsKN.map(async farmPool => { + const [fairLaunchAddress] = farmPool.id.split('_') + const pid = Number(farmPool.pid) + const id = farmPool.pool.id + // const version = + // farmPool.version === 1 + // ? FairLaunchVersion.V1 + // : farmPool.version === 2 + // ? FairLaunchVersion.V2 + // : FairLaunchVersion.V3 + // todo namgold: subgraph issue, revert this later + const version: FairLaunchVersion = + Number(farmPool.start) < 1_000_000_000 ? FairLaunchVersion.V1 : FairLaunchVersion.V2 + const rewardTokens: Token[] = farmPool.rewardTokens.map(({ id, decimals, symbol, name }) => + id === ZERO_ADDRESS ? WETH[chainId] : new Token(chainId, id, Number(decimals), symbol, name), + ) + const totalStake = parseFraction(farmPool.stakedAmount).divide(10 ** 18) + const stakeToken = id + const token0: Token = + farmPool.pool.token0.id === ZERO_ADDRESS + ? WETH[chainId] + : new Token( + chainId, + farmPool.pool.token0.id, + Number(farmPool.pool.token0.decimals), + farmPool.pool.token0.symbol, + farmPool.pool.token0.name, + ) + const token1: Token = + farmPool.pool.token1.id === ZERO_ADDRESS + ? WETH[chainId] + : new Token( + chainId, + farmPool.pool.token1.id, + Number(farmPool.pool.token1.decimals), + farmPool.pool.token1.symbol, + farmPool.pool.token1.name, + ) + const amp = Number(farmPool.pool.amp) + const reserve0 = farmPool.pool.reserve0 + const reserve1 = farmPool.pool.reserve1 + const reserveUSD = farmPool.pool.reserveUSD + const totalSupply = farmPool.pool.totalSupply + const oneDayFeeUSD = parseFraction(farmPool.pool.feeUSD) + .subtract(parseFraction(farmPool.pool.feesUsdOneDayAgo)) + .toFixed(18) + const oneDayFeeUntracked = '0' + const rewardPerUnits: BigNumber[] = farmPool.rewardPerUnits.map(i => parseUnits(toString(i), 0)) + const start = Number(farmPool.start) + const end = Number(farmPool.end) + + const userData = await (async () => { + if (!account) return {} + if (!readProvider) return {} + try { + const contract = getContractForReading( + fairLaunchAddress, + version === FairLaunchVersion.V1 + ? FAIRLAUNCH_ABI + : version === FairLaunchVersion.V2 + ? FAIRLAUNCH_V2_ABI + : FAIRLAUNCH_V3_ABI, + readProvider, + ) + + const stakedBalance = (await contract.getUserInfo(pid, account)).amount + if (abortController.signal.aborted) throw new AbortedError() + const pendingRewards: BigNumber[] = await contract.pendingRewards(pid, account) + if (abortController.signal.aborted) throw new AbortedError() + + const userData = { + stakedBalance, + rewards: + version === FairLaunchVersion.V1 + ? pendingRewards + : pendingRewards.map((pendingReward, index) => + pendingReward.div(10 ** (18 - rewardTokens[index].decimals)), + ), + } + return userData + } catch (e) { + if (!abortController.signal.aborted) { + console.error('fetch userData error', e) + } + return {} + } + })() + + if (version === FairLaunchVersion.V1) { + return { + fairLaunchAddress, + version, + pid, + id, + rewardTokens, + rewardPerBlocks: rewardPerUnits, + totalStake, + stakeToken, + startBlock: start, + endBlock: end, + token0, + token1, + amp, + reserve0, + reserve1, + reserveUSD, + totalSupply, + oneDayFeeUSD, + oneDayFeeUntracked, + userData, + } as FarmV1 + } + + return { + fairLaunchAddress, + version, + pid, + id, + rewardTokens, + rewardPerSeconds: rewardPerUnits, + totalStake, + stakeToken, + startTime: start, + endTime: end, + token0, + token1, + amp, + reserve0, + reserve1, + reserveUSD, + totalSupply, + oneDayFeeUSD, + oneDayFeeUntracked, + userData, + } as FarmV2 + }), + ) + return mapping + } catch (error) { + if (!abortController.signal.aborted) { + console.error('parse kn error', { error }) + } + throw error + } + } + + async function checkForFarms() { + try { + dispatch(setLoading(true)) + + const farms: Farm[] = await getListFarmsKN() + if (abortController.signal.aborted) throw new AbortedError() + const data = farms.reduce((acc, cur) => { + const id = cur.fairLaunchAddress + if (!acc[id]) acc[id] = [] + acc[id].push(cur) + return acc + }, {} as { [key: string]: Farm[] }) + + dispatch(setFarmsData(data)) + } catch (err) { + if (!abortController.signal.aborted) { + console.error('fetch farmData KN error', { error: err }) + dispatch(setYieldPoolsError(err as Error)) + } + } finally { + dispatch(setLoading(false)) + } + } + + dispatch(setFarmsData({})) + checkForFarms() + + const i = + isInterval && + setInterval(() => { + checkForFarms() + }, 30_000) + + return () => { + abortController.abort() + i && clearInterval(i) + } + }, [fetchFarmKN, dispatch, chainId, account, isEnableKNProtocol, isInterval, readProvider]) + + return null +} +export default KNUpdater diff --git a/src/state/farms/classic/updater.ts b/src/state/farms/classic/rpcUpdater.tsx similarity index 85% rename from src/state/farms/classic/updater.ts rename to src/state/farms/classic/rpcUpdater.tsx index 9c64385b45..1d00c4858c 100644 --- a/src/state/farms/classic/updater.ts +++ b/src/state/farms/classic/rpcUpdater.tsx @@ -1,5 +1,7 @@ import { BigNumber } from '@ethersproject/bignumber' import { Contract } from '@ethersproject/contracts' +import { Fraction, Token } from '@kyberswap/ks-sdk-core' +import JSBI from 'jsbi' import { useEffect, useRef } from 'react' import { useSelector } from 'react-redux' @@ -8,6 +10,7 @@ import { EVMNetworkInfo } from 'constants/networks/type' import { NativeCurrencies } from 'constants/tokens' import { useActiveWeb3React } from 'hooks' import { useAllTokens } from 'hooks/Tokens' +import { ClassicPoolData } from 'hooks/pool/classic/type' import { useFairLaunchContracts } from 'hooks/useContract' import { AppState } from 'state' import { useETHPrice, useKyberSwapConfig } from 'state/application/hooks' @@ -16,10 +19,10 @@ import { FairLaunchVersion, Farm } from 'state/farms/classic/types' import { useAppDispatch } from 'state/hooks' import { getBulkPoolDataFromPoolList } from 'state/pools/hooks' -export default function Updater({ isInterval = true }: { isInterval?: boolean }): null { +export default function RPCUpdater({ isInterval = true }: { isInterval?: boolean }): null { const dispatch = useAppDispatch() const { chainId, account, isEVM, networkInfo } = useActiveWeb3React() - const fairLaunchContracts = useFairLaunchContracts(false) + const fairLaunchContracts = useFairLaunchContracts() const ethPrice = useETHPrice() const ethPriceRef = useRef(ethPrice.currentPrice) ethPriceRef.current = ethPrice.currentPrice @@ -67,8 +70,9 @@ export default function Updater({ isInterval = true }: { isInterval?: boolean }) if (isV2 || isV3) { return { ...poolInfo, - accRewardPerShares: poolInfo.accRewardPerShares.map((accRewardPerShare: BigNumber, index: number) => - accRewardPerShare.div(isV3 ? poolInfo.multipliers[index] : poolInfo.rewardMultipliers[index]), + totalStake: new Fraction( + poolInfo.totalStake.toString(), + JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(18)), ), rewardPerSeconds: poolInfo.rewardPerSeconds.map((accRewardPerShare: BigNumber, index: number) => accRewardPerShare.div(isV3 ? poolInfo.multipliers[index] : poolInfo.rewardMultipliers[index]), @@ -80,7 +84,7 @@ export default function Updater({ isInterval = true }: { isInterval?: boolean }) ? poolInfo.rewardTokens.map((rw: string) => rw.toLowerCase() === ZERO_ADDRESS || rw.toLowerCase() === ETHER_ADDRESS.toLowerCase() ? NativeCurrencies[chainId] - : allTokens[rw], + : allTokens[rw] || new Token(chainId, rw, 18, 'unknown', 'unknown'), ) : rewardTokens) || [], } @@ -88,6 +92,10 @@ export default function Updater({ isInterval = true }: { isInterval?: boolean }) return { ...poolInfo, + totalStake: new Fraction( + poolInfo.totalStake.toString(), + JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(18)), + ), pid, fairLaunchVersion: FairLaunchVersion.V1, rewardTokens, @@ -117,7 +125,7 @@ export default function Updater({ isInterval = true }: { isInterval?: boolean }) const poolAddresses = poolInfos.map(poolInfo => poolInfo.stakeToken.toLowerCase()) - const farmsData = await getBulkPoolDataFromPoolList( + const poolsData: ClassicPoolData[] = await getBulkPoolDataFromPoolList( isEnableBlockService, poolAddresses, classicClient, @@ -129,17 +137,17 @@ export default function Updater({ isInterval = true }: { isInterval?: boolean }) const farms: Farm[] = poolInfos.map((poolInfo, index) => { return { - ...farmsData.find( - (farmData: Farm) => farmData && farmData.id.toLowerCase() === poolInfo.stakeToken.toLowerCase(), + ...poolsData.find( + (poolData: ClassicPoolData) => poolData && poolData.id.toLowerCase() === poolInfo.stakeToken.toLowerCase(), ), ...poolInfo, + version: isV2 ? FairLaunchVersion.V2 : isV3 ? FairLaunchVersion.V3 : FairLaunchVersion.V1, rewardTokens: poolInfo.rewardTokens, fairLaunchAddress: contract.address, userData: { stakedBalance: stakedBalances[index], rewards: [FairLaunchVersion.V2, FairLaunchVersion.V3].includes(poolInfo.fairLaunchVersion) - ? pendingRewards[index] && - pendingRewards[index].map((pendingReward: BigNumber, pendingRewardIndex: number) => + ? pendingRewards[index]?.map((pendingReward: BigNumber, pendingRewardIndex: number) => pendingReward.div( isV3 ? poolInfo.multipliers[pendingRewardIndex] : poolInfo.rewardMultipliers[pendingRewardIndex], ), @@ -174,9 +182,7 @@ export default function Updater({ isInterval = true }: { isInterval?: boolean }) result[address] = promiseResult[index] }) - if (latestChainId.current === chainId && Object.keys(farmsDataRef.current).length === 0) { - dispatch(setFarmsData(result)) - } + dispatch(setFarmsData(result)) } catch (err) { if (err instanceof AbortedError) return if (abortController.signal.aborted) return @@ -187,6 +193,7 @@ export default function Updater({ isInterval = true }: { isInterval?: boolean }) dispatch(setLoading(false)) } + dispatch(setFarmsData({})) checkForFarms() const i = diff --git a/src/state/farms/classic/types.ts b/src/state/farms/classic/types.ts index 37d465a793..e0e8245963 100644 --- a/src/state/farms/classic/types.ts +++ b/src/state/farms/classic/types.ts @@ -1,5 +1,5 @@ import { BigNumber } from '@ethersproject/bignumber' -import { Token } from '@kyberswap/ks-sdk-core' +import { Fraction, Token } from '@kyberswap/ks-sdk-core' export enum FairLaunchVersion { V1, @@ -12,21 +12,19 @@ export enum RewardLockerVersion { V2, } -interface FarmV1 { +export interface FarmV1 { fairLaunchAddress: string - version: FairLaunchVersion + version: FairLaunchVersion.V1 pid: number id: string rewardTokens: Token[] rewardPerBlocks: BigNumber[] - accRewardPerShares: BigNumber[] - totalStake: BigNumber + totalStake: Fraction stakeToken: string startBlock: number endBlock: number - lastRewardBlock: number - token0?: any - token1?: any + token0: Token + token1: Token amp: number reserve0: string reserve1: string @@ -35,30 +33,24 @@ interface FarmV1 { oneDayFeeUSD?: string oneDayFeeUntracked?: string userData?: { - allowance?: string - tokenBalance?: string stakedBalance?: string rewards?: string[] } - time: string } -interface FarmV2 { +export interface FarmV2 { fairLaunchAddress: string - version: FairLaunchVersion + version: FairLaunchVersion.V2 | FairLaunchVersion.V3 pid: number id: string rewardTokens: Token[] rewardPerSeconds: BigNumber[] - accRewardPerShares: BigNumber[] - totalStake: BigNumber + totalStake: Fraction stakeToken: string - generatedToken: string startTime: number endTime: number - lastRewardTime: number - token0?: any - token1?: any + token0: Token + token1: Token amp: number reserve0: string reserve1: string @@ -67,17 +59,12 @@ interface FarmV2 { oneDayFeeUSD?: string oneDayFeeUntracked?: string userData?: { - allowance?: string - tokenBalance?: string stakedBalance?: string rewards?: string[] } - time: string - vestingDuration: number - rewardMultipliers: BigNumber[] } -export interface Farm extends FarmV1, FarmV2 {} +export type Farm = FarmV1 | FarmV2 export interface Reward { token: Token diff --git a/src/state/farms/classic/updater.tsx b/src/state/farms/classic/updater.tsx new file mode 100644 index 0000000000..b77753e630 --- /dev/null +++ b/src/state/farms/classic/updater.tsx @@ -0,0 +1,8 @@ +import { useKyberSwapConfig } from 'state/application/hooks' +import KNUpdater from 'state/farms/classic/knUpdater' +import RPCUpdater from 'state/farms/classic/rpcUpdater' + +export default function Updater({ isInterval = true }: { isInterval?: boolean }) { + const { isEnableKNProtocol } = useKyberSwapConfig() + return isEnableKNProtocol ? : +} diff --git a/src/state/farms/elasticv2/updater.tsx b/src/state/farms/elasticv2/updater.tsx index f1ddbb20c6..ecf7c923f7 100644 --- a/src/state/farms/elasticv2/updater.tsx +++ b/src/state/farms/elasticv2/updater.tsx @@ -11,7 +11,7 @@ import knProtocolApi, { useLazyGetFarmV2Query } from 'services/knprotocol' import FarmV2QuoterABI from 'constants/abis/farmv2Quoter.json' import NFTPositionManagerABI from 'constants/abis/v2/ProAmmNFTPositionManager.json' -import { ETHER_ADDRESS, ZERO_ADDRESS } from 'constants/index' +import { ETHER_ADDRESS, RTK_QUERY_TAGS, ZERO_ADDRESS } from 'constants/index' import { EVMNetworkInfo } from 'constants/networks/type' import { NativeCurrencies } from 'constants/tokens' import { useActiveWeb3React } from 'hooks' @@ -147,7 +147,7 @@ export default function ElasticFarmV2Updater({ interval = true }: { interval?: b }) } } - Promise.resolve(dispatch(knProtocolApi.util.resetApiState())).then(() => { + Promise.resolve(dispatch(knProtocolApi.util.invalidateTags([RTK_QUERY_TAGS.GET_FARM_V2]))).then(() => { dispatch(setFarms({ chainId, farms: [] })) getFarm(chainId, true) }) diff --git a/src/state/pools/actions.ts b/src/state/pools/actions.ts index 2a3d786778..b2981ce8f1 100644 --- a/src/state/pools/actions.ts +++ b/src/state/pools/actions.ts @@ -1,12 +1,14 @@ import { createAction } from '@reduxjs/toolkit' -import { SubgraphPoolData, UserLiquidityPosition } from './hooks' +import { ClassicPoolData } from 'hooks/pool/classic/type' -export const updatePools = createAction<{ pools: SubgraphPoolData[] }>('pools/updatePools') +import { UserLiquidityPosition } from './hooks' + +export const updatePools = createAction<{ pools: ClassicPoolData[] }>('pools/updatePools') export const setLoading = createAction('pools/setLoading') export const setError = createAction('pools/setError') export const setSelectedPool = createAction<{ - poolData: SubgraphPoolData + poolData: ClassicPoolData myLiquidity?: UserLiquidityPosition }>('pools/setSelectedPool') export const setSharedPoolId = createAction<{ poolId: string | undefined }>('pools/setSharedPoolId') diff --git a/src/state/pools/hooks.ts b/src/state/pools/hooks.ts index 8f664b602b..a16d6afaab 100644 --- a/src/state/pools/hooks.ts +++ b/src/state/pools/hooks.ts @@ -1,5 +1,5 @@ import { ApolloClient, NormalizedCacheObject, useQuery } from '@apollo/client' -import { ChainId, WETH } from '@kyberswap/ks-sdk-core' +import { ChainId, Token, WETH } from '@kyberswap/ks-sdk-core' import { useCallback, useEffect, useMemo, useState } from 'react' import { useDispatch, useSelector } from 'react-redux' @@ -14,46 +14,13 @@ import { } from 'apollo/queries' import { ONLY_DYNAMIC_FEE_CHAINS } from 'constants/networks' import { useActiveWeb3React } from 'hooks' +import { ClassicPoolData, CommonReturn } from 'hooks/pool/classic/type' import { useETHPrice, useKyberSwapConfig } from 'state/application/hooks' import { AppState } from 'state/index' import { get24hValue, getBlocksFromTimestamps, getPercentChange, getTimestampsForChanges } from 'utils' import { setError, setLoading, setSharedPoolId, updatePools } from './actions' -export interface SubgraphPoolData { - id: string - amp: string - fee: number - reserve0: string - reserve1: string - vReserve0: string - vReserve1: string - totalSupply: string - reserveUSD: string - volumeUSD: string - feeUSD: string - oneDayVolumeUSD: string - oneDayVolumeUntracked: string - oneDayFeeUSD: string - oneDayFeeUntracked: string - token0: { - id: string - symbol: string - name: string - decimals: string - totalLiquidity: string - derivedETH: string - } - token1: { - id: string - symbol: string - name: string - decimals: string - totalLiquidity: string - derivedETH: string - } -} - export interface UserLiquidityPosition { id: string liquidityTokenBalance: string @@ -98,7 +65,7 @@ export function useUserLiquidityPositions(chainId?: ChainId): UserLiquidityPosit return useMemo(() => ({ loading, error, data }), [data, error, loading]) } -function parseData(data: any, oneDayData: any, ethPrice: any, oneDayBlock: any, chainId?: ChainId): SubgraphPoolData { +function parseData(data: any, oneDayData: any, ethPrice: any, oneDayBlock: any, chainId: ChainId): ClassicPoolData { // get volume changes const oneDayVolumeUSD = get24hValue(data?.volumeUSD, oneDayData?.volumeUSD) const oneDayFeeUSD = get24hValue(data?.feeUSD, oneDayData?.feeUSD) @@ -121,10 +88,10 @@ function parseData(data: any, oneDayData: any, ethPrice: any, oneDayBlock: any, else data.oneDayVolumeUSD = 0 } - if (chainId && WETH[chainId].address.toLowerCase() === data?.token0?.id) { + if (WETH[chainId].address.toLowerCase() === data?.token0?.id) { data.token0 = { ...data.token0, name: WETH[chainId].name, symbol: WETH[chainId].symbol } } - if (chainId && WETH[chainId].address.toLowerCase() === data?.token1?.id) { + if (WETH[chainId].address.toLowerCase() === data?.token1?.id) { data.token1 = { ...data.token1, name: WETH[chainId].name, symbol: WETH[chainId].symbol } } @@ -138,10 +105,10 @@ export async function getBulkPoolDataFromPoolList( blockClient: ApolloClient, chainId: ChainId, ethPrice: string | undefined, -): Promise { +): Promise { try { const current = await apolloClient.query({ - query: POOLS_BULK_FROM_LIST(poolList, chainId && !ONLY_DYNAMIC_FEE_CHAINS.includes(chainId)), + query: POOLS_BULK_FROM_LIST(poolList, !ONLY_DYNAMIC_FEE_CHAINS.includes(chainId)), fetchPolicy: 'network-only', }) let poolData @@ -155,11 +122,7 @@ export async function getBulkPoolDataFromPoolList( const [oneDayResult] = await Promise.all( [b1].map(async block => { const result = apolloClient.query({ - query: POOLS_HISTORICAL_BULK_FROM_LIST( - block, - poolList, - chainId && !ONLY_DYNAMIC_FEE_CHAINS.includes(chainId), - ), + query: POOLS_HISTORICAL_BULK_FROM_LIST(block, poolList, !ONLY_DYNAMIC_FEE_CHAINS.includes(chainId)), fetchPolicy: 'network-only', }) return result @@ -185,6 +148,10 @@ export async function getBulkPoolDataFromPoolList( data = parseData(data, oneDayHistory, ethPrice, b1, chainId) + const token0 = data.token0 + const token1 = data.token1 + data.token0 = new Token(chainId, token0.id, Number(token0.decimals), token0.symbol, token0.name) + data.token1 = new Token(chainId, token1.id, Number(token1.decimals), token1.symbol, token1.name) return data }), ) @@ -197,7 +164,7 @@ export async function getBulkPoolDataFromPoolList( } } -export async function getBulkPoolDataWithPagination( +async function getBulkPoolDataWithPagination( isEnableBlockService: boolean, first: number, skip: number, @@ -222,7 +189,7 @@ export async function getBulkPoolDataWithPagination( first, skip, block, - chainId && !ONLY_DYNAMIC_FEE_CHAINS.includes(chainId), + !ONLY_DYNAMIC_FEE_CHAINS.includes(chainId), ), fetchPolicy: 'network-only', }) @@ -233,7 +200,7 @@ export async function getBulkPoolDataWithPagination( }) .concat( apolloClient.query({ - query: POOLS_BULK_WITH_PAGINATION(first, skip, chainId && !ONLY_DYNAMIC_FEE_CHAINS.includes(chainId)), + query: POOLS_BULK_WITH_PAGINATION(first, skip, !ONLY_DYNAMIC_FEE_CHAINS.includes(chainId)), fetchPolicy: 'network-only', }), ), @@ -258,7 +225,10 @@ export async function getBulkPoolDataWithPagination( // } data = parseData(data, oneDayHistory, ethPrice, b1, chainId) - + const token0 = data.token0 + const token1 = data.token1 + data.token0 = new Token(chainId, token0.id, Number(token0.decimals), token0.symbol, token0.name) + data.token1 = new Token(chainId, token1.id, Number(token1.decimals), token1.symbol, token1.name) return data }), ) @@ -304,11 +274,7 @@ function usePoolCountInSubgraph(): number { return poolCount } -export function useAllPoolsData(): { - loading: AppState['pools']['loading'] - error: AppState['pools']['error'] - data: AppState['pools']['pools'] -} { +export function useGetClassicPoolsSubgraph(): CommonReturn { const dispatch = useDispatch() const { chainId, isEVM, networkInfo } = useActiveWeb3React() @@ -317,11 +283,12 @@ export function useAllPoolsData(): { const error = useSelector((state: AppState) => state.pools.error) const { currentPrice: ethPrice } = useETHPrice() - const { classicClient, blockClient, isEnableBlockService } = useKyberSwapConfig() + const { classicClient, blockClient, isEnableBlockService, isEnableKNProtocol } = useKyberSwapConfig() const poolCountSubgraph = usePoolCountInSubgraph() useEffect(() => { if (!isEVM) return + if (isEnableKNProtocol) return const getPoolsData = async () => { try { @@ -355,6 +322,7 @@ export function useAllPoolsData(): { getPoolsData() }, [ chainId, + isEnableKNProtocol, dispatch, error, ethPrice, @@ -380,13 +348,13 @@ export function useSinglePoolData( ): { loading: boolean error?: Error - data?: SubgraphPoolData + data?: ClassicPoolData } { const { chainId, isEVM, networkInfo } = useActiveWeb3React() const [loading, setLoading] = useState(false) const [error, setError] = useState(undefined) - const [poolData, setPoolData] = useState() + const [poolData, setPoolData] = useState() const { classicClient, blockClient, isEnableBlockService } = useKyberSwapConfig() useEffect(() => { diff --git a/src/state/pools/reducer.ts b/src/state/pools/reducer.ts index 973c6937d3..0f51e202f7 100644 --- a/src/state/pools/reducer.ts +++ b/src/state/pools/reducer.ts @@ -1,15 +1,17 @@ import { createReducer } from '@reduxjs/toolkit' +import { ClassicPoolData } from 'hooks/pool/classic/type' + import { setError, setLoading, setSelectedPool, setSharedPoolId, updatePools } from './actions' -import { SubgraphPoolData, UserLiquidityPosition } from './hooks' +import { UserLiquidityPosition } from './hooks' interface SelectedPool { - poolData: SubgraphPoolData + poolData: ClassicPoolData myLiquidity: UserLiquidityPosition | undefined } interface PoolsState { - readonly pools: SubgraphPoolData[] + readonly pools: ClassicPoolData[] readonly loading: boolean readonly error: Error | undefined readonly selectedPool: SelectedPool | undefined diff --git a/src/state/prommPools/useGetElasticPools/index.ts b/src/state/prommPools/useGetElasticPools/index.ts index 127cda4f38..fb5330d94b 100644 --- a/src/state/prommPools/useGetElasticPools/index.ts +++ b/src/state/prommPools/useGetElasticPools/index.ts @@ -1,17 +1,9 @@ import { useKyberSwapConfig } from 'state/application/hooks' -import { ElasticPoolDetail } from 'types/pool' +import { CommonReturn } from './type' import useGetElasticPoolsV1 from './useGetElasticPoolsV1' import useGetElasticPoolsV2 from './useGetElasticPoolsV2' -export type CommonReturn = { - isLoading: boolean - isError: boolean - data?: { - [address: string]: ElasticPoolDetail - } -} - const useGetElasticPools = (poolAddresses: string[]): CommonReturn => { const { isEnableKNProtocol } = useKyberSwapConfig() diff --git a/src/state/prommPools/useGetElasticPools/type.ts b/src/state/prommPools/useGetElasticPools/type.ts new file mode 100644 index 0000000000..417d7650bd --- /dev/null +++ b/src/state/prommPools/useGetElasticPools/type.ts @@ -0,0 +1,9 @@ +import { ElasticPoolDetail } from 'types/pool' + +export type CommonReturn = { + isLoading: boolean + isError: boolean + data?: { + [address: string]: ElasticPoolDetail + } +} diff --git a/src/state/prommPools/useGetElasticPools/useGetElasticPoolsV1.ts b/src/state/prommPools/useGetElasticPools/useGetElasticPoolsV1.ts index 512f9120f9..a51893f346 100644 --- a/src/state/prommPools/useGetElasticPools/useGetElasticPoolsV1.ts +++ b/src/state/prommPools/useGetElasticPools/useGetElasticPoolsV1.ts @@ -9,7 +9,7 @@ import { useKyberSwapConfig } from 'state/application/hooks' import { ElasticPoolDetail } from 'types/pool' import { getBlocksFromTimestamps } from 'utils' -import { CommonReturn } from '.' +import { CommonReturn } from './type' interface PoolDataResponse { pools: ProMMPoolFields[] diff --git a/src/state/prommPools/useGetElasticPools/useGetElasticPoolsV2.ts b/src/state/prommPools/useGetElasticPools/useGetElasticPoolsV2.ts index f071b96f8a..0b6cda50f5 100644 --- a/src/state/prommPools/useGetElasticPools/useGetElasticPoolsV2.ts +++ b/src/state/prommPools/useGetElasticPools/useGetElasticPoolsV2.ts @@ -6,7 +6,7 @@ import { useActiveWeb3React } from 'hooks' import { useKyberSwapConfig } from 'state/application/hooks' import { ElasticPoolDetail } from 'types/pool' -import { CommonReturn } from '.' +import { CommonReturn } from './type' export type RawToken = { id: string diff --git a/src/state/user/hooks.tsx b/src/state/user/hooks.tsx index 7d37593e37..d9d80fbb9a 100644 --- a/src/state/user/hooks.tsx +++ b/src/state/user/hooks.tsx @@ -248,11 +248,10 @@ export function useToV2LiquidityTokens( result.map((result, index) => { return { tokens: tokenCouples[index], - liquidityTokens: result?.result?.[0] - ? result.result[0].map( - (address: string) => new Token(tokenCouples[index][0].chainId, address, 18, 'DMM-LP', 'DMM LP'), - ) - : [], + liquidityTokens: + result?.result?.[0]?.map( + (address: string) => new Token(tokenCouples[index][0].chainId, address, 18, 'DMM-LP', 'DMM LP'), + ) ?? [], } }), [tokenCouples, result], diff --git a/src/utils/dmm.ts b/src/utils/dmm.ts index 5e00914532..f9884b5b31 100644 --- a/src/utils/dmm.ts +++ b/src/utils/dmm.ts @@ -1,4 +1,3 @@ -import { getAddress } from '@ethersproject/address' import { BigNumber } from '@ethersproject/bignumber' import { Pair } from '@kyberswap/ks-sdk-classic' import { ChainId, Currency, CurrencyAmount, Fraction, Price, Token, TokenAmount } from '@kyberswap/ks-sdk-core' @@ -10,13 +9,14 @@ import { EVM_NETWORK } from 'constants/networks' import { NativeCurrencies } from 'constants/tokens' import { useActiveWeb3React } from 'hooks' import { useAllTokens } from 'hooks/Tokens' +import { ClassicPoolData } from 'hooks/pool/classic/type' import { useBlockNumber } from 'state/application/hooks' import { useRewardTokens } from 'state/farms/classic/hooks' -import { Farm, Reward, RewardPerTimeUnit } from 'state/farms/classic/types' -import { SubgraphPoolData, UserLiquidityPosition } from 'state/pools/hooks' +import { FairLaunchVersion, Farm, Reward, RewardPerTimeUnit } from 'state/farms/classic/types' +import { UserLiquidityPosition } from 'state/pools/hooks' import { tryParseAmount } from 'state/swap/hooks' import { useTokenPrices } from 'state/tokenPrices/hooks' -import { formattedNum } from 'utils' +import { formatDisplayNumber } from 'utils/numbers' import { isTokenNative } from 'utils/tokenInfo' import { unwrappedToken } from 'utils/wrappedCurrency' @@ -38,7 +38,7 @@ export function priceRangeCalc( } export function parseSubgraphPoolData( - poolData: SubgraphPoolData, + poolData: ClassicPoolData, chainId: ChainId, ): { reserve0: CurrencyAmount | undefined @@ -49,22 +49,8 @@ export function parseSubgraphPoolData( currency0: Currency currency1: Currency } { - const token0 = new Token( - chainId, - getAddress(poolData.token0.id), - +poolData.token0.decimals, - poolData.token0.symbol, - poolData.token0.name, - ) - const token1 = new Token( - chainId, - getAddress(poolData.token1.id), - +poolData.token1.decimals, - poolData.token1.symbol, - poolData.token1.name, - ) - const currency0 = unwrappedToken(token0) - const currency1 = unwrappedToken(token1) + const currency0 = unwrappedToken(poolData.token0) + const currency1 = unwrappedToken(poolData.token1) const reserve0 = tryParseAmount(poolData.reserve0, currency0) const virtualReserve0 = tryParseAmount(poolData.vReserve0, currency0) @@ -85,7 +71,7 @@ export function parseSubgraphPoolData( // const temp = pool.virtualReserve1.subtract(pool.reserve1).divide(pool.reserve1.decimalScale).asFraction -function getToken0MinPrice(pool: Pair | SubgraphPoolData): Fraction { +function getToken0MinPrice(pool: Pair | ClassicPoolData): Fraction { if (pool instanceof Pair) { const temp = pool.virtualReserve1.subtract(pool.reserve1).divide(pool.reserve1.decimalScale).asFraction return temp @@ -112,7 +98,7 @@ function getToken0MinPrice(pool: Pair | SubgraphPoolData): Fraction { } } -function getToken0MaxPrice(pool: Pair | SubgraphPoolData): Fraction { +function getToken0MaxPrice(pool: Pair | ClassicPoolData): Fraction { if (pool instanceof Pair) { const temp = pool.virtualReserve0.subtract(pool.reserve0).divide(pool.virtualReserve0.decimalScale).asFraction @@ -145,7 +131,7 @@ function getToken0MaxPrice(pool: Pair | SubgraphPoolData): Fraction { } } -function getToken1MinPrice(pool: Pair | SubgraphPoolData): Fraction { +function getToken1MinPrice(pool: Pair | ClassicPoolData): Fraction { if (pool instanceof Pair) { const temp = pool.virtualReserve0.subtract(pool.reserve0).divide(pool.reserve0.decimalScale).asFraction @@ -173,7 +159,7 @@ function getToken1MinPrice(pool: Pair | SubgraphPoolData): Fraction { } } -function getToken1MaxPrice(pool: Pair | SubgraphPoolData): Fraction { +function getToken1MaxPrice(pool: Pair | ClassicPoolData): Fraction { if (pool instanceof Pair) { const temp = pool.virtualReserve1.subtract(pool.reserve1).divide(pool.reserve1.decimalScale).asFraction @@ -222,7 +208,7 @@ export const priceRangeCalcByPair = (pair?: Pair): [Fraction | undefined, Fracti } export const priceRangeCalcBySubgraphPool = ( - pool?: SubgraphPoolData, + pool?: ClassicPoolData, ): [Fraction | undefined, Fraction | undefined][] => { if (!pool || new Fraction(pool.amp).equalTo(JSBI.BigInt(10000))) return [ @@ -251,12 +237,12 @@ export const getTradingFeeAPR = (liquidity?: string, feeOneDay?: string): number : (parseFloat(feeOneDay) * 365 * 100) / parseFloat(liquidity) } -const DEFAULT_MY_LIQUIDITY = '-' +const DEFAULT_MY_LIQUIDITY = '--' export const getMyLiquidity = ( liquidityPosition?: UserLiquidityPosition, defaultValue = DEFAULT_MY_LIQUIDITY, -): string | 0 => { +): string => { if (!liquidityPosition || parseFloat(liquidityPosition.pool.totalSupply) === 0) { return defaultValue } @@ -265,11 +251,7 @@ export const getMyLiquidity = ( (parseFloat(liquidityPosition.liquidityTokenBalance) * parseFloat(liquidityPosition.pool.reserveUSD)) / parseFloat(liquidityPosition.pool.totalSupply) - if (myLiquidity === 0) { - return defaultValue - } - - return formattedNum(myLiquidity.toString(), true) + return formatDisplayNumber(myLiquidity, { style: 'currency', significantDigits: 4, allowZero: false }) } function useFarmRewardsPerTimeUnit(farm?: Farm): RewardPerTimeUnit[] { @@ -279,29 +261,27 @@ function useFarmRewardsPerTimeUnit(farm?: Farm): RewardPerTimeUnit[] { const farmRewardsPerTimeUnit: RewardPerTimeUnit[] = [] - if (farm.rewardPerSeconds) { + if (farm.version === FairLaunchVersion.V1) { farm.rewardTokens.forEach((token, index) => { + const amount = BigNumber.from(farm.rewardPerBlocks[index]) if (farmRewardsPerTimeUnit[index]) { - farmRewardsPerTimeUnit[index].amount = farmRewardsPerTimeUnit[index].amount.add( - BigNumber.from(farm.rewardPerSeconds[index]), - ) + farmRewardsPerTimeUnit[index].amount = farmRewardsPerTimeUnit[index].amount.add(amount) } else { farmRewardsPerTimeUnit[index] = { token, - amount: BigNumber.from(farm.rewardPerSeconds[index]), + amount, } } }) - } else if (farm.rewardPerBlocks) { + } else { farm.rewardTokens.forEach((token, index) => { + const amount = BigNumber.from(farm.rewardPerSeconds[index]) if (farmRewardsPerTimeUnit[index]) { - farmRewardsPerTimeUnit[index].amount = farmRewardsPerTimeUnit[index].amount.add( - BigNumber.from(farm.rewardPerBlocks[index]), - ) + farmRewardsPerTimeUnit[index].amount = farmRewardsPerTimeUnit[index].amount.add(amount) } else { farmRewardsPerTimeUnit[index] = { token, - amount: BigNumber.from(farm.rewardPerBlocks[index]), + amount, } } }) @@ -323,15 +303,11 @@ export function useFarmApr(farm: Farm, poolLiquidityUsd: string): number { let yearlyRewardUSD - if (farm.rewardPerSeconds) { - // FarmV2 - - const currentTimestamp = Math.floor(Date.now() / 1000) - + if (farm.version === FairLaunchVersion.V1) { // Check if pool is active for liquidity mining const isLiquidityMiningActive = - currentTimestamp && farm.startTime && farm.endTime - ? farm.startTime <= currentTimestamp && currentTimestamp <= farm.endTime + currentBlock && farm.startBlock && farm.endBlock + ? farm.startBlock <= currentBlock && currentBlock <= farm.endBlock : false if (parseFloat(poolLiquidityUsd) === 0 || !isLiquidityMiningActive) { @@ -342,27 +318,29 @@ export function useFarmApr(farm: Farm, poolLiquidityUsd: string): number { return 0 } - yearlyRewardUSD = rewardsPerTimeUnit.reduce((total, rewardPerSecond) => { - if (!rewardPerSecond || !rewardPerSecond.amount) { + yearlyRewardUSD = rewardsPerTimeUnit.reduce((total, rewardPerBlock, index) => { + if (!rewardPerBlock || !rewardPerBlock.amount) { return total } - if (chainId && tokenPrices[rewardPerSecond.token.wrapped.address]) { - const rewardPerSecondAmount = TokenAmount.fromRawAmount( - rewardPerSecond.token, - rewardPerSecond.amount.toString(), - ) - const yearlyETHRewardAllocation = parseFloat(rewardPerSecondAmount.toSignificant(6)) * SECONDS_PER_YEAR - total += yearlyETHRewardAllocation * tokenPrices[rewardPerSecond.token.wrapped.address] + if (isEVM && tokenPrices[index]) { + const rewardPerBlockAmount = TokenAmount.fromRawAmount(rewardPerBlock.token, rewardPerBlock.amount.toString()) + const yearlyETHRewardAllocation = + parseFloat(rewardPerBlockAmount.toSignificant(6)) * BLOCKS_PER_YEAR(chainId as EVM_NETWORK) + total += yearlyETHRewardAllocation * tokenPrices[index] } return total }, 0) } else { + // FarmV2 + + const currentTimestamp = Math.floor(Date.now() / 1000) + // Check if pool is active for liquidity mining const isLiquidityMiningActive = - currentBlock && farm.startBlock && farm.endBlock - ? farm.startBlock <= currentBlock && currentBlock <= farm.endBlock + currentTimestamp && farm.startTime && farm.endTime + ? farm.startTime <= currentTimestamp && currentTimestamp <= farm.endTime : false if (parseFloat(poolLiquidityUsd) === 0 || !isLiquidityMiningActive) { @@ -373,16 +351,18 @@ export function useFarmApr(farm: Farm, poolLiquidityUsd: string): number { return 0 } - yearlyRewardUSD = rewardsPerTimeUnit.reduce((total, rewardPerBlock, index) => { - if (!rewardPerBlock || !rewardPerBlock.amount) { + yearlyRewardUSD = rewardsPerTimeUnit.reduce((total, rewardPerSecond) => { + if (!rewardPerSecond || !rewardPerSecond.amount) { return total } - if (isEVM && tokenPrices[index]) { - const rewardPerBlockAmount = TokenAmount.fromRawAmount(rewardPerBlock.token, rewardPerBlock.amount.toString()) - const yearlyETHRewardAllocation = - parseFloat(rewardPerBlockAmount.toSignificant(6)) * BLOCKS_PER_YEAR(chainId as EVM_NETWORK) - total += yearlyETHRewardAllocation * tokenPrices[index] + if (chainId && tokenPrices[rewardPerSecond.token.wrapped.address]) { + const rewardPerSecondAmount = TokenAmount.fromRawAmount( + rewardPerSecond.token, + rewardPerSecond.amount.toString(), + ) + const yearlyETHRewardAllocation = parseFloat(rewardPerSecondAmount.toSignificant(6)) * SECONDS_PER_YEAR + total += yearlyETHRewardAllocation * tokenPrices[rewardPerSecond.token.wrapped.address] } return total @@ -403,7 +383,7 @@ export function useCurrencyConvertedToNative(currency?: Currency): Currency | un }, [currency]) } -export function useFarmRewards(farms?: Farm[], onlyCurrentUser = true): Reward[] { +export function useFarmRewards(farms?: Farm[]): Reward[] { const result = useMemo(() => { if (!farms) { return [] @@ -438,42 +418,8 @@ export function useFarmRewards(farms?: Farm[], onlyCurrentUser = true): Reward[] return total }, initialRewards) - const initialAllFarmsRewards: { [key: string]: Reward } = {} - - const allFarmsRewards = farms.reduce((total, farm) => { - if (farm.rewardPerSeconds) { - farm.rewardTokens.forEach((token, index) => { - if (total[token.address]) { - total[token.address].amount = total[token.address].amount.add( - BigNumber.from(farm.lastRewardTime - farm.startTime).mul(farm.rewardPerSeconds[index]), - ) - } else { - total[token.address] = { - token, - amount: BigNumber.from(farm.lastRewardTime - farm.startTime).mul(farm.rewardPerSeconds[index]), - } - } - }) - } else { - farm.rewardTokens.forEach((token, index) => { - if (total[token.address]) { - total[token.address].amount = total[token.address].amount.add( - BigNumber.from(farm.lastRewardBlock - farm.startBlock).mul(farm.rewardPerBlocks[index]), - ) - } else { - total[token.address] = { - token, - amount: BigNumber.from(farm.lastRewardBlock - farm.startBlock).mul(farm.rewardPerBlocks[index]), - } - } - }) - } - - return total - }, initialAllFarmsRewards) - - return onlyCurrentUser ? Object.values(userFarmRewards) : Object.values(allFarmsRewards) - }, [farms, onlyCurrentUser]) + return Object.values(userFarmRewards) + }, [farms]) return result } diff --git a/src/utils/formatCurrencyAmount.tsx b/src/utils/formatCurrencyAmount.tsx index 352a304226..b3384e2106 100644 --- a/src/utils/formatCurrencyAmount.tsx +++ b/src/utils/formatCurrencyAmount.tsx @@ -3,7 +3,7 @@ import JSBI from 'jsbi' import { MouseoverTooltip } from 'components/Tooltip' -// todo: deprecated, use formatDisplayNumber instead +/** @deprecated use formatDisplayNumber instead */ export function formatCurrencyAmount(amount: CurrencyAmount | undefined, sigFigs: number) { if (!amount) { return '-' @@ -20,7 +20,7 @@ export function formatCurrencyAmount(amount: CurrencyAmount | undefine return amount.toSignificant(sigFigs) } -// todo: deprecated, use formatDisplayNumber instead +/** @deprecated use formatDisplayNumber instead */ export function toSignificantOrMaxIntegerPart(price: Price | undefined, sigFigs: number): string { if (!price) return '' @@ -30,7 +30,7 @@ export function toSignificantOrMaxIntegerPart(price: Price | return price.toSignificant(sigFigs) } -// todo: deprecated, use formatDisplayNumber instead +/** @deprecated use formatDisplayNumber instead */ export function formatPrice(price: Price | undefined, sigFigs: number) { if (!price) { return '-' diff --git a/src/utils/index.ts b/src/utils/index.ts index b49c364c34..b64d743c33 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -152,8 +152,9 @@ const formatDollarSignificantAmount = (num: number, minDigits: number, maxDigits }) return formatter.format(num) } - -// todo: deprecated, use formatDisplayNumber instead +/** @deprecated use formatDisplayNumber instead + * @example formatDisplayNumber(number, { style: 'decimal', significantDigits: 2 }) + */ export function formatNumberWithPrecisionRange(number: number, minPrecision = 2, maxPrecision = 2) { const options = { minimumFractionDigits: minPrecision, @@ -176,7 +177,9 @@ const truncateFloatNumber = (num: number, maximumFractionDigits = 6) => { return `${wholePart}.${fractionalPart.slice(0, maximumFractionDigits)}` } -// todo: deprecated, use formatDisplayNumber instead +/** @deprecated use formatDisplayNumber instead + * @example formatDisplayNumber(number, { style: 'currency' | 'decimal', significantDigits: 6 }) + */ export function formattedNum(number: string | number, usd = false, fractionDigits = 5): string { if (number === 0 || number === '' || number === undefined) { return usd ? '$0' : '0' @@ -218,7 +221,9 @@ export function formattedNum(number: string | number, usd = false, fractionDigit return truncateFloatNumber(num, fractionDigits) } -// todo: deprecated, use formatDisplayNumber instead +/** @deprecated use formatDisplayNumber instead + * @example formatDisplayNumber(number, { style: 'currency' | 'decimal', significantDigits: 6 }) + */ export function formattedNumLong(num: number, usd = false) { if (num === 0) { if (usd) { diff --git a/src/utils/numbers.ts b/src/utils/numbers.ts index 59e3422b8d..e50be0019c 100644 --- a/src/utils/numbers.ts +++ b/src/utils/numbers.ts @@ -1,9 +1,12 @@ import { CurrencyAmount, Fraction, Percent, Price } from '@kyberswap/ks-sdk-core' +import { BigNumber } from 'ethers' import JSBI from 'jsbi' import { BIG_INT_ONE, BIG_INT_ZERO, RESERVE_USD_DECIMALS } from 'constants/index' -// todo: deprecated, use formatDisplayNumber instead +/** @deprecated use formatDisplayNumber instead + * @example formatDisplayNumber(num, { style: 'currency', significantDigits: 4 }) + */ export const formatDollarAmount = (num: number | undefined, digits = 2) => { if (num === 0) return '$0.00' if (!num) return '-' @@ -26,7 +29,7 @@ export const formatDollarAmount = (num: number | undefined, digits = 2) => { // e.g: (123456789123456789123456789).toString() => 1.2345678912345679e+26 // toFixed(123456789123456789123456789) => 123456789123456800000000000 // https://stackoverflow.com/a/1685917/8153505 -export function toFixed(x: number): string { +export function toString(x: number): string { if (Math.abs(x) < 1.0) { const e = parseInt(x.toString().split('e-')[1]) if (e) { @@ -44,6 +47,9 @@ export function toFixed(x: number): string { return x.toString() } +/** @deprecated use parseFraction instead + * @example parseFraction(value) + */ export const uint256ToFraction = (value: string, decimals = RESERVE_USD_DECIMALS) => new Fraction(value, JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(decimals))) @@ -64,19 +70,44 @@ const log10 = (n: Fraction): number => { const parsedN = Number(n.toSignificant(30)) return Math.log10(parsedN) } +// - $ 123,456,222,333.44444 e+22 eur5 +const regex = /^\s*?\+?(-)?\s*?(\$)?\s*?([\d,]+)(?:\.(\d+))?\s*?(?:e\+?(\-?\d+))?\s*?(%|\w+?)?\s*?$/ +const parseNumPart = (str: string): [string, string, string, string, string, string] => { + const parsedResult = regex.exec(str) + if (parsedResult) { + const [, negative, currency, integer, decimal, exponent, unit] = parsedResult + return [negative || '', currency || '', integer, decimal || '', exponent, unit || ''] + } + return ['', '', '0', '', '', ''] // [negative, currency, integer, decimal, exponent, unit] +} -const parseNum = (value: FormatValue): Fraction => { +const parseString = (value: string): Fraction => { + try { + const [negative, _currency, integer, decimal, e, _unit] = parseNumPart(value) + const exponent = Number(e || '0') - decimal.length + if (exponent > 0) { + return new Fraction(negative + integer.replace(/,/g, '') + decimal + '0'.repeat(exponent), 1) + } + return new Fraction(negative + integer.replace(/,/g, '') + decimal, 10 ** -exponent) + } catch (e) { + return new Fraction(0, 1) + } +} + +export const parseFraction = (value: FormatValue): Fraction => { try { if ( typeof value === 'string' || typeof value === 'number' || + value instanceof BigNumber || value instanceof CurrencyAmount || value instanceof Percent || value instanceof Price ) { const valueStr = (() => { - if (typeof value === 'string') return toFixed(+value) - if (typeof value === 'number') return toFixed(value) + if (typeof value === 'string') return parseString(value).toFixed(18) + if (typeof value === 'number') return toString(value) + if (value instanceof BigNumber) return value.toString() if (value instanceof CurrencyAmount) return value.toFixed(value.currency.decimals) if (value instanceof Price) return value.toFixed(18) if (value instanceof Percent) return value.divide(100).toFixed(18) @@ -94,13 +125,14 @@ const parseNum = (value: FormatValue): Fraction => { } } -type FormatValue = string | number | bigint | JSBI | Fraction | undefined | null +type FormatValue = string | number | bigint | JSBI | BigNumber | Fraction | undefined | null type FormatOptions = { style?: 'decimal' | 'currency' | 'percent' fractionDigits?: number // usually for percent & currency styles significantDigits?: number // usually for decimal style fallback?: string allowNegative?: boolean + allowZero?: boolean } interface RequiredFraction extends FormatOptions { fractionDigits: number // usually for percent & currency styles @@ -132,6 +164,7 @@ export const formatDisplayNumber = ( fractionDigits, fallback = '--', allowNegative = false, + allowZero = true, }: RequiredFraction | RequiredSignificant, ): string => { const currency = style === 'currency' ? '$' : '' @@ -139,8 +172,9 @@ export const formatDisplayNumber = ( const fallbackResult = `${currency}${fallback}${percent}` if (value === undefined || value === null || Number.isNaN(value)) return fallbackResult - const parsedFraction = parseNum(value) + const parsedFraction = parseFraction(value) if (!allowNegative && parsedFraction.lessThan(BIG_INT_ZERO)) return fallbackResult + if (!allowZero && parsedFraction.equalTo(BIG_INT_ZERO)) return fallbackResult const shownFraction = style === 'percent' ? parsedFraction.multiply(100) : parsedFraction const absShownFraction = shownFraction.lessThan(0) ? shownFraction.multiply(-1) : shownFraction @@ -155,7 +189,7 @@ export const formatDisplayNumber = ( .slice(0, significantDigits || 6) .replace(/0+$/, '') - if (numberOfLeadingZeros > 2) { + if (numberOfLeadingZeros > 3) { const subscripts = numberOfLeadingZeros .toString() .split('') @@ -169,8 +203,10 @@ export const formatDisplayNumber = ( }${percent}` } + const thresholdLog = significantDigits || fractionDigits || 4 + const threshold = thresholdLog > 1 ? 10 ** thresholdLog : 10_000 const formatter = Intl.NumberFormat('en-US', { - notation: absShownFraction.greaterThan(10 ** (significantDigits || fractionDigits || 4)) ? 'compact' : 'standard', + notation: !absShownFraction.lessThan(threshold) ? 'compact' : 'standard', style, currency: 'USD', minimumFractionDigits: fractionDigits ? 0 : undefined, @@ -187,20 +223,10 @@ export const formatDisplayNumber = ( // It might return number with longer fraction digits than maximumFractionDigits // Hence, we have to do an additional step that manually slice those oversize fraction digits if (fractionDigits !== undefined) { - const [negative, currency, integer, decimal, unit] = parseNumPart(result) + const [negative, currency, integer, decimal, _exponent, unit] = parseNumPart(result) const trimedSlicedDecimal = decimal?.slice(0, fractionDigits).replace(/0+$/, '') if (trimedSlicedDecimal) return negative + currency + integer + '.' + trimedSlicedDecimal + unit return negative + currency + integer + unit } return result } - -const regex = /^(-\s*)?(\$\s*)?([\d,]+)(\.\d+)?\s*?(\w?.*?)$/ -const parseNumPart = (str: string): string[] => { - const parsedResult = regex.exec(str) - if (parsedResult) { - const [, negative, currency, integer, decimal, unit] = parsedResult - return [negative?.trim() || '', currency?.trim() || '', integer, decimal?.slice(1) || '', unit?.trim() || ''] - } - return ['', '', '', '', ''] -} diff --git a/src/utils/retry.ts b/src/utils/retry.ts index bd991c5890..4504c4ddbd 100644 --- a/src/utils/retry.ts +++ b/src/utils/retry.ts @@ -68,7 +68,7 @@ export function retry( } } -export const timeoutReject = (ms: number, msg = 'timeout') => { +export const timeoutReject = (ms: number, msg = 'timeout'): Promise => { return new Promise((resolve, reject) => { setTimeout(() => { return reject(new Error(msg)) diff --git a/src/utils/wrappedCurrency.ts b/src/utils/wrappedCurrency.ts index 8599ae0f82..474a45d199 100644 --- a/src/utils/wrappedCurrency.ts +++ b/src/utils/wrappedCurrency.ts @@ -1,9 +1,11 @@ -import { Currency, WETH } from '@kyberswap/ks-sdk-core' +import { Currency, Token, WETH } from '@kyberswap/ks-sdk-core' +import { ZERO_ADDRESS } from 'constants/index' import { NativeCurrencies } from 'constants/tokens' export function unwrappedToken(token: Currency): Currency { if (token.equals(WETH[token.chainId])) return NativeCurrencies[token.chainId] + if (token instanceof Token && token.address === ZERO_ADDRESS) return NativeCurrencies[token.chainId] return token }