@rango-dev/provider-walletconnect-2 0.57.1-next.2 → 0.57.1-next.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-SPXU256S.js +2 -0
- package/dist/{chunk-GEAT645O.js.map → chunk-SPXU256S.js.map} +3 -3
- package/dist/{evm-3KFL5N77.js → evm-KIJWJ4KA.js} +2 -2
- package/dist/mod.d.ts +1 -0
- package/dist/mod.d.ts.map +1 -1
- package/dist/mod.js +1 -1
- package/dist/mod.js.map +3 -3
- package/dist/session/evm.d.ts.map +1 -1
- package/dist/utils.d.ts +1 -0
- package/dist/utils.d.ts.map +1 -1
- package/package.json +8 -7
- package/src/mod.ts +1 -0
- package/src/session/evm.ts +2 -4
- package/src/session/lifecycle.ts +1 -1
- package/src/utils.ts +15 -0
- package/dist/chunk-GEAT645O.js +0 -2
- /package/dist/{evm-3KFL5N77.js.map → evm-KIJWJ4KA.js.map} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var T=Object.defineProperty;var r=(e,n)=>T(e,"name",{value:n,configurable:!0});var _={evm:"eip155",utxo:"bip122"},c="wc@2:client//namespaces";var A=["chainChanged","accountsChanged"],N=["personal_sign","eth_sendTransaction","eth_signTransaction","wallet_switchEthereumChain","wallet_addEthereumChain","eth_chainId"];var I=["bip122_addressesChanged"],S=["signPsbt","getAccountAddresses"],C={name:"Rango Exchange",description:"The Ultimate Cross-Chain Solution",url:"https://app.rango.exchange/",icons:["https://app.rango.exchange/logo-rounded.png"]},m="wss://relay.walletconnect.com";import{isEvmBlockchain as a}from"rango-types";var i=16;async function x(e,n){let t=new Promise((o,s)=>{setTimeout(()=>{s("Timeout!")},n)});return Promise.race([e,t])}r(x,"timeout");function f(e,n=!1){let t=Array.from(new TextEncoder().encode(e)).map(o=>o.toString(i).padStart(2,"0")).join("");return n?`0x${t}`:t}r(f,"utf8ToHex");function p(e){if(e)return typeof e=="string"?e.startsWith("0x")?String(parseInt(e)):String(parseInt(e,10)||e):String(parseInt(e.chainId))}r(p,"parseChainReference");function l(e,n){let t=p(e??void 0);if(t)return n.find(o=>a(o)&&String(parseInt(o.chainId))===t)?.name}r(l,"resolveNetworkName");function h(e){return`0x${parseInt(e).toString(i)}`}r(h,"chainReferenceToHex");function H(e){return e.filter(a).map(n=>({namespace:"eip155",reference:String(parseInt(n.chainId))}))}r(H,"evmMetaToCaipChainIds");export{r as a,_ as b,c,A as d,N as e,I as f,S as g,C as h,m as i,x as j,f as k,p as l,l as m,h as n,H as o};
|
|
2
|
+
//# sourceMappingURL=chunk-SPXU256S.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/wcConstants.ts", "../src/utils.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * WalletConnect protocol constants shared across the hub path (session/,\n * adapter/, signers/, namespaces/). Kept separate from `constants.ts` (which\n * holds the hub provider identity/metadata) so this module stays a dependency\n * leaf and importing it never pulls in the signer/provider graph (the\n * `WalletConnectNamespace` import below is type-only, so it is erased at runtime).\n */\nimport type { WalletConnectNamespace } from './types.js';\n\nexport const PING_TIMEOUT = 10_000;\n\nexport enum NAMESPACES {\n ETHEREUM = 'eip155',\n BITCOIN = 'bip122',\n POLKADOT = 'polkadot',\n CARDANO = 'cip34',\n ERLOND = 'elrond',\n MULTIVERSX = 'multiversx',\n}\n\n/**\n * Single source of truth for the namespace-alias -> CAIP-2 prefix relationship\n * (`evm -> eip155`, `utxo -> bip122`). `proposals` and `lookup` read from this\n * instead of re-encoding it. `Record<WalletConnectNamespace, \u2026>` makes a new\n * alias a compile error until it's mapped.\n */\nexport const WC_NAMESPACE_TO_CAIP: Record<WalletConnectNamespace, string> = {\n evm: NAMESPACES.ETHEREUM,\n utxo: NAMESPACES.BITCOIN,\n};\n\nexport const CHAIN_ID_STORAGE = 'wc@2:client//namespaces';\n\n// Refrence: https://docs.walletconnect.com/2.0/advanced/rpc-reference/ethereum-rpc\nexport enum EthereumRPCMethods {\n PERSONAL_SIGN = 'personal_sign',\n SIGN = 'eth_sign',\n SIGN_TYPED_DATA = 'eth_signTypedData',\n SIGN_TRANSACTION = 'eth_signTransaction',\n SEND_TRANSACTION = 'eth_sendTransaction',\n SEND_RAW_TRANSACTION = 'eth_sendRawTransaction',\n SWITCH_CHAIN = 'wallet_switchEthereumChain',\n ADD_CHAIN = 'wallet_addEthereumChain',\n GET_CHAIN = 'eth_chainId',\n}\n\nexport enum EthereumEvents {\n CHAIN_CHANGED = 'chainChanged',\n ACCOUNTS_CHANGED = 'accountsChanged',\n}\n\nexport const DEFAULT_ETHEREUM_EVENTS: EthereumEvents[] = [\n EthereumEvents.CHAIN_CHANGED,\n EthereumEvents.ACCOUNTS_CHANGED,\n];\n\nexport const DEFAULT_ETHEREUM_METHODS = [\n EthereumRPCMethods.PERSONAL_SIGN,\n EthereumRPCMethods.SEND_TRANSACTION,\n EthereumRPCMethods.SIGN_TRANSACTION,\n EthereumRPCMethods.SWITCH_CHAIN,\n EthereumRPCMethods.ADD_CHAIN,\n EthereumRPCMethods.GET_CHAIN,\n];\n\n// Reference: https://docs.reown.com/advanced/multichain/rpc-reference/bitcoin-rpc\nexport enum BitcoinRPCMethods {\n SIGN_PSBT = 'signPsbt',\n GET_ACCOUNT_ADDRESSES = 'getAccountAddresses',\n SIGN_MESSAGE = 'signMessage',\n SEND_TRANSFER = 'sendTransfer',\n}\n\nexport enum BitcoinEvents {\n ADDRESSES_CHANGED = 'bip122_addressesChanged',\n}\n\nexport const DEFAULT_BITCOIN_EVENTS: BitcoinEvents[] = [\n BitcoinEvents.ADDRESSES_CHANGED,\n];\n\nexport const DEFAULT_BITCOIN_METHODS = [\n BitcoinRPCMethods.SIGN_PSBT,\n BitcoinRPCMethods.GET_ACCOUNT_ADDRESSES,\n];\n\nexport const DEFAULT_APP_METADATA = {\n name: 'Rango Exchange',\n description: 'The Ultimate Cross-Chain Solution',\n url: 'https://app.rango.exchange/',\n icons: ['https://app.rango.exchange/logo-rounded.png'],\n};\n\nexport const RELAY_URL = 'wss://relay.walletconnect.com';\n", "import type { Chain } from '@hub3js/evm';\nimport type { ChainIdParams } from 'caip';\nimport type { BlockchainMeta } from 'rango-types';\n\nimport { isEvmBlockchain } from 'rango-types';\n\nimport { NAMESPACES } from './wcConstants.js';\n\nconst HEX_RADIX = 16;\n\nexport function utf8ToHex(value: string, prefixed = false): string {\n const hex = Array.from(new TextEncoder().encode(value))\n .map((byte) => byte.toString(HEX_RADIX).padStart(2, '0'))\n .join('');\n\n return prefixed ? `0x${hex}` : hex;\n}\n\n/** Normalizes hub chain input (hex, decimal, or AddEthereumChainParameter) to a decimal reference. */\nexport function parseChainReference(\n chain?: string | Chain\n): string | undefined {\n if (!chain) {\n return undefined;\n }\n\n if (typeof chain === 'string') {\n return chain.startsWith('0x')\n ? String(parseInt(chain))\n : String(parseInt(chain, 10) || chain);\n }\n\n return String(parseInt(chain.chainId));\n}\n\n/** Maps a chain reference to a Rango network name using blockchain meta. */\nexport function resolveNetworkName(\n chain: string | Chain | null | undefined,\n meta: BlockchainMeta[]\n): string | undefined {\n const reference = parseChainReference(chain ?? undefined);\n if (!reference) {\n return undefined;\n }\n\n return meta.find(\n (blockchain) =>\n isEvmBlockchain(blockchain) &&\n String(parseInt(blockchain.chainId)) === reference\n )?.name;\n}\n\n/** Converts a decimal EVM chain reference to the `0x`-prefixed hex expected by hub EVM actions. */\nexport function chainReferenceToHex(reference: string): `0x${string}` {\n return `0x${parseInt(reference).toString(HEX_RADIX)}`;\n}\n\n/**\n * Converts rango EVM blockchain meta to CAIP-2 chain ids - the only chain data the\n * connect/proposal path needs. This is the single boundary where rango-types' chain\n * shape is translated; everything downstream uses caip's ChainIdParams.\n */\nexport function evmMetaToCaipChainIds(meta: BlockchainMeta[]): ChainIdParams[] {\n return meta.filter(isEvmBlockchain).map((blockchain) => ({\n namespace: NAMESPACES.ETHEREUM,\n reference: String(parseInt(blockchain.chainId)),\n }));\n}\n"],
|
|
5
|
-
"mappings": "+EA0BO,IAAMA,EAA+D,CAC1E,IAAK,SACL,KAAM,QACR,EAEaC,EAAmB,0BAoBzB,IAAMC,EAA4C,CACvD,eACA,iBACF,EAEaC,EAA2B,CACtC,gBACA,sBACA,sBACA,6BACA,0BACA,aACF,EAcO,IAAMC,EAA0C,CACrD,yBACF,EAEaC,EAA0B,CACrC,WACA,qBACF,EAEaC,EAAuB,CAClC,KAAM,iBACN,YAAa,oCACb,IAAK,8BACL,MAAO,CAAC,6CAA6C,CACvD,EAEaC,EAAY,gCCzFzB,OAAS,mBAAAC,MAAuB,cAIhC,IAAMC,EAAY,
|
|
6
|
-
"names": ["WC_NAMESPACE_TO_CAIP", "CHAIN_ID_STORAGE", "DEFAULT_ETHEREUM_EVENTS", "DEFAULT_ETHEREUM_METHODS", "DEFAULT_BITCOIN_EVENTS", "DEFAULT_BITCOIN_METHODS", "DEFAULT_APP_METADATA", "RELAY_URL", "isEvmBlockchain", "HEX_RADIX", "utf8ToHex", "value", "prefixed", "hex", "byte", "
|
|
4
|
+
"sourcesContent": ["/**\n * WalletConnect protocol constants shared across the hub path (session/,\n * adapter/, signers/, namespaces/). Kept separate from `constants.ts` (which\n * holds the hub provider identity/metadata) so this module stays a dependency\n * leaf and importing it never pulls in the signer/provider graph (the\n * `WalletConnectNamespace` import below is type-only, so it is erased at runtime).\n */\nimport type { WalletConnectNamespace } from './types.js';\n\nexport const PING_TIMEOUT = 10_000;\n\nexport enum NAMESPACES {\n ETHEREUM = 'eip155',\n BITCOIN = 'bip122',\n POLKADOT = 'polkadot',\n CARDANO = 'cip34',\n ERLOND = 'elrond',\n MULTIVERSX = 'multiversx',\n}\n\n/**\n * Single source of truth for the namespace-alias -> CAIP-2 prefix relationship\n * (`evm -> eip155`, `utxo -> bip122`). `proposals` and `lookup` read from this\n * instead of re-encoding it. `Record<WalletConnectNamespace, \u2026>` makes a new\n * alias a compile error until it's mapped.\n */\nexport const WC_NAMESPACE_TO_CAIP: Record<WalletConnectNamespace, string> = {\n evm: NAMESPACES.ETHEREUM,\n utxo: NAMESPACES.BITCOIN,\n};\n\nexport const CHAIN_ID_STORAGE = 'wc@2:client//namespaces';\n\n// Refrence: https://docs.walletconnect.com/2.0/advanced/rpc-reference/ethereum-rpc\nexport enum EthereumRPCMethods {\n PERSONAL_SIGN = 'personal_sign',\n SIGN = 'eth_sign',\n SIGN_TYPED_DATA = 'eth_signTypedData',\n SIGN_TRANSACTION = 'eth_signTransaction',\n SEND_TRANSACTION = 'eth_sendTransaction',\n SEND_RAW_TRANSACTION = 'eth_sendRawTransaction',\n SWITCH_CHAIN = 'wallet_switchEthereumChain',\n ADD_CHAIN = 'wallet_addEthereumChain',\n GET_CHAIN = 'eth_chainId',\n}\n\nexport enum EthereumEvents {\n CHAIN_CHANGED = 'chainChanged',\n ACCOUNTS_CHANGED = 'accountsChanged',\n}\n\nexport const DEFAULT_ETHEREUM_EVENTS: EthereumEvents[] = [\n EthereumEvents.CHAIN_CHANGED,\n EthereumEvents.ACCOUNTS_CHANGED,\n];\n\nexport const DEFAULT_ETHEREUM_METHODS = [\n EthereumRPCMethods.PERSONAL_SIGN,\n EthereumRPCMethods.SEND_TRANSACTION,\n EthereumRPCMethods.SIGN_TRANSACTION,\n EthereumRPCMethods.SWITCH_CHAIN,\n EthereumRPCMethods.ADD_CHAIN,\n EthereumRPCMethods.GET_CHAIN,\n];\n\n// Reference: https://docs.reown.com/advanced/multichain/rpc-reference/bitcoin-rpc\nexport enum BitcoinRPCMethods {\n SIGN_PSBT = 'signPsbt',\n GET_ACCOUNT_ADDRESSES = 'getAccountAddresses',\n SIGN_MESSAGE = 'signMessage',\n SEND_TRANSFER = 'sendTransfer',\n}\n\nexport enum BitcoinEvents {\n ADDRESSES_CHANGED = 'bip122_addressesChanged',\n}\n\nexport const DEFAULT_BITCOIN_EVENTS: BitcoinEvents[] = [\n BitcoinEvents.ADDRESSES_CHANGED,\n];\n\nexport const DEFAULT_BITCOIN_METHODS = [\n BitcoinRPCMethods.SIGN_PSBT,\n BitcoinRPCMethods.GET_ACCOUNT_ADDRESSES,\n];\n\nexport const DEFAULT_APP_METADATA = {\n name: 'Rango Exchange',\n description: 'The Ultimate Cross-Chain Solution',\n url: 'https://app.rango.exchange/',\n icons: ['https://app.rango.exchange/logo-rounded.png'],\n};\n\nexport const RELAY_URL = 'wss://relay.walletconnect.com';\n", "import type { Chain } from '@hub3js/evm';\nimport type { ChainIdParams } from 'caip';\nimport type { BlockchainMeta } from 'rango-types';\n\nimport { isEvmBlockchain } from 'rango-types';\n\nimport { NAMESPACES } from './wcConstants.js';\n\nconst HEX_RADIX = 16;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport async function timeout<T = any>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n forPromise: Promise<any>,\n time: number\n): Promise<T> {\n const timeoutPromise = new Promise((_, reject) => {\n setTimeout(() => {\n reject('Timeout!');\n }, time);\n });\n\n return Promise.race([forPromise, timeoutPromise]);\n}\n\nexport function utf8ToHex(value: string, prefixed = false): string {\n const hex = Array.from(new TextEncoder().encode(value))\n .map((byte) => byte.toString(HEX_RADIX).padStart(2, '0'))\n .join('');\n\n return prefixed ? `0x${hex}` : hex;\n}\n\n/** Normalizes hub chain input (hex, decimal, or AddEthereumChainParameter) to a decimal reference. */\nexport function parseChainReference(\n chain?: string | Chain\n): string | undefined {\n if (!chain) {\n return undefined;\n }\n\n if (typeof chain === 'string') {\n return chain.startsWith('0x')\n ? String(parseInt(chain))\n : String(parseInt(chain, 10) || chain);\n }\n\n return String(parseInt(chain.chainId));\n}\n\n/** Maps a chain reference to a Rango network name using blockchain meta. */\nexport function resolveNetworkName(\n chain: string | Chain | null | undefined,\n meta: BlockchainMeta[]\n): string | undefined {\n const reference = parseChainReference(chain ?? undefined);\n if (!reference) {\n return undefined;\n }\n\n return meta.find(\n (blockchain) =>\n isEvmBlockchain(blockchain) &&\n String(parseInt(blockchain.chainId)) === reference\n )?.name;\n}\n\n/** Converts a decimal EVM chain reference to the `0x`-prefixed hex expected by hub EVM actions. */\nexport function chainReferenceToHex(reference: string): `0x${string}` {\n return `0x${parseInt(reference).toString(HEX_RADIX)}`;\n}\n\n/**\n * Converts rango EVM blockchain meta to CAIP-2 chain ids - the only chain data the\n * connect/proposal path needs. This is the single boundary where rango-types' chain\n * shape is translated; everything downstream uses caip's ChainIdParams.\n */\nexport function evmMetaToCaipChainIds(meta: BlockchainMeta[]): ChainIdParams[] {\n return meta.filter(isEvmBlockchain).map((blockchain) => ({\n namespace: NAMESPACES.ETHEREUM,\n reference: String(parseInt(blockchain.chainId)),\n }));\n}\n"],
|
|
5
|
+
"mappings": "+EA0BO,IAAMA,EAA+D,CAC1E,IAAK,SACL,KAAM,QACR,EAEaC,EAAmB,0BAoBzB,IAAMC,EAA4C,CACvD,eACA,iBACF,EAEaC,EAA2B,CACtC,gBACA,sBACA,sBACA,6BACA,0BACA,aACF,EAcO,IAAMC,EAA0C,CACrD,yBACF,EAEaC,EAA0B,CACrC,WACA,qBACF,EAEaC,EAAuB,CAClC,KAAM,iBACN,YAAa,oCACb,IAAK,8BACL,MAAO,CAAC,6CAA6C,CACvD,EAEaC,EAAY,gCCzFzB,OAAS,mBAAAC,MAAuB,cAIhC,IAAMC,EAAY,GAGlB,eAAsBC,EAEpBC,EACAC,EACY,CACZ,IAAMC,EAAiB,IAAI,QAAQ,CAACC,EAAGC,IAAW,CAChD,WAAW,IAAM,CACfA,EAAO,UAAU,CACnB,EAAGH,CAAI,CACT,CAAC,EAED,OAAO,QAAQ,KAAK,CAACD,EAAYE,CAAc,CAAC,CAClD,CAZsBG,EAAAN,EAAA,WAcf,SAASO,EAAUC,EAAeC,EAAW,GAAe,CACjE,IAAMC,EAAM,MAAM,KAAK,IAAI,YAAY,EAAE,OAAOF,CAAK,CAAC,EACnD,IAAKG,GAASA,EAAK,SAASZ,CAAS,EAAE,SAAS,EAAG,GAAG,CAAC,EACvD,KAAK,EAAE,EAEV,OAAOU,EAAW,KAAKC,CAAG,GAAKA,CACjC,CANgBJ,EAAAC,EAAA,aAST,SAASK,EACdC,EACoB,CACpB,GAAKA,EAIL,OAAI,OAAOA,GAAU,SACZA,EAAM,WAAW,IAAI,EACxB,OAAO,SAASA,CAAK,CAAC,EACtB,OAAO,SAASA,EAAO,EAAE,GAAKA,CAAK,EAGlC,OAAO,SAASA,EAAM,OAAO,CAAC,CACvC,CAdgBP,EAAAM,EAAA,uBAiBT,SAASE,EACdD,EACAE,EACoB,CACpB,IAAMC,EAAYJ,EAAoBC,GAAS,MAAS,EACxD,GAAKG,EAIL,OAAOD,EAAK,KACTE,GACCC,EAAgBD,CAAU,GAC1B,OAAO,SAASA,EAAW,OAAO,CAAC,IAAMD,CAC7C,GAAG,IACL,CAdgBV,EAAAQ,EAAA,sBAiBT,SAASK,EAAoBH,EAAkC,CACpE,MAAO,KAAK,SAASA,CAAS,EAAE,SAASjB,CAAS,CAAC,EACrD,CAFgBO,EAAAa,EAAA,uBAST,SAASC,EAAsBL,EAAyC,CAC7E,OAAOA,EAAK,OAAOG,CAAe,EAAE,IAAKD,IAAgB,CACvD,mBACA,UAAW,OAAO,SAASA,EAAW,OAAO,CAAC,CAChD,EAAE,CACJ,CALgBX,EAAAc,EAAA",
|
|
6
|
+
"names": ["WC_NAMESPACE_TO_CAIP", "CHAIN_ID_STORAGE", "DEFAULT_ETHEREUM_EVENTS", "DEFAULT_ETHEREUM_METHODS", "DEFAULT_BITCOIN_EVENTS", "DEFAULT_BITCOIN_METHODS", "DEFAULT_APP_METADATA", "RELAY_URL", "isEvmBlockchain", "HEX_RADIX", "timeout", "forPromise", "time", "timeoutPromise", "_", "reject", "__name", "utf8ToHex", "value", "prefixed", "hex", "byte", "parseChainReference", "chain", "resolveNetworkName", "meta", "reference", "blockchain", "isEvmBlockchain", "chainReferenceToHex", "evmMetaToCaipChainIds"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as d,
|
|
2
|
-
//# sourceMappingURL=evm-
|
|
1
|
+
import{a as d,k as l}from"./chunk-SPXU256S.js";import{cleanEvmError as p,toHexQuantity as o}from"@rango-dev/signer-evm";import{AccountId as f,ChainId as u}from"caip";import"rango-types";var g="eip155",h=class m{static{d(this,"EVMSigner")}client;getSession;constructor(t,e){this.client=t,this.getSession=e}get session(){let t=this.getSession();if(!t)throw new Error("EVM WalletConnect session is not available.");return t}static buildTx(t){let e={data:t.data||"0x",value:t.value?o(t.value):"0x0"};return t.from&&(e.from=t.from),t.to&&(e.to=t.to),t.nonce&&(e.nonce=o(t.nonce)),t.gasLimit&&(e.gas=o(t.gasLimit)),t.maxFeePerGas&&t.maxPriorityFeePerGas?(e.maxFeePerGas=o(t.maxFeePerGas),e.maxPriorityFeePerGas=o(t.maxPriorityFeePerGas)):t.gasPrice&&(e.gasPrice=o(t.gasPrice)),e}async signMessage(t,e,i){let s=this.isNetworkAndAccountExistInSession({address:e,chainId:i}),r=new u({namespace:g,reference:s.chainId}),a=[l(t,!0),e],c;try{c=await this.client.request({topic:this.session.topic,chainId:r.toString(),request:{method:"personal_sign",params:a}})}catch(S){throw p(S)}return c}async signAndSendTx(t,e,i){try{let s=this.isNetworkAndAccountExistInSession({address:e,chainId:i}),r=m.buildTx(t),n=await this.client.request({topic:this.session.topic,chainId:s.caipChainId,request:{method:"eth_sendTransaction",params:[r]}});if(!n?.startsWith("0x"))throw new Error(`Received an invalid hash on signing the transaction. (hash=${n})`);return{hash:n}}catch(s){let r=p(s),n=this.session,a={namspaces:n?.namespaces,peering:n?.peer?.metadata,code:s?.code};throw r.context=a,r}}isNetworkAndAccountExistInSession(t){let{address:e,chainId:i}=t;if(!i)throw new Error("You need to set your chain for signing message/transaction.");let s=i.startsWith("0x")?String(parseInt(i)):i,r=new f({chainId:{namespace:g,reference:s},address:e}),n=this.session.namespaces[g]?.accounts.map(c=>c.toLowerCase());if(!n||!n.includes(r.toString()))throw new Error("Your requested address doesn't exist on your wallect connect session. Please reconnect your wallet.");let a=new u({namespace:g,reference:s});return{chainId:s,address:e,caipChainId:a.toString()}}},x=h;export{x as default};
|
|
2
|
+
//# sourceMappingURL=evm-KIJWJ4KA.js.map
|
package/dist/mod.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export type { Environments } from './types.js';
|
|
2
2
|
declare const versions: () => readonly [readonly ["1.0.0", import("@hub3js/core").Provider<Record<"evm", import("@hub3js/evm").EvmActions>>]];
|
|
3
3
|
export { versions };
|
|
4
|
+
export { WALLET_ID } from './constants.js';
|
|
4
5
|
//# sourceMappingURL=mod.d.ts.map
|
package/dist/mod.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../src/mod.ts"],"names":[],"mappings":"AAIA,YAAY,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/C,QAAA,MAAM,QAAQ,uHAC8C,CAAC;AAE7D,OAAO,EAAE,QAAQ,EAAE,CAAC"}
|
|
1
|
+
{"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../src/mod.ts"],"names":[],"mappings":"AAIA,YAAY,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/C,QAAA,MAAM,QAAQ,uHAC8C,CAAC;AAE7D,OAAO,EAAE,QAAQ,EAAE,CAAC;AACpB,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC"}
|
package/dist/mod.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as r,b as y,c as D,d as ee,e as te,f as ne,g as se,h as re,i as oe,k as E,l as H,m as S,n as ie}from"./chunk-GEAT645O.js";import{defineVersions as Ft}from"@hub3js/core/utils";import{ProviderBuilder as jt}from"@hub3js/core";import{debug as At}from"@rango-dev/logging-core";import{error as F}from"@rango-dev/logging-core";import{ChainId as Je}from"caip";import{AccountId as L}from"caip";function ae(t){return t.includes(":")?new L(t).address:t}r(ae,"extractAddress");function T(t){return Object.values(t.namespaces).map(n=>n.accounts).flat().map(n=>{let{address:s,chainId:o}=new L(n);return{address:s,chainId:o.reference}})}r(T,"getAccountsFromSession");function ce(t){return Object.values(t.params.namespaces).map(n=>n.accounts).flat().map(n=>{let{address:s,chainId:o}=new L(n);return{accounts:[s],chainId:o.reference}})}r(ce,"getAccountsFromEvent");async function A(t,e){return t.core.storage.setItem(D,{defaultChainId:e?parseInt(e):""})}r(A,"persistCurrentChainId");async function I(t){try{let e=(await t.core.storage.getItem(D))?.defaultChainId;return e?String(e):void 0}catch{return}}r(I,"getPersistedChainId");function j(t,e){let s=e.find(o=>o.name===t)?.chainId;if(s)return String(parseInt(s))}r(j,"getChainIdByNetworkName");import{debug as ze}from"@rango-dev/logging-core";import{convertEvmBlockchainMetaToEvmChainInfo as qe,isEvmAddress as me}from"@rango-dev/wallets-shared";import{AccountId as le,ChainId as $e}from"caip";import{isEvmBlockchain as Ge}from"rango-types";function Ze(t){return t.namespaces.eip155?.accounts?.map(e=>new le(e).address)?.filter(e=>me(e))?.[0]}r(Ze,"getCurrentEvmAccountAddress");function pe(t,e,n){let s=j(t,n);if(s)return le.format({chainId:{namespace:"eip155",reference:s},address:e})}r(pe,"getEvmAccount");function C(t,e){let n=!1;return t.filter(({address:s,chainId:o})=>{if(!me(s)||e&&o!==e)return!1;if(!e){if(n)return!1;n=!0}return!0}).map(({address:s,chainId:o})=>({accounts:[s],chainId:o}))}r(C,"filterEvmAccounts");async function ue(t,e,n,s,o){let i=n.filter(Ge),c=qe(i)[s],m=n.find(h=>h.name===s)?.chainId,l=j(o,n),f=$e.format({namespace:"eip155",reference:String(l)});try{await t.request({topic:e.topic,request:{method:"wallet_switchEthereumChain",params:[{chainId:m}]},chainId:f})}catch(h){let{code:u,message:x}=h??{};if(u===4902||x?.includes(String(4902)))await t.request({topic:e.topic,request:{method:"wallet_addEthereumChain",params:[c]},chainId:f});else throw h}}r(ue,"switchOrAddEvmChain");async function de(t,e,n,s,o){let i=e.namespaces.eip155,a=Ze(e);if(!i||!a)return e;let c=i.accounts??[],p=[pe(n,a,o),pe(s,a,o)].filter(l=>!!l&&!c.includes(l));if(!p.length)return e;let m={...e,namespaces:{...e.namespaces,eip155:{...i,accounts:[...c,...new Set(p)]}}};try{await t.session.update(e.topic,{namespaces:m.namespaces})}catch(l){return ze(l instanceof Error?l:new Error(String(l))),e}return m}r(de,"updateSessionAccounts");function fe(t){let e=["trust","1inch"],n=t.peer?.metadata?.name;return e.some(s=>n?.toLowerCase()?.includes(s))}r(fe,"ignoreNamespaceMethods");async function b(t,e){let n=await I(t);if(n)return n;let s=T(e);return C(s)[0]?.chainId}r(b,"resolveActiveChainReference");async function he(t,e){let n=await b(t,e);if(!n)throw new Error("Unable to determine EVM chain id from WalletConnect session.");return S(n)}r(he,"getCurrentChainId");async function K(t){let{client:e,session:n,meta:s,requestedChainId:o,currentChainId:i}=t,a=E(o);if(!a){let u=new Error(`There is no match for ${o}`);throw F(u),u}let c=new Je({namespace:"eip155",reference:a}).toString(),p=H(o,s),m=H(i,s),l=n.namespaces.eip155,f=l?.chains||[],h=l?.methods||[],d=n;if(h.includes("wallet_switchEthereumChain")&&!fe(n)){if(!p||!m){let u=new Error(`Chain ${a} is not configured.`);throw F(u),u}d=await de(e,n,p,m,s),await ue(e,d,s,p,m)}else if(!f.includes(c)){let u=new Error(`Chain ${a} is not configured.`);throw F(u),u}return await A(e,a),d}r(K,"switchEvmNetwork");async function Qe(t,e){let n=t.getSession("evm");if(!n)throw new Error("WalletConnect session is not available.");let s=await t.getClient(),o=await b(s,n);if(o===e){await A(s,e);return}let i=o?S(o):S(e);t.cacheSession("evm",await K({client:s,session:n,meta:t.meta,requestedChainId:e,currentChainId:i}))}r(Qe,"switchToChainIfNeeded");async function ge(t,e){let n=e?E(e):void 0;t.getSession("evm")||await t.ensureSession({namespace:"evm",chainReference:n}),n&&await Qe(t,n);let s=t.getSession("evm");if(!s)throw new Error("WalletConnect session is not available.");return s}r(ge,"ensureConnectedToChain");import{debug as ht}from"@rango-dev/logging-core";import{timeout as gt}from"@rango-dev/wallets-shared";import{createAppKit as Xe}from"@reown/appkit/core";function Se(t){return{formatters:void 0,fees:void 0,serializers:void 0,...t}}r(Se,"defineChain");var M=Se({id:1,caipNetworkId:"eip155:1",chainNamespace:"eip155",name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:23085558},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),V=Se({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});var Ye=999999999,et=[M,V],tt={evm:M,utxo:V};async function Ce(t,e){await t.ready(),await t.switchNetwork(tt[e])}r(Ce,"prepareModalForNamespace");function ye({projectId:t,universalProvider:e,themeMode:n="light",zIndex:s=Ye}){return Xe({projectId:t,networks:et,universalProvider:e,enableReconnect:!1,defaultNetwork:M,defaultAccountTypes:{bip122:"payment"},manualWCControl:!0,allowUnsupportedChain:!0,themeMode:n,themeVariables:{"--apkt-z-index":s}})}r(ye,"createAppKitModal");import{debug as nt}from"@rango-dev/logging-core";import{CAIP_BITCOIN_CHAIN_ID as st}from"@rango-dev/wallets-core/namespaces/utxo";import{AccountId as z}from"caip";function rt(t){return t.namespaces.bip122?.accounts??[]}r(rt,"getBip122AccountsFromSession");function N(t){return rt(t).map(e=>({address:new z(e).address}))}r(N,"filterBip122Accounts");function ot(t){if(!t?.length)return;let e=t[0];if(typeof e=="string")return e;let n=t;return n.find(s=>s.intention==="payment")?.address??n[0]?.address}r(ot,"pickPaymentAddress");function it(t,e){let n=t.namespaces.bip122;if(!n)return t;let s=new z({chainId:{namespace:"bip122",reference:st},address:e}).toString(),o=n.accounts??[];return o.some(a=>new z(a).address.toLowerCase()===e.toLowerCase())?t:{...t,namespaces:{...t.namespaces,bip122:{...n,accounts:[...o,s]}}}}r(it,"patchBip122SessionAccount");var at=15e3;async function ve(t,e){if(N(e).length)return e;let s=t.session.get(e.topic)??e;if(N(s).length)return s;let{address:i,session:a}=await pt(t,s),c=it(a,i);return await ct(t,c),c}r(ve,"resolveBip122Session");async function ct(t,e){try{await t.session.update(e.topic,{namespaces:e.namespaces})}catch(n){nt(n instanceof Error?n:new Error(String(n)))}}r(ct,"persistSessionNamespaces");async function pt(t,e,n=at){return await new Promise((s,o)=>{let i=e.topic,a=!1,c=r((d,u)=>{a||(a=!0,l(),s({address:d,session:u}))},"finish"),p=r(d=>{a||(a=!0,l(),o(d))},"fail"),m=setTimeout(()=>{p(new Error("Timed out waiting for Bitcoin account from wallet. Please try reconnecting."))},n),l=r(()=>{clearTimeout(m),t.off("session_event",f),t.off("session_update",h)},"cleanup"),f=r(d=>{if(d.topic!==i||d.params.event.name!=="bip122_addressesChanged")return;let u=ot(d.params.event.data);u&&c(u,t.session.get(i)??e)},"onEvent"),h=r(d=>{if(d.topic!==i)return;let u=t.session.get(i)??e,x=N(u);x.length&&c(x[0].address,u)},"onUpdate");t.on("session_event",f),t.on("session_update",h)})}r(pt,"waitForBip122PaymentAddress");function mt(t){return y[t]}r(mt,"getCaipNamespace");function q(t,e){let n=mt(e);return t.session.getAll().find(s=>{let o=s.namespaces[n];return(o?.accounts?.length??0)>0?!0:e==="utxo"&&(o?.chains?.length??0)>0})}r(q,"findSessionByNamespace");function $(t){let e=r(s=>(t.namespaces[y[s]]?.accounts?.length??0)>0,"hasAccounts"),n=r(s=>(t.namespaces[y[s]]?.chains?.length??0)>0,"hasChains");if(e("evm"))return"evm";if(e("utxo")||n("utxo"))return"utxo";if(n("evm"))return"evm"}r($,"getSessionNamespace");import{CAIP_BITCOIN_CHAIN_ID as lt}from"@rango-dev/wallets-core/namespaces/utxo";import{ChainId as ut}from"caip";var dt={evm:{methods:te,events:ee,resolveChains:(t,e)=>e?[{namespace:"eip155",reference:e}]:t.length>0?t:[{namespace:"eip155",reference:"1"}]},utxo:{methods:se,events:ne,resolveChains:()=>[{namespace:"bip122",reference:lt}]}};function Ee(t,e,n){let s={};for(let o of e){let i=dt[o];s[y[o]]={methods:i.methods,events:i.events,chains:i.resolveChains(t,n).map(a=>new ut(a).toString())}}return Object.keys(s).length>0?s:void 0}r(Ee,"generateOptionalNamespace");import{debug as G}from"@rango-dev/logging-core";import{getSdkError as Z}from"@walletconnect/utils";function Ae(t){return(t instanceof Error?t.message:String(t)).includes("No matching key")}r(Ae,"isNoMatchingKeyError");function _(t,e){try{return!!t.session.get(e)}catch{return!1}}r(_,"hasActiveSession");function J(t,e){return t.pairing.getAll().some(n=>n.topic===e)}r(J,"hasActivePairing");async function w(t,e){let n=t.session.getAll(),s=t.pairing.getAll();n.forEach(o=>{if(o.topic===e||o.pairingTopic===e){let i=o.pairingTopic===e?o.pairingTopic:o.topic;t.core.expirer.set(i,0)}}),s.forEach(o=>{o.topic===e&&t.core.expirer.set(e,0)})}r(w,"expireWalletConnectTopic");async function v(t,e){let n=$(e),s=e.pairingTopic;if(_(t,e.topic))try{await t.disconnect({topic:e.topic,reason:Z("USER_DISCONNECTED")})}catch(i){G(i instanceof Error?i:new Error(String(i))),Ae(i)&&await w(t,e.topic)}else await w(t,e.topic);if(!t.session.getAll().filter(i=>i.pairingTopic===s).length&&s)if(J(t,s))try{await t.disconnect({topic:s,reason:Z("USER_DISCONNECTED")})}catch(i){G(i instanceof Error?i:new Error(String(i))),Ae(i)&&await w(t,s)}else await w(t,s);n==="evm"&&A(t,void 0)}r(v,"removeSessionRecord");async function we(t){let e=new Set(t.pairing.getAll().map(n=>n.topic));for(let n of[...t.session.getAll()]){let s=!!n.pairingTopic&&!e.has(n.pairingTopic),o=!_(t,n.topic);(s||o)&&await v(t,n)}}r(we,"purgeOrphanedSessions");async function Te(t){let e=new Set(t.session.getAll().map(n=>n.pairingTopic).filter(n=>!!n));for(let n of[...t.pairing.getAll()])if(!e.has(n.topic))try{await t.disconnect({topic:n.topic,reason:Z("USER_DISCONNECTED")})}catch(s){G(s instanceof Error?s:new Error(String(s))),await w(t,n.topic)}}r(Te,"purgeOrphanedPairings");async function Ie(t,e){for(let n of t.session.getAll()){if($(n)!==e)continue;let s=n.namespaces.bip122;s&&(s.chains?.length??0)>0&&(s.accounts?.length??0)===0&&await v(t,n)}}r(Ie,"cleanupStaleSessionsForNamespace");async function Q(t,e,n={}){let s=await Ct(t,e);if(s&&!(e==="utxo"&&N(s).length===0)&&!(n.validateAccounts&&!await St(t,e,s)))return s}r(Q,"restoreWalletConnectSession");async function St(t,e,n){if(e==="utxo")return N(n).length>0;let s=T(n),o=await I(t);return C(s,o).length>0}r(St,"hasNamespaceAccounts");async function Ct(t,e){let n=q(t,e);if(n?.topic){if(!_(t,n.topic)){await v(t,n);return}if(n.pairingTopic&&!J(t,n.pairingTopic)){await v(t,n);return}try{await gt(t.ping({topic:n.topic}),1e4)}catch(s){ht(s instanceof Error?s:new Error(String(s))),await v(t,n);return}return q(t,e)??n}}r(Ct,"restoreNamespaceSession");async function Ne(t,e){await we(t),await Ie(t,e),await Te(t)}r(Ne,"prepareWalletConnectNamespace");async function Pe(t,e,n){let{chains:s,namespace:o,chainReference:i}=n,a=await Q(t,o);if(a)return a;let c=Ee(s,[o],i),p=await yt(t,e,{optionalNamespaces:c??{}},{envs:n.envs,namespace:o});return o==="utxo"?ve(t,p):p}r(Pe,"connectWalletConnectSession");async function yt(t,e,n,s){let{optionalNamespaces:o,pairingTopic:i}=n;try{let{uri:a,approval:c}=await t.connect({optionalNamespaces:o,pairingTopic:i}),p;if(a){let l=s.envs.DISABLE_MODAL_AND_OPEN_LINK;if(l){let f=`${l}/wc?uri=${encodeURIComponent(a)}`;window.open(f,"_blank","noreferrer noopener")}else{await Ce(e,s.namespace);let f={uri:a,namespace:y[s.namespace]};await e.open(f),p=new Promise((h,d)=>{e.subscribeState(u=>{u.open||d(new Error("Modal has been closed."))})})}}let m=c();return p?await Promise.race([m,p]):await m}finally{e.close()}}r(yt,"createSession");import{debug as vt}from"@rango-dev/logging-core";async function X(t,e,n,s,o){try{let i=await Q(t,e,s);return i?(n.set(e,i),i):null}catch(i){return vt(i instanceof Error?i:new Error(String(i))),n.get(e)&&await o?.(e),null}}r(X,"restoreAndCacheSession");var W=class{static{r(this,"ModalCache")}#e=null;getModal(e){return this.#e||(this.#e=ye(e)),this.#e}};import Et from"@walletconnect/universal-provider";async function xe(t){return Et.init({relayUrl:oe,projectId:t,metadata:re})}r(xe,"createUniversalProvider");function be(){let t=new Map;return{get:e=>t.get(e)??null,set:(e,n)=>void t.set(e,n),clear:e=>void t.delete(e),clearTopic:e=>{for(let[n,s]of t)s.topic===e&&t.delete(n)},clearAll:()=>t.clear()}}r(be,"createSessionCache");var k=class{static{r(this,"TaskQueue")}#e=Promise.resolve();async run(e){let n=this.#e,s;this.#e=new Promise(o=>{s=o}),await n;try{return await e()}finally{s()}}};var R=class{static{r(this,"WalletConnectAdapter")}#e;#a;#c;#p;#n;#r=null;#s=null;#t=be();#m=new W;#o=new k;constructor(e){this.#e=e.projectId,this.#n=e.meta,this.#a=e.disableModalLink,this.#c=e.themeMode,this.#p=e.modalZIndex}async getUniversalProvider(){return this.#s||(this.#s=xe(this.#e).then(e=>(this.#r=e,e)).catch(e=>{throw this.#s=null,e})),this.#s}async getClient(){return(await this.getUniversalProvider()).client}getSession(e){return this.#t.get(e)}cacheSession(e,n){this.#t.set(e,n)}clearSession(e){this.#t.clear(e)}clearAllSessions(){this.#t.clearAll()}async tryRestoreEagerSession(e){return this.#o.run(async()=>{let n=await this.getClient();return!!await X(n,e,this.#t,{validateAccounts:!0},async s=>this.#i(s))})}async ensureSession(e){return this.#o.run(async()=>this.#l(e))}async disconnectSession(e){return this.#o.run(async()=>this.#i(e))}async resolveActiveChainReference(){let e=this.getSession("evm");if(e)return b(await this.getClient(),e)}async getCurrentChainId(){let e=this.getSession("evm");if(!e)throw new Error("Unable to determine EVM chain id from WalletConnect session.");return he(await this.getClient(),e)}async ensureConnectedToChain(e){return ge(this.#u(),e)}async switchEvmNetwork(e,n){let s=this.getSession("evm");if(!s)throw new Error("WalletConnect session is not available.");this.cacheSession("evm",await K({client:await this.getClient(),session:s,meta:this.#n,requestedChainId:e,currentChainId:n}))}async#l(e){let{namespace:n,chainReference:s}=e,o=await this.getClient(),i=await X(o,n,this.#t,void 0,async p=>this.#i(p));if(i)return i;await Ne(o,n);let a=await this.getUniversalProvider();await a.cleanupPendingPairings().catch(()=>{});let c=await Pe(o,this.#m.getModal({projectId:this.#e,universalProvider:a,themeMode:this.#c,zIndex:this.#p}),{chains:ie(this.#n),envs:{WC_PROJECT_ID:this.#e,DISABLE_MODAL_AND_OPEN_LINK:this.#a},namespace:n,chainReference:s});return this.#t.set(n,c),c}async#i(e){let n=this.getSession(e);this.#r?.client&&n&&await v(this.#r.client,n).catch(s=>At(s)),this.clearSession(e),n&&this.#t.clearTopic(n.topic)}#u(){return{meta:this.#n,getSession:e=>this.getSession(e),cacheSession:(e,n)=>this.cacheSession(e,n),getClient:async()=>this.getClient(),ensureSession:async e=>this.ensureSession(e)}}};var Me,g=r(()=>Me,"getAdapter"),_e=r(t=>{Me=t},"setAdapter");import{isEvmNamespace as It}from"@hub3js/evm";import{DefaultSignerFactory as wt,TransactionType as Tt}from"rango-types";async function Y(){let t=g();if(!t)throw new Error("WalletConnect provider has not been initialized.");let e=await t.getClient(),n=new wt,s=(await import("./evm-3KFL5N77.js")).default;return n.registerSigner(Tt.EVM,new s(e,()=>t.getSession("evm"))),n}r(Y,"getSigners");var U="wallet-connect-2",We={name:"WalletConnect",icon:"https://raw.githubusercontent.com/rango-exchange/assets/main/wallets/walletconnect/icon.svg",extensions:{homepage:"https://walletconnect.com/"},properties:[{name:"namespaces",value:{selection:"single",data:[{label:"EVM",value:"EVM",id:"ETH",isChainSupported:It}]}},{name:"signers",value:{getSigners:async()=>Y()}},{name:"details",value:{mobileWallet:!0,showOnMobile:!0}}]};import{NamespaceBuilder as bt}from"@hub3js/core";import{actions as Mt,builders as O,utils as _t}from"@hub3js/evm";import*as De from"@hub3js/std/builders";import{standardizeAndThrowError as Wt}from"@hub3js/std/operators";import{utils as Re}from"@hub3js/evm";import{ChainId as Pt}from"caip";import{debug as Nt}from"@rango-dev/logging-core";function ke(t){Nt(t instanceof Error?t:new Error(String(t)))}r(ke,"logHandlerError");function B(t,e,n){let s=null;return[async o=>{let i=g(),a=await i.getClient();s&&a.off(e,s),s=r(c=>{let p=i.getSession(t);if(!(!p||c.topic!==p.topic))try{let m=n({args:c,session:p,adapter:i,context:o});m instanceof Promise&&m.catch(ke)}catch(m){ke(m)}},"handler"),a.on(e,s)},(o,i)=>{let a=s;return a&&(s=null,g().getClient().then(c=>c.off(e,a))),i}]}r(B,"createSessionSubscriber");function Ue(){return B("evm","session_update",async({args:t,session:e,adapter:n,context:s})=>{t.params.namespaces.eip155&&n.cacheSession("evm",{...e,namespaces:t.params.namespaces});let o=ce(t);if(!o.length)return;let i=o.map(d=>({address:d.accounts[0],chainId:d.chainId})),[a,c]=s.state(),p=a().network,m=await I(await n.getClient()),l=E(p??void 0)??m,f=C(i,l);if(f.length||(f=C(i)),!f.length)return;let h=S(f[0].chainId);c("accounts",Re.formatAccountsToCAIP([f[0].accounts[0]],h)),c("network",h)})}r(Ue,"sessionUpdateSubscriber");function xt(t){return(Array.isArray(t)?t:[t]).filter(e=>typeof e=="string"&&!!e).map(ae)}r(xt,"eventAccounts");function Be(){return B("evm","session_event",({args:t,adapter:e,context:n})=>{let[,s]=n.state();if(t.params.event.name==="accountsChanged"){let o=xt(t.params.event.data);if(!o.length){n.action("disconnect");return}let i=S(Pt.parse(t.params.chainId).reference);s("network",i),s("accounts",Re.formatAccountsToCAIP(o,i));return}if(t.params.event.name==="chainChanged"){let o=S(t.params.event.data);s("network",o),e.getClient().then(async i=>A(i,o))}})}r(Be,"sessionEventSubscriber");function Oe(){return B("evm","session_delete",({args:t,adapter:e,context:n})=>{e.clearSession("evm"),e.getClient().then(async s=>w(s,t.topic)),n.action("disconnect")})}r(Oe,"sessionDeleteSubscriber");var[kt,He]=Ue(),[Rt,Le]=Be(),[Ut,je]=Oe(),Bt=O.connect().action(async function(t,e){let n=g(),s=e?E(e):void 0,o=await n.ensureConnectedToChain(e),i=s??await n.resolveActiveChainReference();if(!i)throw new Error("Unable to determine EVM chain id from WalletConnect session.");let a=T(o),c=C(a,i);if(!c.length)throw new Error("No EVM accounts found in WalletConnect session.");return{accounts:_t.formatAccountsToCAIP(c.map(p=>p.accounts[0]),i),network:S(i)}}).before(kt).before(Rt).before(Ut).or(He).or(Le).or(je).or((t,e)=>(g().disconnectSession("evm"),e)).or(Wt).build(),Ot=O.canEagerConnect().action(async()=>g().tryRestoreEagerSession("evm")).build(),Dt=O.canSwitchNetwork().action(Mt.canSwitchNetwork()).build(),Ht=De.disconnect().before(async()=>{await g().disconnectSession("evm")}).after(He).after(Le).after(je).build(),Lt=O.getChainId().action(async()=>g().getCurrentChainId()).build(),Fe=new bt("EVM",U).action(Bt).action(Ot).action(Dt).action(Ht).action(Lt).build();var Ke=r(()=>new jt(U).init(function(t,e){let[,n]=t.state();e.WC_PROJECT_ID&&(_e(new R({projectId:e.WC_PROJECT_ID,meta:e.meta||[],disableModalLink:e.DISABLE_MODAL_AND_OPEN_LINK,themeMode:e.themeMode,modalZIndex:e.modalZIndex})),n("installed",!0),console.debug("[wallet-connect-2] provider initialized.",t))}).config("metadata",We).add("evm",Fe).build(),"buildProvider");var Sr=r(()=>Ft().version("1.0.0",Ke()).build(),"versions");export{Sr as versions};
|
|
1
|
+
import{a as r,b as y,c as D,d as ee,e as te,f as ne,g as se,h as re,i as oe,j as ie,l as E,m as H,n as S,o as ae}from"./chunk-SPXU256S.js";import{defineVersions as Ft}from"@hub3js/core/utils";import{ProviderBuilder as jt}from"@hub3js/core";import{debug as At}from"@rango-dev/logging-core";import{error as F}from"@rango-dev/logging-core";import{ChainId as Qe}from"caip";import{AccountId as L}from"caip";function ce(t){return t.includes(":")?new L(t).address:t}r(ce,"extractAddress");function T(t){return Object.values(t.namespaces).map(n=>n.accounts).flat().map(n=>{let{address:s,chainId:o}=new L(n);return{address:s,chainId:o.reference}})}r(T,"getAccountsFromSession");function pe(t){return Object.values(t.params.namespaces).map(n=>n.accounts).flat().map(n=>{let{address:s,chainId:o}=new L(n);return{accounts:[s],chainId:o.reference}})}r(pe,"getAccountsFromEvent");async function A(t,e){return t.core.storage.setItem(D,{defaultChainId:e?parseInt(e):""})}r(A,"persistCurrentChainId");async function I(t){try{let e=(await t.core.storage.getItem(D))?.defaultChainId;return e?String(e):void 0}catch{return}}r(I,"getPersistedChainId");function j(t,e){let s=e.find(o=>o.name===t)?.chainId;if(s)return String(parseInt(s))}r(j,"getChainIdByNetworkName");import{debug as qe}from"@rango-dev/logging-core";import{convertEvmBlockchainMetaToEvmChainInfo as $e}from"@rango-dev/internal-blockchains";import{AccountId as le,ChainId as Ge}from"caip";import{isAddress as ue}from"ethers";import{isEvmBlockchain as Ze}from"rango-types";function Je(t){return t.namespaces.eip155?.accounts?.map(e=>new le(e).address)?.filter(e=>ue(e))?.[0]}r(Je,"getCurrentEvmAccountAddress");function me(t,e,n){let s=j(t,n);if(s)return le.format({chainId:{namespace:"eip155",reference:s},address:e})}r(me,"getEvmAccount");function C(t,e){let n=!1;return t.filter(({address:s,chainId:o})=>{if(!ue(s)||e&&o!==e)return!1;if(!e){if(n)return!1;n=!0}return!0}).map(({address:s,chainId:o})=>({accounts:[s],chainId:o}))}r(C,"filterEvmAccounts");async function de(t,e,n,s,o){let i=n.filter(Ze),c=$e(i)[s],m=n.find(h=>h.name===s)?.chainId,l=j(o,n),f=Ge.format({namespace:"eip155",reference:String(l)});try{await t.request({topic:e.topic,request:{method:"wallet_switchEthereumChain",params:[{chainId:m}]},chainId:f})}catch(h){let{code:u,message:b}=h??{};if(u===4902||b?.includes(String(4902)))await t.request({topic:e.topic,request:{method:"wallet_addEthereumChain",params:[c]},chainId:f});else throw h}}r(de,"switchOrAddEvmChain");async function fe(t,e,n,s,o){let i=e.namespaces.eip155,a=Je(e);if(!i||!a)return e;let c=i.accounts??[],p=[me(n,a,o),me(s,a,o)].filter(l=>!!l&&!c.includes(l));if(!p.length)return e;let m={...e,namespaces:{...e.namespaces,eip155:{...i,accounts:[...c,...new Set(p)]}}};try{await t.session.update(e.topic,{namespaces:m.namespaces})}catch(l){return qe(l instanceof Error?l:new Error(String(l))),e}return m}r(fe,"updateSessionAccounts");function he(t){let e=["trust","1inch"],n=t.peer?.metadata?.name;return e.some(s=>n?.toLowerCase()?.includes(s))}r(he,"ignoreNamespaceMethods");async function M(t,e){let n=await I(t);if(n)return n;let s=T(e);return C(s)[0]?.chainId}r(M,"resolveActiveChainReference");async function ge(t,e){let n=await M(t,e);if(!n)throw new Error("Unable to determine EVM chain id from WalletConnect session.");return S(n)}r(ge,"getCurrentChainId");async function K(t){let{client:e,session:n,meta:s,requestedChainId:o,currentChainId:i}=t,a=E(o);if(!a){let u=new Error(`There is no match for ${o}`);throw F(u),u}let c=new Qe({namespace:"eip155",reference:a}).toString(),p=H(o,s),m=H(i,s),l=n.namespaces.eip155,f=l?.chains||[],h=l?.methods||[],d=n;if(h.includes("wallet_switchEthereumChain")&&!he(n)){if(!p||!m){let u=new Error(`Chain ${a} is not configured.`);throw F(u),u}d=await fe(e,n,p,m,s),await de(e,d,s,p,m)}else if(!f.includes(c)){let u=new Error(`Chain ${a} is not configured.`);throw F(u),u}return await A(e,a),d}r(K,"switchEvmNetwork");async function Xe(t,e){let n=t.getSession("evm");if(!n)throw new Error("WalletConnect session is not available.");let s=await t.getClient(),o=await M(s,n);if(o===e){await A(s,e);return}let i=o?S(o):S(e);t.cacheSession("evm",await K({client:s,session:n,meta:t.meta,requestedChainId:e,currentChainId:i}))}r(Xe,"switchToChainIfNeeded");async function Se(t,e){let n=e?E(e):void 0;t.getSession("evm")||await t.ensureSession({namespace:"evm",chainReference:n}),n&&await Xe(t,n);let s=t.getSession("evm");if(!s)throw new Error("WalletConnect session is not available.");return s}r(Se,"ensureConnectedToChain");import{debug as gt}from"@rango-dev/logging-core";import{createAppKit as Ye}from"@reown/appkit/core";function Ce(t){return{formatters:void 0,fees:void 0,serializers:void 0,...t}}r(Ce,"defineChain");var _=Ce({id:1,caipNetworkId:"eip155:1",chainNamespace:"eip155",name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:23085558},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),V=Ce({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});var et=999999999,tt=[_,V],nt={evm:_,utxo:V};async function ye(t,e){await t.ready(),await t.switchNetwork(nt[e])}r(ye,"prepareModalForNamespace");function ve({projectId:t,universalProvider:e,themeMode:n="light",zIndex:s=et}){return Ye({projectId:t,networks:tt,universalProvider:e,enableReconnect:!1,defaultNetwork:_,defaultAccountTypes:{bip122:"payment"},manualWCControl:!0,allowUnsupportedChain:!0,themeMode:n,themeVariables:{"--apkt-z-index":s}})}r(ve,"createAppKitModal");import{debug as st}from"@rango-dev/logging-core";import{CAIP_BITCOIN_CHAIN_ID as rt}from"@rango-dev/wallets-core/namespaces/utxo";import{AccountId as z}from"caip";function ot(t){return t.namespaces.bip122?.accounts??[]}r(ot,"getBip122AccountsFromSession");function N(t){return ot(t).map(e=>({address:new z(e).address}))}r(N,"filterBip122Accounts");function it(t){if(!t?.length)return;let e=t[0];if(typeof e=="string")return e;let n=t;return n.find(s=>s.intention==="payment")?.address??n[0]?.address}r(it,"pickPaymentAddress");function at(t,e){let n=t.namespaces.bip122;if(!n)return t;let s=new z({chainId:{namespace:"bip122",reference:rt},address:e}).toString(),o=n.accounts??[];return o.some(a=>new z(a).address.toLowerCase()===e.toLowerCase())?t:{...t,namespaces:{...t.namespaces,bip122:{...n,accounts:[...o,s]}}}}r(at,"patchBip122SessionAccount");var ct=15e3;async function Ee(t,e){if(N(e).length)return e;let s=t.session.get(e.topic)??e;if(N(s).length)return s;let{address:i,session:a}=await mt(t,s),c=at(a,i);return await pt(t,c),c}r(Ee,"resolveBip122Session");async function pt(t,e){try{await t.session.update(e.topic,{namespaces:e.namespaces})}catch(n){st(n instanceof Error?n:new Error(String(n)))}}r(pt,"persistSessionNamespaces");async function mt(t,e,n=ct){return await new Promise((s,o)=>{let i=e.topic,a=!1,c=r((d,u)=>{a||(a=!0,l(),s({address:d,session:u}))},"finish"),p=r(d=>{a||(a=!0,l(),o(d))},"fail"),m=setTimeout(()=>{p(new Error("Timed out waiting for Bitcoin account from wallet. Please try reconnecting."))},n),l=r(()=>{clearTimeout(m),t.off("session_event",f),t.off("session_update",h)},"cleanup"),f=r(d=>{if(d.topic!==i||d.params.event.name!=="bip122_addressesChanged")return;let u=it(d.params.event.data);u&&c(u,t.session.get(i)??e)},"onEvent"),h=r(d=>{if(d.topic!==i)return;let u=t.session.get(i)??e,b=N(u);b.length&&c(b[0].address,u)},"onUpdate");t.on("session_event",f),t.on("session_update",h)})}r(mt,"waitForBip122PaymentAddress");function lt(t){return y[t]}r(lt,"getCaipNamespace");function q(t,e){let n=lt(e);return t.session.getAll().find(s=>{let o=s.namespaces[n];return(o?.accounts?.length??0)>0?!0:e==="utxo"&&(o?.chains?.length??0)>0})}r(q,"findSessionByNamespace");function $(t){let e=r(s=>(t.namespaces[y[s]]?.accounts?.length??0)>0,"hasAccounts"),n=r(s=>(t.namespaces[y[s]]?.chains?.length??0)>0,"hasChains");if(e("evm"))return"evm";if(e("utxo")||n("utxo"))return"utxo";if(n("evm"))return"evm"}r($,"getSessionNamespace");import{CAIP_BITCOIN_CHAIN_ID as ut}from"@rango-dev/wallets-core/namespaces/utxo";import{ChainId as dt}from"caip";var ft={evm:{methods:te,events:ee,resolveChains:(t,e)=>e?[{namespace:"eip155",reference:e}]:t.length>0?t:[{namespace:"eip155",reference:"1"}]},utxo:{methods:se,events:ne,resolveChains:()=>[{namespace:"bip122",reference:ut}]}};function Ae(t,e,n){let s={};for(let o of e){let i=ft[o];s[y[o]]={methods:i.methods,events:i.events,chains:i.resolveChains(t,n).map(a=>new dt(a).toString())}}return Object.keys(s).length>0?s:void 0}r(Ae,"generateOptionalNamespace");import{debug as G}from"@rango-dev/logging-core";import{getSdkError as Z}from"@walletconnect/utils";function we(t){return(t instanceof Error?t.message:String(t)).includes("No matching key")}r(we,"isNoMatchingKeyError");function W(t,e){try{return!!t.session.get(e)}catch{return!1}}r(W,"hasActiveSession");function J(t,e){return t.pairing.getAll().some(n=>n.topic===e)}r(J,"hasActivePairing");async function w(t,e){let n=t.session.getAll(),s=t.pairing.getAll();n.forEach(o=>{if(o.topic===e||o.pairingTopic===e){let i=o.pairingTopic===e?o.pairingTopic:o.topic;t.core.expirer.set(i,0)}}),s.forEach(o=>{o.topic===e&&t.core.expirer.set(e,0)})}r(w,"expireWalletConnectTopic");async function v(t,e){let n=$(e),s=e.pairingTopic;if(W(t,e.topic))try{await t.disconnect({topic:e.topic,reason:Z("USER_DISCONNECTED")})}catch(i){G(i instanceof Error?i:new Error(String(i))),we(i)&&await w(t,e.topic)}else await w(t,e.topic);if(!t.session.getAll().filter(i=>i.pairingTopic===s).length&&s)if(J(t,s))try{await t.disconnect({topic:s,reason:Z("USER_DISCONNECTED")})}catch(i){G(i instanceof Error?i:new Error(String(i))),we(i)&&await w(t,s)}else await w(t,s);n==="evm"&&A(t,void 0)}r(v,"removeSessionRecord");async function Te(t){let e=new Set(t.pairing.getAll().map(n=>n.topic));for(let n of[...t.session.getAll()]){let s=!!n.pairingTopic&&!e.has(n.pairingTopic),o=!W(t,n.topic);(s||o)&&await v(t,n)}}r(Te,"purgeOrphanedSessions");async function Ie(t){let e=new Set(t.session.getAll().map(n=>n.pairingTopic).filter(n=>!!n));for(let n of[...t.pairing.getAll()])if(!e.has(n.topic))try{await t.disconnect({topic:n.topic,reason:Z("USER_DISCONNECTED")})}catch(s){G(s instanceof Error?s:new Error(String(s))),await w(t,n.topic)}}r(Ie,"purgeOrphanedPairings");async function Ne(t,e){for(let n of t.session.getAll()){if($(n)!==e)continue;let s=n.namespaces.bip122;s&&(s.chains?.length??0)>0&&(s.accounts?.length??0)===0&&await v(t,n)}}r(Ne,"cleanupStaleSessionsForNamespace");async function Q(t,e,n={}){let s=await Ct(t,e);if(s&&!(e==="utxo"&&N(s).length===0)&&!(n.validateAccounts&&!await St(t,e,s)))return s}r(Q,"restoreWalletConnectSession");async function St(t,e,n){if(e==="utxo")return N(n).length>0;let s=T(n),o=await I(t);return C(s,o).length>0}r(St,"hasNamespaceAccounts");async function Ct(t,e){let n=q(t,e);if(n?.topic){if(!W(t,n.topic)){await v(t,n);return}if(n.pairingTopic&&!J(t,n.pairingTopic)){await v(t,n);return}try{await ie(t.ping({topic:n.topic}),1e4)}catch(s){gt(s instanceof Error?s:new Error(String(s))),await v(t,n);return}return q(t,e)??n}}r(Ct,"restoreNamespaceSession");async function Pe(t,e){await Te(t),await Ne(t,e),await Ie(t)}r(Pe,"prepareWalletConnectNamespace");async function xe(t,e,n){let{chains:s,namespace:o,chainReference:i}=n,a=await Q(t,o);if(a)return a;let c=Ae(s,[o],i),p=await yt(t,e,{optionalNamespaces:c??{}},{envs:n.envs,namespace:o});return o==="utxo"?Ee(t,p):p}r(xe,"connectWalletConnectSession");async function yt(t,e,n,s){let{optionalNamespaces:o,pairingTopic:i}=n;try{let{uri:a,approval:c}=await t.connect({optionalNamespaces:o,pairingTopic:i}),p;if(a){let l=s.envs.DISABLE_MODAL_AND_OPEN_LINK;if(l){let f=`${l}/wc?uri=${encodeURIComponent(a)}`;window.open(f,"_blank","noreferrer noopener")}else{await ye(e,s.namespace);let f={uri:a,namespace:y[s.namespace]};await e.open(f),p=new Promise((h,d)=>{e.subscribeState(u=>{u.open||d(new Error("Modal has been closed."))})})}}let m=c();return p?await Promise.race([m,p]):await m}finally{e.close()}}r(yt,"createSession");import{debug as vt}from"@rango-dev/logging-core";async function X(t,e,n,s,o){try{let i=await Q(t,e,s);return i?(n.set(e,i),i):null}catch(i){return vt(i instanceof Error?i:new Error(String(i))),n.get(e)&&await o?.(e),null}}r(X,"restoreAndCacheSession");var k=class{static{r(this,"ModalCache")}#e=null;getModal(e){return this.#e||(this.#e=ve(e)),this.#e}};import Et from"@walletconnect/universal-provider";async function be(t){return Et.init({relayUrl:oe,projectId:t,metadata:re})}r(be,"createUniversalProvider");function Me(){let t=new Map;return{get:e=>t.get(e)??null,set:(e,n)=>void t.set(e,n),clear:e=>void t.delete(e),clearTopic:e=>{for(let[n,s]of t)s.topic===e&&t.delete(n)},clearAll:()=>t.clear()}}r(Me,"createSessionCache");var R=class{static{r(this,"TaskQueue")}#e=Promise.resolve();async run(e){let n=this.#e,s;this.#e=new Promise(o=>{s=o}),await n;try{return await e()}finally{s()}}};var U=class{static{r(this,"WalletConnectAdapter")}#e;#a;#c;#p;#n;#r=null;#s=null;#t=Me();#m=new k;#o=new R;constructor(e){this.#e=e.projectId,this.#n=e.meta,this.#a=e.disableModalLink,this.#c=e.themeMode,this.#p=e.modalZIndex}async getUniversalProvider(){return this.#s||(this.#s=be(this.#e).then(e=>(this.#r=e,e)).catch(e=>{throw this.#s=null,e})),this.#s}async getClient(){return(await this.getUniversalProvider()).client}getSession(e){return this.#t.get(e)}cacheSession(e,n){this.#t.set(e,n)}clearSession(e){this.#t.clear(e)}clearAllSessions(){this.#t.clearAll()}async tryRestoreEagerSession(e){return this.#o.run(async()=>{let n=await this.getClient();return!!await X(n,e,this.#t,{validateAccounts:!0},async s=>this.#i(s))})}async ensureSession(e){return this.#o.run(async()=>this.#l(e))}async disconnectSession(e){return this.#o.run(async()=>this.#i(e))}async resolveActiveChainReference(){let e=this.getSession("evm");if(e)return M(await this.getClient(),e)}async getCurrentChainId(){let e=this.getSession("evm");if(!e)throw new Error("Unable to determine EVM chain id from WalletConnect session.");return ge(await this.getClient(),e)}async ensureConnectedToChain(e){return Se(this.#u(),e)}async switchEvmNetwork(e,n){let s=this.getSession("evm");if(!s)throw new Error("WalletConnect session is not available.");this.cacheSession("evm",await K({client:await this.getClient(),session:s,meta:this.#n,requestedChainId:e,currentChainId:n}))}async#l(e){let{namespace:n,chainReference:s}=e,o=await this.getClient(),i=await X(o,n,this.#t,void 0,async p=>this.#i(p));if(i)return i;await Pe(o,n);let a=await this.getUniversalProvider();await a.cleanupPendingPairings().catch(()=>{});let c=await xe(o,this.#m.getModal({projectId:this.#e,universalProvider:a,themeMode:this.#c,zIndex:this.#p}),{chains:ae(this.#n),envs:{WC_PROJECT_ID:this.#e,DISABLE_MODAL_AND_OPEN_LINK:this.#a},namespace:n,chainReference:s});return this.#t.set(n,c),c}async#i(e){let n=this.getSession(e);this.#r?.client&&n&&await v(this.#r.client,n).catch(s=>At(s)),this.clearSession(e),n&&this.#t.clearTopic(n.topic)}#u(){return{meta:this.#n,getSession:e=>this.getSession(e),cacheSession:(e,n)=>this.cacheSession(e,n),getClient:async()=>this.getClient(),ensureSession:async e=>this.ensureSession(e)}}};var _e,g=r(()=>_e,"getAdapter"),We=r(t=>{_e=t},"setAdapter");import{isEvmNamespace as It}from"@hub3js/evm";import{DefaultSignerFactory as wt,TransactionType as Tt}from"rango-types";async function Y(){let t=g();if(!t)throw new Error("WalletConnect provider has not been initialized.");let e=await t.getClient(),n=new wt,s=(await import("./evm-KIJWJ4KA.js")).default;return n.registerSigner(Tt.EVM,new s(e,()=>t.getSession("evm"))),n}r(Y,"getSigners");var x="wallet-connect-2",ke={name:"WalletConnect",icon:"https://raw.githubusercontent.com/rango-exchange/assets/main/wallets/walletconnect/icon.svg",extensions:{homepage:"https://walletconnect.com/"},properties:[{name:"namespaces",value:{selection:"single",data:[{label:"EVM",value:"EVM",id:"ETH",isChainSupported:It}]}},{name:"signers",value:{getSigners:async()=>Y()}},{name:"details",value:{mobileWallet:!0,showOnMobile:!0}}]};import{NamespaceBuilder as bt}from"@hub3js/core";import{actions as Mt,builders as O,utils as _t}from"@hub3js/evm";import*as He from"@hub3js/std/builders";import{standardizeAndThrowError as Wt}from"@hub3js/std/operators";import{utils as Ue}from"@hub3js/evm";import{ChainId as Pt}from"caip";import{debug as Nt}from"@rango-dev/logging-core";function Re(t){Nt(t instanceof Error?t:new Error(String(t)))}r(Re,"logHandlerError");function B(t,e,n){let s=null;return[async o=>{let i=g(),a=await i.getClient();s&&a.off(e,s),s=r(c=>{let p=i.getSession(t);if(!(!p||c.topic!==p.topic))try{let m=n({args:c,session:p,adapter:i,context:o});m instanceof Promise&&m.catch(Re)}catch(m){Re(m)}},"handler"),a.on(e,s)},(o,i)=>{let a=s;return a&&(s=null,g().getClient().then(c=>c.off(e,a))),i}]}r(B,"createSessionSubscriber");function Be(){return B("evm","session_update",async({args:t,session:e,adapter:n,context:s})=>{t.params.namespaces.eip155&&n.cacheSession("evm",{...e,namespaces:t.params.namespaces});let o=pe(t);if(!o.length)return;let i=o.map(d=>({address:d.accounts[0],chainId:d.chainId})),[a,c]=s.state(),p=a().network,m=await I(await n.getClient()),l=E(p??void 0)??m,f=C(i,l);if(f.length||(f=C(i)),!f.length)return;let h=S(f[0].chainId);c("accounts",Ue.formatAccountsToCAIP([f[0].accounts[0]],h)),c("network",h)})}r(Be,"sessionUpdateSubscriber");function xt(t){return(Array.isArray(t)?t:[t]).filter(e=>typeof e=="string"&&!!e).map(ce)}r(xt,"eventAccounts");function Oe(){return B("evm","session_event",({args:t,adapter:e,context:n})=>{let[,s]=n.state();if(t.params.event.name==="accountsChanged"){let o=xt(t.params.event.data);if(!o.length){n.action("disconnect");return}let i=S(Pt.parse(t.params.chainId).reference);s("network",i),s("accounts",Ue.formatAccountsToCAIP(o,i));return}if(t.params.event.name==="chainChanged"){let o=S(t.params.event.data);s("network",o),e.getClient().then(async i=>A(i,o))}})}r(Oe,"sessionEventSubscriber");function De(){return B("evm","session_delete",({args:t,adapter:e,context:n})=>{e.clearSession("evm"),e.getClient().then(async s=>w(s,t.topic)),n.action("disconnect")})}r(De,"sessionDeleteSubscriber");var[kt,Le]=Be(),[Rt,je]=Oe(),[Ut,Fe]=De(),Bt=O.connect().action(async function(t,e){let n=g(),s=e?E(e):void 0,o=await n.ensureConnectedToChain(e),i=s??await n.resolveActiveChainReference();if(!i)throw new Error("Unable to determine EVM chain id from WalletConnect session.");let a=T(o),c=C(a,i);if(!c.length)throw new Error("No EVM accounts found in WalletConnect session.");return{accounts:_t.formatAccountsToCAIP(c.map(p=>p.accounts[0]),i),network:S(i)}}).before(kt).before(Rt).before(Ut).or(Le).or(je).or(Fe).or((t,e)=>(g().disconnectSession("evm"),e)).or(Wt).build(),Ot=O.canEagerConnect().action(async()=>g().tryRestoreEagerSession("evm")).build(),Dt=O.canSwitchNetwork().action(Mt.canSwitchNetwork()).build(),Ht=He.disconnect().before(async()=>{await g().disconnectSession("evm")}).after(Le).after(je).after(Fe).build(),Lt=O.getChainId().action(async()=>g().getCurrentChainId()).build(),Ke=new bt("EVM",x).action(Bt).action(Ot).action(Dt).action(Ht).action(Lt).build();var Ve=r(()=>new jt(x).init(function(t,e){let[,n]=t.state();e.WC_PROJECT_ID&&(We(new U({projectId:e.WC_PROJECT_ID,meta:e.meta||[],disableModalLink:e.DISABLE_MODAL_AND_OPEN_LINK,themeMode:e.themeMode,modalZIndex:e.modalZIndex})),n("installed",!0),console.debug("[wallet-connect-2] provider initialized.",t))}).config("metadata",ke).add("evm",Ke).build(),"buildProvider");var Cr=r(()=>Ft().version("1.0.0",Ve()).build(),"versions");export{x as WALLET_ID,Cr as versions};
|
|
2
2
|
//# sourceMappingURL=mod.js.map
|
package/dist/mod.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/mod.ts", "../src/provider.ts", "../src/adapter/adapter.ts", "../src/session/evm-chain.ts", "../src/session/accounts.ts", "../src/session/chain-state.ts", "../src/session/evm.ts", "../src/session/lifecycle.ts", "../src/adapter/modal.ts", "../src/adapter/networks.ts", "../src/session/bip122.ts", "../src/session/lookup.ts", "../src/session/proposals.ts", "../src/session/teardown.ts", "../src/session/restore-cache.ts", "../src/adapter/modal-cache.ts", "../src/adapter/provider-client.ts", "../src/adapter/session-cache.ts", "../src/adapter/task-queue.ts", "../src/adapter/registry.ts", "../src/constants.ts", "../src/signer.ts", "../src/namespaces/evm/namespace.ts", "../src/namespaces/evm/hooks.ts", "../src/namespaces/subscriber.ts"],
|
|
4
|
-
"sourcesContent": ["import { defineVersions } from '@hub3js/core/utils';\n\nimport { buildProvider } from './provider.js';\n\nexport type { Environments } from './types.js';\n\nconst versions = () =>\n defineVersions().version('1.0.0', buildProvider()).build();\n\nexport { versions };\n", "import type { Environments } from './types.js';\n\nimport { ProviderBuilder } from '@hub3js/core';\n\nimport { WalletConnectAdapter } from './adapter/adapter.js';\nimport { setAdapter } from './adapter/registry.js';\nimport { metadata, WALLET_ID } from './constants.js';\nimport { evm } from './namespaces/evm/namespace.js';\n\nconst buildProvider = () =>\n new ProviderBuilder(WALLET_ID)\n .init(function (context, environments: Environments) {\n const [, setState] = context.state();\n\n if (!environments.WC_PROJECT_ID) {\n return;\n }\n\n setAdapter(\n new WalletConnectAdapter({\n projectId: environments.WC_PROJECT_ID,\n meta: environments.meta || [],\n disableModalLink: environments.DISABLE_MODAL_AND_OPEN_LINK,\n themeMode: environments.themeMode,\n modalZIndex: environments.modalZIndex,\n })\n );\n setState('installed', true);\n console.debug('[wallet-connect-2] provider initialized.', context);\n })\n .config('metadata', metadata)\n .add('evm', evm)\n .build();\n\nexport { buildProvider };\n", "import type { WalletConnectNamespace } from '../types.js';\nimport type { Chain } from '@hub3js/evm';\nimport type { SessionTypes } from '@walletconnect/types';\nimport type UniversalProvider from '@walletconnect/universal-provider';\nimport type { BlockchainMeta } from 'rango-types';\n\nimport { debug } from '@rango-dev/logging-core';\n\nimport {\n ensureConnectedToChain as ensureConnectedToChainHelper,\n getCurrentChainId as getCurrentChainIdHelper,\n resolveActiveChainReference as resolveActiveChainReferenceHelper,\n switchEvmNetwork as switchEvmNetworkHelper,\n} from '../session/evm-chain.js';\nimport {\n connectWalletConnectSession,\n prepareWalletConnectNamespace,\n} from '../session/lifecycle.js';\nimport { restoreAndCacheSession } from '../session/restore-cache.js';\nimport { removeSessionRecord } from '../session/teardown.js';\nimport { evmMetaToCaipChainIds } from '../utils.js';\n\nimport { ModalCache } from './modal-cache.js';\nimport { createUniversalProvider } from './provider-client.js';\nimport { createSessionCache } from './session-cache.js';\nimport { TaskQueue } from './task-queue.js';\n\n/**\n * Central coordinator for WalletConnect sessions used by hub EVM/UTXO namespaces.\n *\n * Owns provider state (client, session cache, modal) and delegates protocol/domain\n * logic to `session/*` helpers.\n */\nexport interface WalletConnectAdapterConfig {\n projectId: string;\n meta: BlockchainMeta[];\n disableModalLink?: string;\n themeMode?: 'light' | 'dark';\n modalZIndex?: number;\n}\n\nexport class WalletConnectAdapter {\n readonly #projectId: string;\n readonly #disableModalLink?: string;\n readonly #themeMode?: 'light' | 'dark';\n readonly #modalZIndex?: number;\n readonly #meta: BlockchainMeta[];\n #universalProvider: UniversalProvider | null = null;\n #universalProviderPromise: Promise<UniversalProvider> | null = null;\n\n readonly #cache = createSessionCache();\n readonly #modalCache = new ModalCache();\n\n /**\n * Serializes everything that mutates WalletConnect session state.\n *\n * Connecting and disconnecting must never overlap: tearing a session down also\n * deletes its pairing, and an overlapping connect has already minted a new one\n * by then - the teardown unsubscribes it, so `wc_proposeSession` publishes to a\n * topic we no longer listen on and the relay answers\n * `Topic repository: AlreadyExists`.\n *\n * The hub can't order this for us: `useHubAdapter.disconnect` drops the\n * promises `namespace.disconnect()` returns (it iterates with `forEach`), so it\n * resolves while teardown is still in flight and never joins the queue that\n * serializes `connect`.\n *\n * The cost is that a connect holds the queue for its whole lifetime, including\n * the wait for the user to approve in their wallet, so a disconnect raised\n * meanwhile waits its turn instead of interleaving. That is deliberate rather\n * than an oversight: the pairing has to survive from `client.connect()` through\n * settle, which is exactly the span being protected.\n */\n readonly #sessionQueue = new TaskQueue();\n\n constructor(config: WalletConnectAdapterConfig) {\n this.#projectId = config.projectId;\n this.#meta = config.meta;\n this.#disableModalLink = config.disableModalLink;\n this.#themeMode = config.themeMode;\n this.#modalZIndex = config.modalZIndex;\n }\n\n async getUniversalProvider(): Promise<UniversalProvider> {\n /*\n * Memoize the in-flight promise, not the resolved value. A namespace's\n * `before` subscribers are invoked with `forEach` (nothing awaits between\n * them), so several reach this method in the same tick - awaiting first and\n * assigning after would let each start its own `UniversalProvider`, leaving\n * several SignClients sharing one storage. The extra clients answer relay\n * traffic for a handshake they never made (\"Pending session not found for\n * topic X\", then \"No matching key. session topic doesn't exist: X\").\n */\n if (!this.#universalProviderPromise) {\n this.#universalProviderPromise = createUniversalProvider(this.#projectId)\n .then((provider) => {\n this.#universalProvider = provider;\n return provider;\n })\n .catch((error: unknown) => {\n // Don't cache a failed init - let the next caller retry.\n this.#universalProviderPromise = null;\n throw error;\n });\n }\n\n return this.#universalProviderPromise;\n }\n\n async getClient() {\n return (await this.getUniversalProvider()).client;\n }\n\n getSession(namespace: WalletConnectNamespace): SessionTypes.Struct | null {\n return this.#cache.get(namespace);\n }\n\n cacheSession(\n namespace: WalletConnectNamespace,\n session: SessionTypes.Struct\n ) {\n this.#cache.set(namespace, session);\n }\n\n clearSession(namespace: WalletConnectNamespace) {\n this.#cache.clear(namespace);\n }\n\n clearAllSessions() {\n this.#cache.clearAll();\n }\n\n async tryRestoreEagerSession(\n namespace: WalletConnectNamespace\n ): Promise<boolean> {\n return this.#sessionQueue.run(async () => {\n const client = await this.getClient();\n return !!(await restoreAndCacheSession(\n client,\n namespace,\n this.#cache,\n { validateAccounts: true },\n async (targetNamespace) =>\n this.#disconnectSessionQueued(targetNamespace)\n ));\n });\n }\n\n async ensureSession(options: {\n namespace: WalletConnectNamespace;\n chainReference?: string;\n }): Promise<SessionTypes.Struct> {\n return this.#sessionQueue.run(async () =>\n this.#ensureSessionQueued(options)\n );\n }\n\n async disconnectSession(namespace: WalletConnectNamespace) {\n return this.#sessionQueue.run(async () =>\n this.#disconnectSessionQueued(namespace)\n );\n }\n\n async resolveActiveChainReference(): Promise<string | undefined> {\n const session = this.getSession('evm');\n if (!session) {\n return undefined;\n }\n\n return resolveActiveChainReferenceHelper(await this.getClient(), session);\n }\n\n async getCurrentChainId(): Promise<`0x${string}`> {\n const session = this.getSession('evm');\n if (!session) {\n throw new Error(\n 'Unable to determine EVM chain id from WalletConnect session.'\n );\n }\n\n return getCurrentChainIdHelper(await this.getClient(), session);\n }\n\n async ensureConnectedToChain(\n chain?: string | Chain\n ): Promise<SessionTypes.Struct> {\n return ensureConnectedToChainHelper(this.#evmChainDeps(), chain);\n }\n\n async switchEvmNetwork(\n requestedChainId: string,\n currentChainId: string\n ): Promise<void> {\n const session = this.getSession('evm');\n if (!session) {\n throw new Error('WalletConnect session is not available.');\n }\n\n this.cacheSession(\n 'evm',\n await switchEvmNetworkHelper({\n client: await this.getClient(),\n session,\n meta: this.#meta,\n requestedChainId,\n currentChainId,\n })\n );\n }\n\n /*\n * The `Queued` suffix means \"already running inside `#sessionQueue`\". These\n * call each other directly and must never go back through the public methods\n * above: re-entering the queue from inside a task would wait for a turn that\n * cannot come until that same task finishes, which deadlocks.\n */\n\n async #ensureSessionQueued(options: {\n namespace: WalletConnectNamespace;\n chainReference?: string;\n }): Promise<SessionTypes.Struct> {\n const { namespace, chainReference } = options;\n const client = await this.getClient();\n const restored = await restoreAndCacheSession(\n client,\n namespace,\n this.#cache,\n undefined,\n async (targetNamespace) => this.#disconnectSessionQueued(targetNamespace)\n );\n if (restored) {\n return restored;\n }\n\n await prepareWalletConnectNamespace(client, namespace);\n\n const universalProvider = await this.getUniversalProvider();\n await universalProvider.cleanupPendingPairings().catch(() => undefined);\n\n const session = await connectWalletConnectSession(\n client,\n this.#modalCache.getModal({\n projectId: this.#projectId,\n universalProvider,\n themeMode: this.#themeMode,\n zIndex: this.#modalZIndex,\n }),\n {\n chains: evmMetaToCaipChainIds(this.#meta),\n envs: {\n WC_PROJECT_ID: this.#projectId,\n DISABLE_MODAL_AND_OPEN_LINK: this.#disableModalLink,\n },\n namespace,\n chainReference,\n }\n );\n\n this.#cache.set(namespace, session);\n return session;\n }\n\n async #disconnectSessionQueued(namespace: WalletConnectNamespace) {\n const session = this.getSession(namespace);\n if (this.#universalProvider?.client && session) {\n await removeSessionRecord(this.#universalProvider.client, session).catch(\n (error) => debug(error)\n );\n }\n this.clearSession(namespace);\n if (session) {\n this.#cache.clearTopic(session.topic);\n }\n }\n\n #evmChainDeps() {\n return {\n meta: this.#meta,\n getSession: (namespace: 'evm') => this.getSession(namespace),\n cacheSession: (namespace: 'evm', session: SessionTypes.Struct) =>\n this.cacheSession(namespace, session),\n getClient: async () => this.getClient(),\n ensureSession: async (options: {\n namespace: 'evm';\n chainReference?: string;\n }) => this.ensureSession(options),\n };\n }\n}\n", "import type { Chain } from '@hub3js/evm';\nimport type { ISignClient, SessionTypes } from '@walletconnect/types';\nimport type { BlockchainMeta } from 'rango-types';\n\nimport { error as logError } from '@rango-dev/logging-core';\nimport { ChainId } from 'caip';\n\nimport {\n chainReferenceToHex,\n parseChainReference,\n resolveNetworkName,\n} from '../utils.js';\nimport { EthereumRPCMethods, NAMESPACES } from '../wcConstants.js';\n\nimport { getAccountsFromSession } from './accounts.js';\nimport { getPersistedChainId, persistCurrentChainId } from './chain-state.js';\nimport {\n filterEvmAccounts,\n ignoreNamespaceMethods,\n switchOrAddEvmChain,\n updateSessionAccounts,\n} from './evm.js';\n\nexport type EvmChainDeps = {\n meta: BlockchainMeta[];\n getSession: (namespace: 'evm') => SessionTypes.Struct | null;\n cacheSession: (namespace: 'evm', session: SessionTypes.Struct) => void;\n getClient: () => Promise<ISignClient>;\n ensureSession: (options: {\n namespace: 'evm';\n chainReference?: string;\n }) => Promise<SessionTypes.Struct>;\n};\n\nexport async function resolveActiveChainReference(\n client: ISignClient,\n session: SessionTypes.Struct\n): Promise<string | undefined> {\n const persistedChainId = await getPersistedChainId(client);\n if (persistedChainId) {\n return persistedChainId;\n }\n\n const accounts = getAccountsFromSession(session);\n const evmAccounts = filterEvmAccounts(accounts);\n return evmAccounts[0]?.chainId;\n}\n\nexport async function getCurrentChainId(\n client: ISignClient,\n session: SessionTypes.Struct\n): Promise<`0x${string}`> {\n const reference = await resolveActiveChainReference(client, session);\n if (!reference) {\n throw new Error(\n 'Unable to determine EVM chain id from WalletConnect session.'\n );\n }\n\n return chainReferenceToHex(reference);\n}\n\n/**\n * Returns the session to keep using: `updateSessionAccounts` may rebuild it, and\n * the caller's copy is stale from that point on.\n */\nexport async function switchEvmNetwork(options: {\n client: ISignClient;\n session: SessionTypes.Struct;\n meta: BlockchainMeta[];\n requestedChainId: string;\n currentChainId: string;\n}): Promise<SessionTypes.Struct> {\n const { client, session, meta, requestedChainId, currentChainId } = options;\n\n const requestedReference = parseChainReference(requestedChainId);\n if (!requestedReference) {\n const error = new Error(`There is no match for ${requestedChainId}`);\n logError(error);\n throw error;\n }\n\n const chainIdStr = new ChainId({\n namespace: NAMESPACES.ETHEREUM,\n reference: requestedReference,\n }).toString();\n\n const requestedNetwork = resolveNetworkName(requestedChainId, meta);\n const currentNetwork = resolveNetworkName(currentChainId, meta);\n\n const evmNamespace = session.namespaces[NAMESPACES.ETHEREUM];\n const authorizedChains = evmNamespace?.chains || [];\n const authorizedMethods = evmNamespace?.methods || [];\n let activeSession = session;\n\n if (\n authorizedMethods.includes(EthereumRPCMethods.SWITCH_CHAIN) &&\n !ignoreNamespaceMethods(session)\n ) {\n if (!requestedNetwork || !currentNetwork) {\n const error = new Error(`Chain ${requestedReference} is not configured.`);\n logError(error);\n throw error;\n }\n\n activeSession = await updateSessionAccounts(\n client,\n session,\n requestedNetwork,\n currentNetwork,\n meta\n );\n await switchOrAddEvmChain(\n client,\n activeSession,\n meta,\n requestedNetwork,\n currentNetwork\n );\n } else if (!authorizedChains.includes(chainIdStr)) {\n const error = new Error(`Chain ${requestedReference} is not configured.`);\n logError(error);\n throw error;\n }\n\n await persistCurrentChainId(client, requestedReference);\n return activeSession;\n}\n\nexport async function switchToChainIfNeeded(\n deps: EvmChainDeps,\n requestedReference: string\n): Promise<void> {\n const session = deps.getSession('evm');\n if (!session) {\n throw new Error('WalletConnect session is not available.');\n }\n\n const client = await deps.getClient();\n const currentReference = await resolveActiveChainReference(client, session);\n if (currentReference === requestedReference) {\n await persistCurrentChainId(client, requestedReference);\n return;\n }\n\n const currentChainId = currentReference\n ? chainReferenceToHex(currentReference)\n : chainReferenceToHex(requestedReference);\n\n deps.cacheSession(\n 'evm',\n await switchEvmNetwork({\n client,\n session,\n meta: deps.meta,\n requestedChainId: requestedReference,\n currentChainId,\n })\n );\n}\n\nexport async function ensureConnectedToChain(\n deps: EvmChainDeps,\n chain?: string | Chain\n): Promise<SessionTypes.Struct> {\n const requestedReference = chain ? parseChainReference(chain) : undefined;\n\n if (!deps.getSession('evm')) {\n await deps.ensureSession({\n namespace: 'evm',\n chainReference: requestedReference,\n });\n }\n\n if (requestedReference) {\n await switchToChainIfNeeded(deps, requestedReference);\n }\n\n const session = deps.getSession('evm');\n if (!session) {\n throw new Error('WalletConnect session is not available.');\n }\n\n return session;\n}\n", "import type { SessionTypes, SignClientTypes } from '@walletconnect/types';\n\nimport { AccountId } from 'caip';\n\n/**\n * `accountsChanged` entries are CAIP-10 (`eip155:1:0x\u2026`) from wallets that follow\n * WC and a bare `0x\u2026` from the ones forwarding the EIP-1193 payload as-is.\n */\nexport function extractAddress(account: string): string {\n return account.includes(':') ? new AccountId(account).address : account;\n}\n\nexport function getAccountsFromSession(session: SessionTypes.Struct) {\n const accounts = Object.values(session.namespaces)\n .map((namespace) => namespace.accounts)\n .flat()\n .map((account) => {\n const { address, chainId } = new AccountId(account);\n return {\n address,\n chainId: chainId.reference,\n };\n });\n return accounts;\n}\n\nexport function getAccountsFromEvent(\n event: SignClientTypes.BaseEventArgs<{\n namespaces: SessionTypes.Namespaces;\n }>\n) {\n const accounts = Object.values(event.params.namespaces)\n .map((namespace) => namespace.accounts)\n .flat()\n .map((account) => {\n const { address, chainId } = new AccountId(account);\n return {\n accounts: [address],\n chainId: chainId.reference,\n };\n });\n\n return accounts;\n}\n", "import type { ISignClient } from '@walletconnect/types';\nimport type { BlockchainMeta } from 'rango-types';\n\nimport { CHAIN_ID_STORAGE } from '../wcConstants.js';\n\nexport async function persistCurrentChainId(\n client: ISignClient,\n chainId?: string\n) {\n return client.core.storage.setItem(CHAIN_ID_STORAGE, {\n defaultChainId: chainId ? parseInt(chainId) : '',\n });\n}\n\nexport async function getPersistedChainId(client: ISignClient) {\n try {\n const chainId = (await client.core.storage.getItem(CHAIN_ID_STORAGE))\n ?.defaultChainId;\n return !!chainId ? String(chainId) : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function getChainIdByNetworkName(\n network: string,\n meta: BlockchainMeta[]\n): string | undefined {\n const targetBlockchain = meta.find(\n (blockchain) => blockchain.name === network\n );\n const chainIdInHex = targetBlockchain?.chainId;\n if (!chainIdInHex) {\n return undefined;\n }\n\n return String(parseInt(chainIdInHex));\n}\n", "import type { ISignClient, SessionTypes } from '@walletconnect/types';\nimport type { BlockchainMeta } from 'rango-types';\n\nimport { debug } from '@rango-dev/logging-core';\nimport {\n convertEvmBlockchainMetaToEvmChainInfo,\n isEvmAddress,\n} from '@rango-dev/wallets-shared';\nimport { AccountId, ChainId } from 'caip';\nimport { isEvmBlockchain } from 'rango-types';\n\nimport { EthereumRPCMethods, NAMESPACES } from '../wcConstants.js';\n\nimport { getChainIdByNetworkName } from './chain-state.js';\n\nexport function getCurrentEvmAccountAddress(\n session: SessionTypes.Struct\n): string | undefined {\n return session.namespaces[NAMESPACES.ETHEREUM]?.accounts\n ?.map((account) => new AccountId(account).address)\n ?.filter((address) => isEvmAddress(address))?.[0];\n}\n\nexport function getEvmAccount(\n network: string,\n address: string,\n meta: BlockchainMeta[]\n): string | undefined {\n const currentChainId = getChainIdByNetworkName(network, meta);\n if (!currentChainId) {\n return undefined;\n }\n\n return AccountId.format({\n chainId: {\n namespace: NAMESPACES.ETHEREUM,\n reference: currentChainId,\n },\n address,\n });\n}\n\n// It's enough to return only connected network for the EVM networks and ignore others\nexport function filterEvmAccounts(\n accounts: {\n address: string;\n chainId: string;\n }[],\n currentChainId?: string\n) {\n let firstEvmAddress = false;\n return accounts\n .filter(({ address, chainId }) => {\n const isEvm = isEvmAddress(address);\n if (!isEvm) {\n return false;\n }\n if (currentChainId && chainId !== currentChainId) {\n return false;\n }\n if (!currentChainId) {\n if (firstEvmAddress) {\n return false;\n }\n firstEvmAddress = true;\n }\n return true;\n })\n .map(({ address, chainId }) => ({\n accounts: [address],\n chainId: chainId,\n }));\n}\n\nexport async function switchOrAddEvmChain(\n client: ISignClient,\n session: SessionTypes.Struct,\n meta: BlockchainMeta[],\n requestedNetwork: string,\n currentNetwork: string\n) {\n const evmBlockchains = meta.filter(isEvmBlockchain);\n const evmNetworksChainInfo =\n convertEvmBlockchainMetaToEvmChainInfo(evmBlockchains);\n const targetChain = evmNetworksChainInfo[requestedNetwork];\n const targetBlockchain = meta.find(\n (blockchain: BlockchainMeta) => blockchain.name === requestedNetwork\n );\n const chainIdInHex = targetBlockchain?.chainId;\n\n const currentChainId = getChainIdByNetworkName(currentNetwork, meta);\n const currentChainEip = ChainId.format({\n namespace: NAMESPACES.ETHEREUM,\n reference: String(currentChainId),\n });\n\n try {\n await client.request({\n topic: session.topic,\n request: {\n method: EthereumRPCMethods.SWITCH_CHAIN,\n params: [\n {\n chainId: chainIdInHex,\n },\n ],\n },\n // It's required to pass current chain, otherwise it won't work\n chainId: currentChainEip,\n });\n } catch (err) {\n // EIP-1193 \"Unrecognized chain ID\" - the wallet doesn't have this chain yet.\n const addChainError = 4902;\n const { code, message } = (err ?? {}) as {\n code?: number;\n message?: string;\n };\n if (code === addChainError || message?.includes(String(addChainError))) {\n await client.request({\n topic: session.topic,\n request: {\n method: EthereumRPCMethods.ADD_CHAIN,\n params: [targetChain],\n },\n // It's required to pass current chain, otherwise it won't work\n chainId: currentChainEip,\n });\n } else {\n throw err;\n }\n }\n}\n\n/**\n * Adds the requested and current chains' accounts to the session so sign-client\n * accepts a request carrying their CAIP chain id, and returns the session to use\n * from here on.\n *\n * The record is rebuilt rather than pushed into: the struct is shared with the\n * store and the adapter cache, and the write below can fail (it is logged, not\n * thrown), which would otherwise leave both holding accounts the store never\n * accepted.\n */\nexport async function updateSessionAccounts(\n client: ISignClient,\n session: SessionTypes.Struct,\n requestedNetwork: string,\n currentNetwork: string,\n meta: BlockchainMeta[]\n): Promise<SessionTypes.Struct> {\n const evmNamespace = session.namespaces[NAMESPACES.ETHEREUM];\n const currentAccountAddress = getCurrentEvmAccountAddress(session);\n if (!evmNamespace || !currentAccountAddress) {\n return session;\n }\n\n const existing = evmNamespace.accounts ?? [];\n const wanted = [\n getEvmAccount(requestedNetwork, currentAccountAddress, meta),\n getEvmAccount(currentNetwork, currentAccountAddress, meta),\n ].filter(\n (account): account is string => !!account && !existing.includes(account)\n );\n\n if (!wanted.length) {\n return session;\n }\n\n const updated: SessionTypes.Struct = {\n ...session,\n namespaces: {\n ...session.namespaces,\n [NAMESPACES.ETHEREUM]: {\n ...evmNamespace,\n accounts: [...existing, ...new Set(wanted)],\n },\n },\n };\n\n try {\n await client.session.update(session.topic, {\n namespaces: updated.namespaces,\n });\n } catch (err) {\n debug(err instanceof Error ? err : new Error(String(err)));\n return session;\n }\n\n return updated;\n}\n\nexport function ignoreNamespaceMethods(session: SessionTypes.Struct): boolean {\n const WALLETS_WITH_WRONG_NAMESPACE_METHODS = ['trust', '1inch'];\n const peerName = session.peer?.metadata?.name;\n return WALLETS_WITH_WRONG_NAMESPACE_METHODS.some((name) =>\n peerName?.toLowerCase()?.includes(name)\n );\n}\n", "import type { AppKitModal } from '../adapter/modal.js';\nimport type {\n ConnectParams,\n CreateSessionParams,\n Environments,\n SignClientInstance,\n WalletConnectNamespace,\n} from '../types.js';\nimport type { ISignClient, SessionTypes } from '@walletconnect/types';\nimport type UniversalProvider from '@walletconnect/universal-provider';\n\nimport { debug } from '@rango-dev/logging-core';\nimport { timeout } from '@rango-dev/wallets-shared';\n\nimport { prepareModalForNamespace } from '../adapter/modal.js';\nimport { PING_TIMEOUT, WC_NAMESPACE_TO_CAIP } from '../wcConstants.js';\n\nimport { getAccountsFromSession } from './accounts.js';\nimport { filterBip122Accounts, resolveBip122Session } from './bip122.js';\nimport { getPersistedChainId } from './chain-state.js';\nimport { filterEvmAccounts } from './evm.js';\nimport { findSessionByNamespace } from './lookup.js';\nimport { generateOptionalNamespace } from './proposals.js';\nimport {\n cleanupStaleSessionsForNamespace,\n hasActivePairing,\n hasActiveSession,\n purgeOrphanedPairings,\n purgeOrphanedSessions,\n removeSessionRecord,\n} from './teardown.js';\n\nexport type RestoreWalletConnectSessionOptions = {\n validateAccounts?: boolean;\n};\n\nexport async function restoreWalletConnectSession(\n client: SignClientInstance,\n namespace: WalletConnectNamespace,\n options: RestoreWalletConnectSessionOptions = {}\n): Promise<SessionTypes.Struct | undefined> {\n const session = await restoreNamespaceSession(client, namespace);\n if (!session) {\n return undefined;\n }\n\n /*\n * Never wait for `bip122_addressesChanged` here. The wallet only emits it just\n * after approval, so a stored session that still has no account will never be\n * given one - waiting would stall for the full timeout and fail anyway. Report\n * it as unrestorable instead and let the caller negotiate a fresh session.\n */\n if (namespace === 'utxo' && filterBip122Accounts(session).length === 0) {\n return undefined;\n }\n\n if (options.validateAccounts) {\n const isValid = await hasNamespaceAccounts(client, namespace, session);\n if (!isValid) {\n return undefined;\n }\n }\n\n return session;\n}\n\nasync function hasNamespaceAccounts(\n client: SignClientInstance,\n namespace: WalletConnectNamespace,\n session: SessionTypes.Struct\n): Promise<boolean> {\n if (namespace === 'utxo') {\n return filterBip122Accounts(session).length > 0;\n }\n\n const accounts = getAccountsFromSession(session);\n const currentChainId = await getPersistedChainId(client);\n return filterEvmAccounts(accounts, currentChainId).length > 0;\n}\n\n/**\n * Ping the session topic and return it if still valid.\n * Returns undefined (instead of throwing) when storage contains stale records.\n */\nexport async function restoreNamespaceSession(\n client: SignClientInstance,\n namespace: WalletConnectNamespace\n): Promise<SessionTypes.Struct | undefined> {\n const session = findSessionByNamespace(client, namespace);\n if (!session?.topic) {\n return undefined;\n }\n\n if (!hasActiveSession(client, session.topic)) {\n await removeSessionRecord(client, session);\n return undefined;\n }\n\n if (session.pairingTopic && !hasActivePairing(client, session.pairingTopic)) {\n await removeSessionRecord(client, session);\n return undefined;\n }\n\n try {\n await timeout(\n client.ping({\n topic: session.topic,\n }),\n PING_TIMEOUT\n );\n } catch (error) {\n debug(error instanceof Error ? error : new Error(String(error)));\n await removeSessionRecord(client, session);\n return undefined;\n }\n\n return findSessionByNamespace(client, namespace) ?? session;\n}\n\n/**\n * Clears unusable records ahead of a connect: orphaned sessions across every\n * namespace, plus `namespace`'s own stale ones.\n *\n * A *live* session belonging to another namespace is deliberately left alone -\n * EVM and UTXO each own an independent session, and only the namespace being\n * disconnected drops its own.\n */\nexport async function prepareWalletConnectNamespace(\n client: UniversalProvider['client'],\n namespace: WalletConnectNamespace\n): Promise<void> {\n await purgeOrphanedSessions(client);\n await cleanupStaleSessionsForNamespace(client, namespace);\n await purgeOrphanedPairings(client);\n}\n\n/**\n * Restores `namespace`'s session, or negotiates a new one.\n *\n * Callers are expected to have run {@link prepareWalletConnectNamespace} first -\n * this does not clean up on its own.\n */\nexport async function connectWalletConnectSession(\n client: UniversalProvider['client'],\n web3Modal: AppKitModal,\n params: ConnectParams\n): Promise<SessionTypes.Struct> {\n const { chains, namespace, chainReference } = params;\n\n const restored = await restoreWalletConnectSession(client, namespace);\n if (restored) {\n return restored;\n }\n\n const proposal = generateOptionalNamespace(\n chains,\n [namespace],\n chainReference\n );\n const session = await createSession(\n client,\n web3Modal,\n { optionalNamespaces: proposal ?? {} },\n {\n envs: params.envs,\n namespace,\n }\n );\n\n /*\n * Only a just-approved session can be waited on: bitcoin wallets routinely\n * approve bip122 with no account and send it moments later. A restored session\n * never reaches here, so the wait can't be spent on one that will never\n * receive the event.\n */\n if (namespace === 'utxo') {\n return resolveBip122Session(client, session);\n }\n\n return session;\n}\n\nasync function createSession(\n client: ISignClient,\n web3Modal: AppKitModal,\n options: CreateSessionParams,\n configs: {\n envs: Environments;\n namespace: WalletConnectNamespace;\n }\n): Promise<SessionTypes.Struct> {\n const { optionalNamespaces, pairingTopic } = options;\n\n try {\n const { uri, approval } = await client.connect({\n optionalNamespaces,\n pairingTopic,\n });\n\n let onCloseModal;\n if (uri) {\n const redirectLink = configs.envs.DISABLE_MODAL_AND_OPEN_LINK;\n if (redirectLink) {\n const url = `${redirectLink}/wc?uri=${encodeURIComponent(uri)}`;\n window.open(url, '_blank', 'noreferrer noopener');\n } else {\n await prepareModalForNamespace(web3Modal, configs.namespace);\n /*\n * `namespace` scopes the wallet list AppKit renders. It isn't in\n * AppKit's `OpenOptions` type but is honored at runtime, so it goes\n * through a pre-built object (an inline literal would trip the\n * excess-property check). `WC_NAMESPACE_TO_CAIP` is the single source\n * for the alias -> CAIP prefix instead of sniffing the payload keys.\n */\n const openOptions = {\n uri,\n namespace: WC_NAMESPACE_TO_CAIP[configs.namespace],\n };\n await web3Modal.open(openOptions);\n\n onCloseModal = new Promise((_, reject) => {\n web3Modal.subscribeState((state) => {\n if (!state.open) {\n reject(new Error('Modal has been closed.'));\n }\n });\n });\n }\n }\n\n const session = approval();\n\n if (onCloseModal) {\n const result = await Promise.race([session, onCloseModal]);\n return result as SessionTypes.Struct;\n }\n return await session;\n } finally {\n void web3Modal.close();\n }\n}\n", "import type { WalletConnectNamespace } from '../types.js';\nimport type { AppKitNetwork } from '@reown/appkit-common';\nimport type UniversalProvider from '@walletconnect/universal-provider';\n\nimport { createAppKit } from '@reown/appkit/core';\n\nimport { bitcoin, mainnet } from './networks.js';\n\nexport type AppKitModal = ReturnType<typeof createAppKitModal>;\n\nconst DEFAULT_MODAL_Z_INDEX = 999_999_999;\n\nexport type ModalParams = {\n projectId: string;\n universalProvider: UniversalProvider;\n themeMode?: 'light' | 'dark';\n zIndex?: number;\n};\n\n/*\n * Every WalletConnect namespace shares one AppKit instance with all networks\n * registered up front. A per-namespace instance had to be rebuilt on each\n * switch, and every rebuild re-ran AppKit init against its module-level\n * singleton controllers - leaving router history from the previous open mixed\n * into the next (a stray back button in the modal header). The active network\n * is chosen per connect with `switchNetwork` instead.\n *\n * The active network is now shared mutable state, so this is only safe while\n * connects are serialized (the adapter's `#sessionQueue`): the switch/open/close\n * for one namespace never interleaves with another's. A connect path that\n * bypassed that queue would race this switch.\n */\nconst NETWORKS: [AppKitNetwork, ...AppKitNetwork[]] = [mainnet, bitcoin];\n\n/**\n * The network to make active before opening the modal for a namespace. Keyed by\n * `WalletConnectNamespace` so a future namespace is a compile error until mapped.\n */\nconst NAMESPACE_NETWORK: Record<WalletConnectNamespace, AppKitNetwork> = {\n evm: mainnet,\n utxo: bitcoin,\n};\n\n/**\n * Make a namespace's network active before opening the shared modal.\n *\n * `open()` compares the requested namespace against AppKit's active chain: if\n * they differ it treats the open as a network switch and pushes an extra step\n * onto the router, which leaves a stray back button in the modal header. One\n * shared instance keeps whatever chain the previous connect left active, so we\n * switch it to the target here first - then `open()` sees a matching chain and\n * takes its clean, non-switching path.\n *\n * `ready()` first so AppKit init has registered the networks `switchNetwork`\n * looks up.\n */\nexport async function prepareModalForNamespace(\n web3Modal: AppKitModal,\n namespace: WalletConnectNamespace\n): Promise<void> {\n await web3Modal.ready();\n await web3Modal.switchNetwork(NAMESPACE_NETWORK[namespace]);\n}\n\nexport function createAppKitModal({\n projectId,\n universalProvider,\n themeMode = 'light',\n zIndex = DEFAULT_MODAL_Z_INDEX,\n}: ModalParams) {\n return createAppKit({\n projectId,\n networks: NETWORKS,\n universalProvider,\n /*\n * AppKit is intentionally kept out of the WalletConnect session lifecycle -\n * it renders the modal (QR + wallet list), nothing more. We drive the\n * handshake ourselves with `client.connect()` (see `session/lifecycle.ts`).\n *\n * Why: AppKit models one unified, multi-chain session with a single active\n * chain and its own reconnect/sync. The hub needs the opposite - EVM and\n * UTXO as independent sessions that connect, disconnect and eager-restore\n * separately (the adapter keeps one cache entry per namespace). Letting\n * AppKit drive via `provider.connect()` accumulates namespaces into a single\n * proposal, so connecting BTC after EVM asks the wallet for Ethereum - it was\n * tried and reverted. `manualWCControl: true` is AppKit's supported flag for\n * exactly this \"you render, I connect\" split.\n *\n * The visible cost: because we own the lifecycle, `provider.session` is never\n * set. With `enableReconnect: false`, AppKit init runs\n * `unSyncExistingConnection()`, whose `provider.disconnect()` hits a\n * `if (!this.session) throw` guard and AppKit logs the caught error as\n * `UniversalAdapter:disconnect - error: Please call connect() before\n * enable()`. It is expected and harmless - AppKit looking for a session to\n * clean up, finding none.\n *\n * Do NOT \"fix\" the log. Enabling reconnect makes AppKit actively restore/sync\n * connections it doesn't own, racing our own restore path and serialize\n * queue. Assigning `provider.session` removes the guard so that disconnect\n * (and every other AppKit-initiated disconnect) succeeds for real, tearing\n * down a live session on AppKit's schedule instead of ours. Both trade a\n * cosmetic log for real state conflicts.\n */\n enableReconnect: false,\n defaultNetwork: mainnet,\n defaultAccountTypes: { bip122: 'payment' },\n manualWCControl: true,\n /*\n * We register only one EVM network (`mainnet`) but the session approves every\n * EVM chain, so a network switch can land on a chain AppKit considers\n * \"unsupported\" and it auto-opens its UnsupportedChain modal\n * (ChainController.showUnsupportedChainUI). Allow it so AppKit doesn't police\n * the network we manage ourselves.\n */\n allowUnsupportedChain: true,\n themeMode,\n themeVariables: {\n '--apkt-z-index': zIndex,\n },\n });\n}\n", "import type { AppKitNetwork, CaipNetwork } from '@reown/appkit-common';\n\n/*\n * The two networks AppKit renders the modal for, defined here instead of\n * imported from `@reown/appkit/networks`.\n *\n * That entry point is `export * from 'viem/chains'` plus AppKit's own non-EVM\n * chains, so importing a single name off it pulls every viem chain definition\n * into the consumer's bundle. One of them (`tempo`) re-exports viem's tempo\n * chainConfig, which reaches `ox`'s salt-mining worker pool - and that module\n * routes `await import(id)` through a variable so bundlers skip\n * `node:worker_threads` in the browser. webpack can't resolve the expression\n * and warns \"Critical dependency: the request of a dependency is an\n * expression\"; react-scripts promotes warnings to errors on CI, which fails\n * the build for anyone consuming the widget through Create React App.\n *\n * viem publishes no per-chain subpath (`./chains` is the only export), so\n * there is no narrower import to reach for - the definitions are plain data,\n * so we carry the two we need.\n *\n * Keep these in sync with upstream if AppKit's `bitcoin` or viem's `mainnet`\n * changes: `@reown/appkit/dist/esm/src/networks/bitcoin.js` and\n * `viem/_esm/chains/definitions/mainnet.js`.\n */\n\n/**\n * Mirrors `defineChain` from both `viem/chains` and AppKit's networks module -\n * they are the same three-key spread. Declaring the viem-only formatter fields\n * keeps the objects structurally identical to the ones AppKit used to receive.\n */\nfunction defineChain<const chain extends AppKitNetwork>(chain: chain) {\n return {\n formatters: undefined,\n fees: undefined,\n serializers: undefined,\n ...chain,\n };\n}\n\n/** viem's `mainnet`, the only EVM network we register. */\nexport const mainnet = defineChain({\n id: 1,\n caipNetworkId: 'eip155:1',\n chainNamespace: 'eip155',\n name: 'Ethereum',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://eth.merkle.io'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Etherscan',\n url: 'https://etherscan.io',\n apiUrl: 'https://api.etherscan.io/api',\n },\n },\n contracts: {\n ensUniversalResolver: {\n address: '0xeeeeeeee14d718c2b47d9923deab1335e144eeee',\n blockCreated: 23_085_558,\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 14_353_601,\n },\n },\n} satisfies CaipNetwork);\n\n/** AppKit's `bitcoin`, the only UTXO network we register. */\nexport const bitcoin = defineChain({\n id: '000000000019d6689c085ae165831e93',\n caipNetworkId: 'bip122:000000000019d6689c085ae165831e93',\n chainNamespace: 'bip122',\n name: 'Bitcoin',\n nativeCurrency: {\n name: 'Bitcoin',\n symbol: 'BTC',\n decimals: 8,\n },\n rpcUrls: {\n default: { http: ['https://rpc.walletconnect.org/v1'] },\n },\n} satisfies CaipNetwork);\n", "import type { SignClientInstance } from '../types.js';\nimport type { SessionTypes, SignClientTypes } from '@walletconnect/types';\n\nimport { debug } from '@rango-dev/logging-core';\nimport { CAIP_BITCOIN_CHAIN_ID } from '@rango-dev/wallets-core/namespaces/utxo';\nimport { AccountId } from 'caip';\n\nimport { BitcoinEvents, NAMESPACES } from '../wcConstants.js';\n\nexport function getBip122AccountsFromSession(\n session: SessionTypes.Struct\n): string[] {\n return session.namespaces[NAMESPACES.BITCOIN]?.accounts ?? [];\n}\n\nexport function filterBip122Accounts(session: SessionTypes.Struct) {\n return getBip122AccountsFromSession(session).map((account) => ({\n address: new AccountId(account).address,\n }));\n}\n\nexport type Bip122AddressEntry = {\n address: string;\n intention?: 'payment' | 'ordinal';\n};\n\n/**\n * Every address a `bip122_addressesChanged` payload carries, in wallet order.\n * Unlike {@link pickPaymentAddress} it makes no guess about which one is active.\n */\nexport function getAnnouncedAddresses(\n data: Bip122AddressEntry[] | string[] | undefined\n): string[] {\n if (!data?.length) {\n return [];\n }\n\n return data\n .map((entry) => (typeof entry === 'string' ? entry : entry?.address))\n .filter((address): address is string => !!address);\n}\n\nexport function pickPaymentAddress(\n data: Bip122AddressEntry[] | string[] | undefined\n): string | undefined {\n if (!data?.length) {\n return undefined;\n }\n\n const first = data[0];\n if (typeof first === 'string') {\n return first;\n }\n\n const entries = data as Bip122AddressEntry[];\n return (\n entries.find((entry) => entry.intention === 'payment')?.address ??\n entries[0]?.address\n );\n}\n\nexport function patchBip122SessionAccount(\n session: SessionTypes.Struct,\n address: string\n): SessionTypes.Struct {\n const btcNamespace = session.namespaces[NAMESPACES.BITCOIN];\n if (!btcNamespace) {\n return session;\n }\n\n const caipAccount = new AccountId({\n chainId: {\n namespace: NAMESPACES.BITCOIN,\n reference: CAIP_BITCOIN_CHAIN_ID,\n },\n address,\n }).toString();\n\n const accounts = btcNamespace.accounts ?? [];\n const hasAccount = accounts.some(\n (account) =>\n new AccountId(account).address.toLowerCase() === address.toLowerCase()\n );\n\n if (hasAccount) {\n return session;\n }\n\n return {\n ...session,\n namespaces: {\n ...session.namespaces,\n [NAMESPACES.BITCOIN]: {\n ...btcNamespace,\n accounts: [...accounts, caipAccount],\n },\n },\n };\n}\n\nconst BIP122_ACCOUNT_TIMEOUT = 15_000;\n\n/**\n * Bitcoin wallets often approve bip122 without accounts in the session object.\n * They emit bip122_addressesChanged or session_update shortly after approval.\n */\nexport async function resolveBip122Session(\n client: SignClientInstance,\n session: SessionTypes.Struct\n): Promise<SessionTypes.Struct> {\n const existing = filterBip122Accounts(session);\n if (existing.length) {\n return session;\n }\n\n const freshSession = client.session.get(session.topic) ?? session;\n const freshAccounts = filterBip122Accounts(freshSession);\n if (freshAccounts.length) {\n return freshSession;\n }\n\n const { address, session: resolvedSession } =\n await waitForBip122PaymentAddress(client, freshSession);\n\n const patched = patchBip122SessionAccount(resolvedSession, address);\n await persistSessionNamespaces(client, patched);\n return patched;\n}\n\n/**\n * The address the wallet reports via `bip122_addressesChanged` lands only on our\n * patched copy, so write it back to `client.session` - the record that restore,\n * teardown and staleness checks all read. Left unpersisted, the stored session\n * keeps `bip122.accounts === []`: `cleanupStaleSessionsForNamespace` reads a live\n * session as stale and disconnects it, and a reload waits again for an event the\n * wallet only emits right after approval.\n */\nasync function persistSessionNamespaces(\n client: SignClientInstance,\n session: SessionTypes.Struct\n): Promise<void> {\n try {\n await client.session.update(session.topic, {\n namespaces: session.namespaces,\n });\n } catch (error) {\n debug(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\nasync function waitForBip122PaymentAddress(\n client: SignClientInstance,\n session: SessionTypes.Struct,\n timeoutMs = BIP122_ACCOUNT_TIMEOUT\n): Promise<{ address: string; session: SessionTypes.Struct }> {\n return await new Promise((resolve, reject) => {\n const topic = session.topic;\n let settled = false;\n\n const finish = (address: string, updatedSession: SessionTypes.Struct) => {\n if (settled) {\n return;\n }\n settled = true;\n cleanup();\n resolve({ address, session: updatedSession });\n };\n\n const fail = (error: Error) => {\n if (settled) {\n return;\n }\n settled = true;\n cleanup();\n reject(error);\n };\n\n const timer = setTimeout(() => {\n fail(\n new Error(\n 'Timed out waiting for Bitcoin account from wallet. Please try reconnecting.'\n )\n );\n }, timeoutMs);\n\n const cleanup = () => {\n clearTimeout(timer);\n client.off('session_event', onEvent);\n client.off('session_update', onUpdate);\n };\n\n const onEvent = (args: SignClientTypes.EventArguments['session_event']) => {\n if (args.topic !== topic) {\n return;\n }\n if (args.params.event.name !== BitcoinEvents.ADDRESSES_CHANGED) {\n return;\n }\n\n const address = pickPaymentAddress(\n args.params.event.data as Bip122AddressEntry[]\n );\n if (address) {\n finish(address, client.session.get(topic) ?? session);\n }\n };\n\n const onUpdate = (\n args: SignClientTypes.EventArguments['session_update']\n ) => {\n if (args.topic !== topic) {\n return;\n }\n\n const updatedSession = client.session.get(topic) ?? session;\n const accounts = filterBip122Accounts(updatedSession);\n if (accounts.length) {\n finish(accounts[0].address, updatedSession);\n }\n };\n\n client.on('session_event', onEvent);\n client.on('session_update', onUpdate);\n });\n}\n", "import type { WalletConnectNamespace } from '../types.js';\nimport type { ISignClient, SessionTypes } from '@walletconnect/types';\n\nimport { WC_NAMESPACE_TO_CAIP } from '../wcConstants.js';\n\nexport function getCaipNamespace(namespace: WalletConnectNamespace): string {\n return WC_NAMESPACE_TO_CAIP[namespace];\n}\n\nexport function findSessionByNamespace(\n client: ISignClient,\n namespace: WalletConnectNamespace\n): SessionTypes.Struct | undefined {\n const caipNamespace = getCaipNamespace(namespace);\n\n return client.session.getAll().find((session) => {\n const ns = session.namespaces[caipNamespace];\n if ((ns?.accounts?.length ?? 0) > 0) {\n return true;\n }\n\n return namespace === 'utxo' && (ns?.chains?.length ?? 0) > 0;\n });\n}\n\nexport function getSessionNamespace(\n session: SessionTypes.Struct\n): WalletConnectNamespace | undefined {\n const hasAccounts = (namespace: WalletConnectNamespace) =>\n (session.namespaces[WC_NAMESPACE_TO_CAIP[namespace]]?.accounts?.length ??\n 0) > 0;\n const hasChains = (namespace: WalletConnectNamespace) =>\n (session.namespaces[WC_NAMESPACE_TO_CAIP[namespace]]?.chains?.length ?? 0) >\n 0;\n\n /*\n * Prefer a namespace the wallet shared accounts for; fall back to one that\n * only negotiated chains (utxo can be chains-only before its account settles).\n */\n if (hasAccounts('evm')) {\n return 'evm';\n }\n if (hasAccounts('utxo')) {\n return 'utxo';\n }\n if (hasChains('utxo')) {\n return 'utxo';\n }\n if (hasChains('evm')) {\n return 'evm';\n }\n\n return undefined;\n}\n", "import type { WalletConnectNamespace } from '../types.js';\nimport type { ChainIdParams } from 'caip';\n\nimport { CAIP_BITCOIN_CHAIN_ID } from '@rango-dev/wallets-core/namespaces/utxo';\nimport { ChainId } from 'caip';\n\nimport {\n DEFAULT_BITCOIN_EVENTS,\n DEFAULT_BITCOIN_METHODS,\n DEFAULT_ETHEREUM_EVENTS,\n DEFAULT_ETHEREUM_METHODS,\n NAMESPACES,\n WC_NAMESPACE_TO_CAIP,\n} from '../wcConstants.js';\n\n/**\n * `chains` is required here so the same shape is assignable both to the\n * SignClient `ProposalTypes` (chains optional) and to the UniversalProvider\n * `NamespaceConfig` (chains required).\n */\nexport type FinalNamespaces = Record<\n string,\n { chains: string[]; methods: string[]; events: string[] }\n>;\n\ntype NamespaceProposal = {\n methods: string[];\n events: string[];\n resolveChains: (\n chains: ChainIdParams[],\n targetChainReference?: string\n ) => ChainIdParams[];\n};\n\n/**\n * Per-namespace proposal facts as data, keyed by `WalletConnectNamespace` so a\n * newly-added alias is a compile error until it's configured here. The CAIP\n * prefix comes from the shared `WC_NAMESPACE_TO_CAIP` map.\n */\nconst NAMESPACE_PROPOSALS: Record<WalletConnectNamespace, NamespaceProposal> = {\n evm: {\n methods: DEFAULT_ETHEREUM_METHODS,\n events: DEFAULT_ETHEREUM_EVENTS,\n resolveChains: (chains, targetChainReference) => {\n if (targetChainReference) {\n return [\n { namespace: NAMESPACES.ETHEREUM, reference: targetChainReference },\n ];\n }\n return chains.length > 0\n ? chains\n : [{ namespace: NAMESPACES.ETHEREUM, reference: '1' }];\n },\n },\n utxo: {\n methods: DEFAULT_BITCOIN_METHODS,\n events: DEFAULT_BITCOIN_EVENTS,\n resolveChains: () => [\n { namespace: NAMESPACES.BITCOIN, reference: CAIP_BITCOIN_CHAIN_ID },\n ],\n },\n};\n\n/**\n * Builds a WalletConnect namespace proposal (chains, methods, events).\n *\n * The result always goes to `optionalNamespaces`: sign-client merges\n * `requiredNamespaces` into `optionalNamespaces` and clears it before sending\n * the proposal, so passing anything as required only earns a deprecation\n * warning. Narrowing the proposal (see `targetChainReference`) is what actually\n * constrains what the wallet can approve.\n *\n * @param targetChainReference - When set for EVM, limits the proposal to this\n * single chain id (decimal string, e.g. `\"137\"`). Omit to include all EVM\n * chains from `chains`.\n */\nexport function generateOptionalNamespace(\n chains: ChainIdParams[],\n namespaces: WalletConnectNamespace[],\n targetChainReference?: string\n): FinalNamespaces | undefined {\n const proposal: FinalNamespaces = {};\n\n for (const namespace of namespaces) {\n const config = NAMESPACE_PROPOSALS[namespace];\n proposal[WC_NAMESPACE_TO_CAIP[namespace]] = {\n methods: config.methods,\n events: config.events,\n chains: config\n .resolveChains(chains, targetChainReference)\n .map((chain) => new ChainId(chain).toString()),\n };\n }\n\n return Object.keys(proposal).length > 0 ? proposal : undefined;\n}\n", "import type { SignClientInstance, WalletConnectNamespace } from '../types.js';\nimport type { ISignClient, SessionTypes } from '@walletconnect/types';\nimport type UniversalProvider from '@walletconnect/universal-provider';\n\nimport { debug } from '@rango-dev/logging-core';\nimport { getSdkError } from '@walletconnect/utils';\n\nimport { NAMESPACES } from '../wcConstants.js';\n\nimport { persistCurrentChainId } from './chain-state.js';\nimport { getSessionNamespace } from './lookup.js';\n\nfunction isNoMatchingKeyError(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error);\n return message.includes('No matching key');\n}\n\nexport function hasActiveSession(client: ISignClient, topic: string): boolean {\n try {\n return !!client.session.get(topic);\n } catch {\n return false;\n }\n}\n\nexport function hasActivePairing(\n client: SignClientInstance,\n topic: string\n): boolean {\n return client.pairing.getAll().some((pairing) => pairing.topic === topic);\n}\n\nexport async function expireWalletConnectTopic(\n client: SignClientInstance,\n topic: string\n) {\n const sessions = client.session.getAll();\n const pairings = client.pairing.getAll();\n\n sessions.forEach((session: SessionTypes.Struct) => {\n if (session.topic === topic || session.pairingTopic === topic) {\n const requestForDeleteTopic =\n session.pairingTopic === topic ? session.pairingTopic : session.topic;\n client.core.expirer.set(requestForDeleteTopic, 0);\n }\n });\n\n pairings.forEach((pairing) => {\n if (pairing.topic === topic) {\n client.core.expirer.set(topic, 0);\n }\n });\n}\n\nexport async function removeSessionRecord(\n client: SignClientInstance,\n session: SessionTypes.Struct\n) {\n const namespace = getSessionNamespace(session);\n const pairingTopic = session.pairingTopic;\n\n if (hasActiveSession(client, session.topic)) {\n try {\n await client.disconnect({\n topic: session.topic,\n reason: getSdkError('USER_DISCONNECTED'),\n });\n } catch (error) {\n debug(error instanceof Error ? error : new Error(String(error)));\n if (isNoMatchingKeyError(error)) {\n await expireWalletConnectTopic(client, session.topic);\n }\n }\n } else {\n await expireWalletConnectTopic(client, session.topic);\n }\n\n const remainingOnPairing = client.session\n .getAll()\n .filter((item) => item.pairingTopic === pairingTopic);\n\n if (!remainingOnPairing.length && pairingTopic) {\n if (hasActivePairing(client, pairingTopic)) {\n try {\n await client.disconnect({\n topic: pairingTopic,\n reason: getSdkError('USER_DISCONNECTED'),\n });\n } catch (error) {\n debug(error instanceof Error ? error : new Error(String(error)));\n if (isNoMatchingKeyError(error)) {\n await expireWalletConnectTopic(client, pairingTopic);\n }\n }\n } else {\n await expireWalletConnectTopic(client, pairingTopic);\n }\n }\n\n if (namespace === 'evm') {\n void persistCurrentChainId(client, undefined);\n }\n}\n\nexport async function purgeOrphanedSessions(\n client: SignClientInstance\n): Promise<void> {\n const pairingTopics = new Set(\n client.pairing.getAll().map((pairing) => pairing.topic)\n );\n\n for (const session of [...client.session.getAll()]) {\n const pairingOrphaned =\n !!session.pairingTopic && !pairingTopics.has(session.pairingTopic);\n const sessionMissing = !hasActiveSession(client, session.topic);\n\n if (pairingOrphaned || sessionMissing) {\n await removeSessionRecord(client, session);\n }\n }\n}\n\n/**\n * Drops pairings that no session is using.\n *\n * The inverse of {@link purgeOrphanedSessions}, and the only thing that collects\n * them: a cancelled connect leaves behind the pairing `client.connect()` minted,\n * and `cleanupPendingPairings` only unsubscribes pairings - it never deletes the\n * record. Without this they accumulate in `client.pairing` and in storage for the\n * lifetime of the origin.\n *\n * Only safe to call while no connect is in flight (the adapter's `#sessionQueue`\n * guarantees that): a pairing awaiting its first approval has no session yet, so\n * dropping it would kill that handshake.\n */\nexport async function purgeOrphanedPairings(\n client: SignClientInstance\n): Promise<void> {\n const usedPairingTopics = new Set(\n client.session\n .getAll()\n .map((session) => session.pairingTopic)\n .filter((topic): topic is string => !!topic)\n );\n\n for (const pairing of [...client.pairing.getAll()]) {\n if (usedPairingTopics.has(pairing.topic)) {\n continue;\n }\n\n try {\n await client.disconnect({\n topic: pairing.topic,\n reason: getSdkError('USER_DISCONNECTED'),\n });\n } catch (error) {\n debug(error instanceof Error ? error : new Error(String(error)));\n await expireWalletConnectTopic(client, pairing.topic);\n }\n }\n}\n\nexport async function cleanupStaleSessionsForNamespace(\n client: UniversalProvider['client'],\n namespace: WalletConnectNamespace\n): Promise<void> {\n for (const existing of client.session.getAll()) {\n if (getSessionNamespace(existing) !== namespace) {\n continue;\n }\n\n const btc = existing.namespaces[NAMESPACES.BITCOIN];\n if (\n btc &&\n (btc.chains?.length ?? 0) > 0 &&\n (btc.accounts?.length ?? 0) === 0\n ) {\n await removeSessionRecord(client, existing);\n }\n }\n}\n", "import type { SessionCache } from '../adapter/session-cache.js';\nimport type { SignClientInstance, WalletConnectNamespace } from '../types.js';\nimport type { SessionTypes } from '@walletconnect/types';\n\nimport { debug } from '@rango-dev/logging-core';\n\nimport {\n restoreWalletConnectSession,\n type RestoreWalletConnectSessionOptions,\n} from './lifecycle.js';\n\nexport async function restoreAndCacheSession(\n client: SignClientInstance,\n namespace: WalletConnectNamespace,\n cache: SessionCache,\n options?: RestoreWalletConnectSessionOptions,\n onDisconnect?: (namespace: WalletConnectNamespace) => Promise<void>\n): Promise<SessionTypes.Struct | null> {\n try {\n const session = await restoreWalletConnectSession(\n client,\n namespace,\n options\n );\n if (!session) {\n return null;\n }\n\n cache.set(namespace, session);\n return session;\n } catch (error) {\n debug(error instanceof Error ? error : new Error(String(error)));\n if (cache.get(namespace)) {\n await onDisconnect?.(namespace);\n }\n return null;\n }\n}\n", "import type { AppKitModal, ModalParams } from './modal.js';\n\nimport { createAppKitModal } from './modal.js';\n\n/**\n * Holds the single AppKit modal for the adapter's lifetime.\n *\n * One instance serves every namespace - all its networks are registered up front\n * and the active one is chosen per connect with `switchNetwork`. It is built once\n * and reused: rebuilding per namespace re-ran AppKit init against its shared\n * singleton controllers and left stale router/filter state behind.\n */\nexport class ModalCache {\n #web3Modal: AppKitModal | null = null;\n\n getModal(params: ModalParams): AppKitModal {\n if (!this.#web3Modal) {\n this.#web3Modal = createAppKitModal(params);\n }\n\n return this.#web3Modal;\n }\n}\n", "import UniversalProvider from '@walletconnect/universal-provider';\n\nimport { DEFAULT_APP_METADATA, RELAY_URL } from '../wcConstants.js';\n\nexport async function createUniversalProvider(\n projectId: string\n): Promise<UniversalProvider> {\n return UniversalProvider.init({\n relayUrl: RELAY_URL,\n projectId,\n metadata: DEFAULT_APP_METADATA,\n });\n}\n", "import type { WalletConnectNamespace } from '../types.js';\nimport type { SessionTypes } from '@walletconnect/types';\n\nexport type SessionCache = {\n get(namespace: WalletConnectNamespace): SessionTypes.Struct | null;\n set(namespace: WalletConnectNamespace, session: SessionTypes.Struct): void;\n clear(namespace: WalletConnectNamespace): void;\n /**\n * Drops every namespace holding `topic`. A wallet may approve more than was\n * proposed, so one settled session can back both namespaces - tearing its topic\n * down under one of them would otherwise leave the other pointing at a topic\n * the relay has already dropped.\n */\n clearTopic(topic: string): void;\n clearAll(): void;\n};\n\nexport function createSessionCache(): SessionCache {\n const sessions = new Map<WalletConnectNamespace, SessionTypes.Struct>();\n\n return {\n get: (namespace) => sessions.get(namespace) ?? null,\n\n set: (namespace, session) => void sessions.set(namespace, session),\n\n clear: (namespace) => void sessions.delete(namespace),\n\n clearTopic: (topic) => {\n for (const [namespace, session] of sessions) {\n if (session.topic === topic) {\n sessions.delete(namespace);\n }\n }\n },\n\n clearAll: () => sessions.clear(),\n };\n}\n", "/**\n * Runs tasks one at a time, in the order `run` was called.\n *\n * A task that rejects passes its rejection to its own caller and does not block\n * the tasks behind it.\n */\nexport class TaskQueue {\n /** Resolves once the task currently at the back of the queue has settled. */\n #tail: Promise<void> = Promise.resolve();\n\n async run<T>(task: () => Promise<T>): Promise<T> {\n const ourTurn = this.#tail;\n\n /*\n * Take our place at the back of the queue before awaiting anything, so\n * callers arriving in the same tick line up behind us rather than all\n * reading the same `#tail`. `releaseOurTurn` never rejects, which is what\n * lets the next task run even when this one throws.\n */\n let releaseOurTurn!: () => void;\n this.#tail = new Promise<void>((resolve) => {\n releaseOurTurn = resolve;\n });\n\n await ourTurn;\n try {\n return await task();\n } finally {\n releaseOurTurn();\n }\n }\n}\n", "import type { WalletConnectAdapter } from './adapter.js';\n\n/**\n * Holds the singleton adapter instance created in the provider's `init`.\n *\n * This lives in its own leaf module (importing nothing from `provider.ts` or the\n * namespaces) to break the `provider -> namespace -> provider` import cycle that\n * otherwise throws a TDZ error (\"Cannot access 'getAdapter' before initialization\")\n * when the namespace module evaluates its top-level subscriber factories.\n */\nlet adapter: WalletConnectAdapter;\n\nexport const getAdapter = () => adapter;\n\nexport const setAdapter = (instance: WalletConnectAdapter) => {\n adapter = instance;\n};\n", "import type { ProviderMetadata } from '@hub3js/core';\n\nimport { isEvmNamespace } from '@hub3js/evm';\n\nimport getSigners from './signer.js';\n\nexport const WALLET_ID = 'wallet-connect-2';\n\nexport const metadata: ProviderMetadata = {\n name: 'WalletConnect',\n icon: 'https://raw.githubusercontent.com/rango-exchange/assets/main/wallets/walletconnect/icon.svg',\n extensions: {\n homepage: 'https://walletconnect.com/',\n },\n properties: [\n {\n name: 'namespaces',\n value: {\n selection: 'single',\n data: [\n {\n label: 'EVM',\n value: 'EVM',\n id: 'ETH',\n isChainSupported: isEvmNamespace,\n },\n ],\n },\n },\n {\n name: 'signers',\n value: { getSigners: async () => getSigners() },\n },\n {\n name: 'details',\n value: {\n mobileWallet: true,\n showOnMobile: true,\n },\n },\n ],\n};\n", "import type { SignerFactory } from 'rango-types';\n\nimport { DefaultSignerFactory, TransactionType as TxType } from 'rango-types';\n\nimport { getAdapter } from './adapter/registry.js';\n\nexport default async function getSigners(): Promise<SignerFactory> {\n const adapter = getAdapter();\n if (!adapter) {\n throw new Error('WalletConnect provider has not been initialized.');\n }\n\n const client = await adapter.getClient();\n\n const signers = new DefaultSignerFactory();\n const EVMSigner = (await import('./signers/evm.js')).default;\n signers.registerSigner(\n TxType.EVM,\n new EVMSigner(client, () => adapter.getSession('evm'))\n );\n\n return signers;\n}\n", "import type { Context } from '@hub3js/core';\nimport type { EvmActions } from '@hub3js/evm';\n\nimport { NamespaceBuilder } from '@hub3js/core';\nimport { actions, builders, utils } from '@hub3js/evm';\nimport * as commonBuilders from '@hub3js/std/builders';\nimport { standardizeAndThrowError } from '@hub3js/std/operators';\n\nimport { getAdapter } from '../../adapter/registry.js';\nimport { WALLET_ID } from '../../constants.js';\nimport { getAccountsFromSession } from '../../session/accounts.js';\nimport { filterEvmAccounts } from '../../session/evm.js';\nimport { chainReferenceToHex, parseChainReference } from '../../utils.js';\n\nimport {\n sessionDeleteSubscriber,\n sessionEventSubscriber,\n sessionUpdateSubscriber,\n} from './hooks.js';\n\nconst [sessionUpdate, sessionUpdateCleanup] = sessionUpdateSubscriber();\nconst [sessionEvent, sessionEventCleanup] = sessionEventSubscriber();\nconst [sessionDelete, sessionDeleteCleanup] = sessionDeleteSubscriber();\n\nconst connect = builders\n .connect()\n .action(async function (_context: Context<EvmActions>, chain?: string) {\n const adapter = getAdapter();\n // `chain` is set when connecting to a specific network (swap auto-switch or hub connect with network).\n const requestedReference = chain ? parseChainReference(chain) : undefined;\n const session = await adapter.ensureConnectedToChain(chain);\n const activeReference =\n requestedReference ?? (await adapter.resolveActiveChainReference());\n\n if (!activeReference) {\n throw new Error(\n 'Unable to determine EVM chain id from WalletConnect session.'\n );\n }\n\n const accounts = getAccountsFromSession(session);\n const evmAccounts = filterEvmAccounts(accounts, activeReference);\n\n if (!evmAccounts.length) {\n throw new Error('No EVM accounts found in WalletConnect session.');\n }\n\n return {\n accounts: utils.formatAccountsToCAIP(\n evmAccounts.map((account) => account.accounts[0]),\n activeReference\n ),\n network: chainReferenceToHex(activeReference),\n };\n })\n .before(sessionUpdate)\n .before(sessionEvent)\n .before(sessionDelete)\n .or(sessionUpdateCleanup)\n .or(sessionEventCleanup)\n .or(sessionDeleteCleanup)\n .or((_, err) => {\n void getAdapter().disconnectSession('evm');\n return err;\n })\n .or(standardizeAndThrowError)\n .build();\n\nconst canEagerConnect = builders\n .canEagerConnect()\n .action(async () => getAdapter().tryRestoreEagerSession('evm'))\n .build();\n\nconst canSwitchNetwork = builders\n .canSwitchNetwork()\n .action(actions.canSwitchNetwork())\n .build();\n\nconst disconnect = commonBuilders\n .disconnect<EvmActions>()\n .before(async () => {\n await getAdapter().disconnectSession('evm');\n })\n .after(sessionUpdateCleanup)\n .after(sessionEventCleanup)\n .after(sessionDeleteCleanup)\n .build();\n\nconst getChainId = builders\n .getChainId()\n .action(async () => getAdapter().getCurrentChainId())\n .build();\n\nconst evm = new NamespaceBuilder<EvmActions>('EVM', WALLET_ID)\n .action(connect)\n .action(canEagerConnect)\n .action(canSwitchNetwork)\n .action(disconnect)\n .action(getChainId)\n .build();\n\nexport { evm };\n", "import type { EvmActions } from '@hub3js/evm';\n\nimport { utils } from '@hub3js/evm';\nimport { ChainId } from 'caip';\n\nimport {\n extractAddress,\n getAccountsFromEvent,\n} from '../../session/accounts.js';\nimport {\n getPersistedChainId,\n persistCurrentChainId,\n} from '../../session/chain-state.js';\nimport { filterEvmAccounts } from '../../session/evm.js';\nimport { expireWalletConnectTopic } from '../../session/teardown.js';\nimport { chainReferenceToHex, parseChainReference } from '../../utils.js';\nimport { EthereumEvents, NAMESPACES } from '../../wcConstants.js';\nimport { createSessionSubscriber } from '../subscriber.js';\n\n/**\n * WC signals an account switch via `session_update` (re-shared namespaces with the\n * newly-selected account first), so the active account is published from this event.\n */\nexport function sessionUpdateSubscriber() {\n return createSessionSubscriber<'session_update', EvmActions>(\n 'evm',\n 'session_update',\n async ({ args, session, adapter, context }) => {\n /*\n * Keep the cached struct in step with what the wallet just re-shared.\n * `switchEvmNetwork` reads the authorized chains and methods back out\n * of it, so a stale copy rejects a chain the wallet has since added\n * (`wallet_addEthereumChain` lands here as a `session_update`) with\n * \"Chain X is not configured\".\n */\n if (args.params.namespaces[NAMESPACES.ETHEREUM]) {\n adapter.cacheSession('evm', {\n ...session,\n namespaces: args.params.namespaces,\n });\n }\n\n const allAccounts = getAccountsFromEvent(args);\n if (!allAccounts.length) {\n return;\n }\n\n const entries = allAccounts.map((accountsWithChain) => ({\n address: accountsWithChain.accounts[0],\n chainId: accountsWithChain.chainId,\n }));\n\n const [getState, setState] = context.state();\n const hubNetwork = getState().network;\n const persistedChain = await getPersistedChainId(\n await adapter.getClient()\n );\n const activeReference =\n parseChainReference(hubNetwork ?? undefined) ?? persistedChain;\n\n let evmAccounts = filterEvmAccounts(entries, activeReference);\n if (!evmAccounts.length) {\n evmAccounts = filterEvmAccounts(entries);\n }\n if (!evmAccounts.length) {\n return;\n }\n\n const chainIdHex = chainReferenceToHex(evmAccounts[0].chainId);\n setState(\n 'accounts',\n utils.formatAccountsToCAIP([evmAccounts[0].accounts[0]], chainIdHex)\n );\n setState('network', chainIdHex);\n }\n );\n}\n\n/**\n * Addresses out of an `accountsChanged` payload. Spec says `string[]`, but wallets\n * forwarding the EIP-1193 event as-is send a bare value, so the shape is coerced\n * before anything reads it.\n */\nfunction eventAccounts(data: unknown): string[] {\n return (Array.isArray(data) ? data : [data])\n .filter((entry): entry is string => typeof entry === 'string' && !!entry)\n .map(extractAddress);\n}\n\n/**\n * Handles WC `session_event` payloads: EIP-1193 `accountsChanged` (publish the new\n * accounts, or disconnect when the wallet revokes them all) and `chainChanged`\n * (update and persist the active chain). Any other event is ignored.\n */\nexport function sessionEventSubscriber() {\n return createSessionSubscriber<'session_event', EvmActions>(\n 'evm',\n 'session_event',\n ({ args, adapter, context }) => {\n const [, setState] = context.state();\n\n if (args.params.event.name === EthereumEvents.ACCOUNTS_CHANGED) {\n const accounts = eventAccounts(args.params.event.data);\n /*\n * An empty payload is the wallet revoking access (locked, or the account\n * unlinked from this dApp), not a switch - there is nothing to publish.\n */\n if (!accounts.length) {\n void context.action('disconnect');\n return;\n }\n\n const chainIdHex = chainReferenceToHex(\n ChainId.parse(args.params.chainId).reference\n );\n setState('network', chainIdHex);\n setState('accounts', utils.formatAccountsToCAIP(accounts, chainIdHex));\n return;\n }\n\n if (args.params.event.name === EthereumEvents.CHAIN_CHANGED) {\n const chainIdHex = chainReferenceToHex(args.params.event.data);\n setState('network', chainIdHex);\n void adapter\n .getClient()\n .then(async (client) => persistCurrentChainId(client, chainIdHex));\n }\n }\n );\n}\n\n/**\n * Reflects a wallet-initiated `session_delete` into the hub: clears the cached\n * session, expires the WC topic, and runs the hub `disconnect` action.\n */\nexport function sessionDeleteSubscriber() {\n return createSessionSubscriber<'session_delete', EvmActions>(\n 'evm',\n 'session_delete',\n ({ args, adapter, context }) => {\n adapter.clearSession('evm');\n void adapter\n .getClient()\n .then(async (client) => expireWalletConnectTopic(client, args.topic));\n context.action('disconnect');\n }\n );\n}\n", "import type { WalletConnectAdapter } from '../adapter/adapter.js';\nimport type { WalletConnectNamespace } from '../types.js';\nimport type {\n Actions,\n Context,\n Subscriber,\n SubscriberCleanUp,\n} from '@hub3js/core';\nimport type { SessionTypes, SignClientTypes } from '@walletconnect/types';\n\nimport { debug } from '@rango-dev/logging-core';\n\nimport { getAdapter } from '../adapter/registry.js';\n\n/** The WC client events a namespace subscribes to. */\nexport type SessionEventName =\n | 'session_update'\n | 'session_event'\n | 'session_delete';\n\nexport type SessionEventHandler<\n Name extends SessionEventName,\n ActionsType extends Actions<ActionsType>\n> = (event: {\n args: SignClientTypes.EventArguments[Name];\n /** The cached session this event was matched against. */\n session: SessionTypes.Struct;\n adapter: WalletConnectAdapter;\n context: Context<ActionsType>;\n}) => void | Promise<void>;\n\nfunction logHandlerError(error: unknown) {\n debug(error instanceof Error ? error : new Error(String(error)));\n}\n\n/**\n * Builds a hub subscriber for one WC client event, scoped to one namespace.\n *\n * Every namespace hook needs the same four things - resolve the client, only act\n * on events for the session this namespace has cached, register, and unregister\n * the exact same handler reference. Getting the topic guard wrong is what makes a\n * hook act on the other namespace's session, so it lives here rather than being\n * repeated per hook.\n */\nexport function createSessionSubscriber<\n Name extends SessionEventName,\n ActionsType extends Actions<ActionsType>\n>(\n namespace: WalletConnectNamespace,\n event: Name,\n handle: SessionEventHandler<Name, ActionsType>\n): [Subscriber<ActionsType>, SubscriberCleanUp<ActionsType>] {\n let handler: ((args: SignClientTypes.EventArguments[Name]) => void) | null =\n null;\n\n return [\n async (context) => {\n const adapter = getAdapter();\n const client = await adapter.getClient();\n\n /*\n * A namespace re-runs its `before` subscribers on every connect, so drop the\n * previous registration first - otherwise each reconnect leaves another live\n * handler behind and only the last one is ever removed.\n */\n if (handler) {\n client.off(event, handler);\n }\n\n handler = (args) => {\n const session = adapter.getSession(namespace);\n if (!session || args.topic !== session.topic) {\n return;\n }\n\n /*\n * WC dispatches these from its own async request pipeline with nothing\n * catching downstream, so a throw here (a payload shaped unlike anything\n * the handler expects) would surface as an unhandled rejection and take\n * the rest of that pipeline's processing with it. Async handlers are\n * covered too - their rejection lands nowhere otherwise.\n */\n try {\n const handled = handle({ args, session, adapter, context });\n if (handled instanceof Promise) {\n void handled.catch(logHandlerError);\n }\n } catch (error) {\n logHandlerError(error);\n }\n };\n\n client.on(event, handler);\n },\n (_, err) => {\n const currentHandler = handler;\n if (currentHandler) {\n handler = null;\n void getAdapter()\n .getClient()\n .then((client) => client.off(event, currentHandler));\n }\n return err;\n },\n ];\n}\n"],
|
|
5
|
-
"mappings": "mIAAA,OAAS,kBAAAA,OAAsB,qBCE/B,OAAS,mBAAAC,OAAuB,eCIhC,OAAS,SAAAC,OAAa,0BCFtB,OAAS,SAASC,MAAgB,0BAClC,OAAS,WAAAC,OAAe,OCHxB,OAAS,aAAAC,MAAiB,OAMnB,SAASC,GAAeC,EAAyB,CACtD,OAAOA,EAAQ,SAAS,GAAG,EAAI,IAAIC,EAAUD,CAAO,EAAE,QAAUA,CAClE,CAFgBE,EAAAH,GAAA,kBAIT,SAASI,EAAuBC,EAA8B,CAWnE,OAViB,OAAO,OAAOA,EAAQ,UAAU,EAC9C,IAAKC,GAAcA,EAAU,QAAQ,EACrC,KAAK,EACL,IAAKL,GAAY,CAChB,GAAM,CAAE,QAAAM,EAAS,QAAAC,CAAQ,EAAI,IAAIN,EAAUD,CAAO,EAClD,MAAO,CACL,QAAAM,EACA,QAASC,EAAQ,SACnB,CACF,CAAC,CAEL,CAZgBL,EAAAC,EAAA,0BAcT,SAASK,GACdC,EAGA,CAYA,OAXiB,OAAO,OAAOA,EAAM,OAAO,UAAU,EACnD,IAAKJ,GAAcA,EAAU,QAAQ,EACrC,KAAK,EACL,IAAKL,GAAY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CAClB,MAAMlB,EAAW,EAAE,kBAAkB,KAAK,CAC5C,CAAC,EACA,MAAMb,EAAoB,EAC1B,MAAMG,EAAmB,EACzB,MAAMG,EAAoB,EAC1B,MAAM,EAEH0B,GAAavB,EAChB,WAAW,EACX,OAAO,SAAYI,EAAW,EAAE,kBAAkB,CAAC,EACnD,MAAM,EAEHoB,GAAM,IAAIC,GAA6B,MAAOC,CAAS,EAC1D,OAAO3B,EAAO,EACd,OAAOoB,EAAe,EACtB,OAAOC,EAAgB,EACvB,OAAOE,EAAU,EACjB,OAAOC,EAAU,EACjB,MAAM,ErB1FT,IAAMI,GAAgBC,EAAA,IACpB,IAAIC,GAAgBC,CAAS,EAC1B,KAAK,SAAUC,EAASC,EAA4B,CACnD,GAAM,CAAC,CAAEC,CAAQ,EAAIF,EAAQ,MAAM,EAE9BC,EAAa,gBAIlBE,GACE,IAAIC,EAAqB,CACvB,UAAWH,EAAa,cACxB,KAAMA,EAAa,MAAQ,CAAC,EAC5B,iBAAkBA,EAAa,4BAC/B,UAAWA,EAAa,UACxB,YAAaA,EAAa,WAC5B,CAAC,CACH,EACAC,EAAS,YAAa,EAAI,EAC1B,QAAQ,MAAM,2CAA4CF,CAAO,EACnE,CAAC,EACA,OAAO,WAAYK,EAAQ,EAC3B,IAAI,MAAOC,EAAG,EACd,MAAM,EAvBW,iBDHtB,IAAMC,GAAWC,EAAA,IACfC,GAAe,EAAE,QAAQ,QAASC,GAAc,CAAC,EAAE,MAAM,EAD1C",
|
|
6
|
-
"names": ["defineVersions", "ProviderBuilder", "debug", "logError", "ChainId", "AccountId", "extractAddress", "account", "AccountId", "__name", "getAccountsFromSession", "session", "namespace", "address", "chainId", "getAccountsFromEvent", "event", "persistCurrentChainId", "client", "chainId", "CHAIN_ID_STORAGE", "__name", "getPersistedChainId", "getChainIdByNetworkName", "network", "meta", "chainIdInHex", "blockchain", "debug", "convertEvmBlockchainMetaToEvmChainInfo", "
|
|
4
|
+
"sourcesContent": ["import { defineVersions } from '@hub3js/core/utils';\n\nimport { buildProvider } from './provider.js';\n\nexport type { Environments } from './types.js';\n\nconst versions = () =>\n defineVersions().version('1.0.0', buildProvider()).build();\n\nexport { versions };\nexport { WALLET_ID } from './constants.js';\n", "import type { Environments } from './types.js';\n\nimport { ProviderBuilder } from '@hub3js/core';\n\nimport { WalletConnectAdapter } from './adapter/adapter.js';\nimport { setAdapter } from './adapter/registry.js';\nimport { metadata, WALLET_ID } from './constants.js';\nimport { evm } from './namespaces/evm/namespace.js';\n\nconst buildProvider = () =>\n new ProviderBuilder(WALLET_ID)\n .init(function (context, environments: Environments) {\n const [, setState] = context.state();\n\n if (!environments.WC_PROJECT_ID) {\n return;\n }\n\n setAdapter(\n new WalletConnectAdapter({\n projectId: environments.WC_PROJECT_ID,\n meta: environments.meta || [],\n disableModalLink: environments.DISABLE_MODAL_AND_OPEN_LINK,\n themeMode: environments.themeMode,\n modalZIndex: environments.modalZIndex,\n })\n );\n setState('installed', true);\n console.debug('[wallet-connect-2] provider initialized.', context);\n })\n .config('metadata', metadata)\n .add('evm', evm)\n .build();\n\nexport { buildProvider };\n", "import type { WalletConnectNamespace } from '../types.js';\nimport type { Chain } from '@hub3js/evm';\nimport type { SessionTypes } from '@walletconnect/types';\nimport type UniversalProvider from '@walletconnect/universal-provider';\nimport type { BlockchainMeta } from 'rango-types';\n\nimport { debug } from '@rango-dev/logging-core';\n\nimport {\n ensureConnectedToChain as ensureConnectedToChainHelper,\n getCurrentChainId as getCurrentChainIdHelper,\n resolveActiveChainReference as resolveActiveChainReferenceHelper,\n switchEvmNetwork as switchEvmNetworkHelper,\n} from '../session/evm-chain.js';\nimport {\n connectWalletConnectSession,\n prepareWalletConnectNamespace,\n} from '../session/lifecycle.js';\nimport { restoreAndCacheSession } from '../session/restore-cache.js';\nimport { removeSessionRecord } from '../session/teardown.js';\nimport { evmMetaToCaipChainIds } from '../utils.js';\n\nimport { ModalCache } from './modal-cache.js';\nimport { createUniversalProvider } from './provider-client.js';\nimport { createSessionCache } from './session-cache.js';\nimport { TaskQueue } from './task-queue.js';\n\n/**\n * Central coordinator for WalletConnect sessions used by hub EVM/UTXO namespaces.\n *\n * Owns provider state (client, session cache, modal) and delegates protocol/domain\n * logic to `session/*` helpers.\n */\nexport interface WalletConnectAdapterConfig {\n projectId: string;\n meta: BlockchainMeta[];\n disableModalLink?: string;\n themeMode?: 'light' | 'dark';\n modalZIndex?: number;\n}\n\nexport class WalletConnectAdapter {\n readonly #projectId: string;\n readonly #disableModalLink?: string;\n readonly #themeMode?: 'light' | 'dark';\n readonly #modalZIndex?: number;\n readonly #meta: BlockchainMeta[];\n #universalProvider: UniversalProvider | null = null;\n #universalProviderPromise: Promise<UniversalProvider> | null = null;\n\n readonly #cache = createSessionCache();\n readonly #modalCache = new ModalCache();\n\n /**\n * Serializes everything that mutates WalletConnect session state.\n *\n * Connecting and disconnecting must never overlap: tearing a session down also\n * deletes its pairing, and an overlapping connect has already minted a new one\n * by then - the teardown unsubscribes it, so `wc_proposeSession` publishes to a\n * topic we no longer listen on and the relay answers\n * `Topic repository: AlreadyExists`.\n *\n * The hub can't order this for us: `useHubAdapter.disconnect` drops the\n * promises `namespace.disconnect()` returns (it iterates with `forEach`), so it\n * resolves while teardown is still in flight and never joins the queue that\n * serializes `connect`.\n *\n * The cost is that a connect holds the queue for its whole lifetime, including\n * the wait for the user to approve in their wallet, so a disconnect raised\n * meanwhile waits its turn instead of interleaving. That is deliberate rather\n * than an oversight: the pairing has to survive from `client.connect()` through\n * settle, which is exactly the span being protected.\n */\n readonly #sessionQueue = new TaskQueue();\n\n constructor(config: WalletConnectAdapterConfig) {\n this.#projectId = config.projectId;\n this.#meta = config.meta;\n this.#disableModalLink = config.disableModalLink;\n this.#themeMode = config.themeMode;\n this.#modalZIndex = config.modalZIndex;\n }\n\n async getUniversalProvider(): Promise<UniversalProvider> {\n /*\n * Memoize the in-flight promise, not the resolved value. A namespace's\n * `before` subscribers are invoked with `forEach` (nothing awaits between\n * them), so several reach this method in the same tick - awaiting first and\n * assigning after would let each start its own `UniversalProvider`, leaving\n * several SignClients sharing one storage. The extra clients answer relay\n * traffic for a handshake they never made (\"Pending session not found for\n * topic X\", then \"No matching key. session topic doesn't exist: X\").\n */\n if (!this.#universalProviderPromise) {\n this.#universalProviderPromise = createUniversalProvider(this.#projectId)\n .then((provider) => {\n this.#universalProvider = provider;\n return provider;\n })\n .catch((error: unknown) => {\n // Don't cache a failed init - let the next caller retry.\n this.#universalProviderPromise = null;\n throw error;\n });\n }\n\n return this.#universalProviderPromise;\n }\n\n async getClient() {\n return (await this.getUniversalProvider()).client;\n }\n\n getSession(namespace: WalletConnectNamespace): SessionTypes.Struct | null {\n return this.#cache.get(namespace);\n }\n\n cacheSession(\n namespace: WalletConnectNamespace,\n session: SessionTypes.Struct\n ) {\n this.#cache.set(namespace, session);\n }\n\n clearSession(namespace: WalletConnectNamespace) {\n this.#cache.clear(namespace);\n }\n\n clearAllSessions() {\n this.#cache.clearAll();\n }\n\n async tryRestoreEagerSession(\n namespace: WalletConnectNamespace\n ): Promise<boolean> {\n return this.#sessionQueue.run(async () => {\n const client = await this.getClient();\n return !!(await restoreAndCacheSession(\n client,\n namespace,\n this.#cache,\n { validateAccounts: true },\n async (targetNamespace) =>\n this.#disconnectSessionQueued(targetNamespace)\n ));\n });\n }\n\n async ensureSession(options: {\n namespace: WalletConnectNamespace;\n chainReference?: string;\n }): Promise<SessionTypes.Struct> {\n return this.#sessionQueue.run(async () =>\n this.#ensureSessionQueued(options)\n );\n }\n\n async disconnectSession(namespace: WalletConnectNamespace) {\n return this.#sessionQueue.run(async () =>\n this.#disconnectSessionQueued(namespace)\n );\n }\n\n async resolveActiveChainReference(): Promise<string | undefined> {\n const session = this.getSession('evm');\n if (!session) {\n return undefined;\n }\n\n return resolveActiveChainReferenceHelper(await this.getClient(), session);\n }\n\n async getCurrentChainId(): Promise<`0x${string}`> {\n const session = this.getSession('evm');\n if (!session) {\n throw new Error(\n 'Unable to determine EVM chain id from WalletConnect session.'\n );\n }\n\n return getCurrentChainIdHelper(await this.getClient(), session);\n }\n\n async ensureConnectedToChain(\n chain?: string | Chain\n ): Promise<SessionTypes.Struct> {\n return ensureConnectedToChainHelper(this.#evmChainDeps(), chain);\n }\n\n async switchEvmNetwork(\n requestedChainId: string,\n currentChainId: string\n ): Promise<void> {\n const session = this.getSession('evm');\n if (!session) {\n throw new Error('WalletConnect session is not available.');\n }\n\n this.cacheSession(\n 'evm',\n await switchEvmNetworkHelper({\n client: await this.getClient(),\n session,\n meta: this.#meta,\n requestedChainId,\n currentChainId,\n })\n );\n }\n\n /*\n * The `Queued` suffix means \"already running inside `#sessionQueue`\". These\n * call each other directly and must never go back through the public methods\n * above: re-entering the queue from inside a task would wait for a turn that\n * cannot come until that same task finishes, which deadlocks.\n */\n\n async #ensureSessionQueued(options: {\n namespace: WalletConnectNamespace;\n chainReference?: string;\n }): Promise<SessionTypes.Struct> {\n const { namespace, chainReference } = options;\n const client = await this.getClient();\n const restored = await restoreAndCacheSession(\n client,\n namespace,\n this.#cache,\n undefined,\n async (targetNamespace) => this.#disconnectSessionQueued(targetNamespace)\n );\n if (restored) {\n return restored;\n }\n\n await prepareWalletConnectNamespace(client, namespace);\n\n const universalProvider = await this.getUniversalProvider();\n await universalProvider.cleanupPendingPairings().catch(() => undefined);\n\n const session = await connectWalletConnectSession(\n client,\n this.#modalCache.getModal({\n projectId: this.#projectId,\n universalProvider,\n themeMode: this.#themeMode,\n zIndex: this.#modalZIndex,\n }),\n {\n chains: evmMetaToCaipChainIds(this.#meta),\n envs: {\n WC_PROJECT_ID: this.#projectId,\n DISABLE_MODAL_AND_OPEN_LINK: this.#disableModalLink,\n },\n namespace,\n chainReference,\n }\n );\n\n this.#cache.set(namespace, session);\n return session;\n }\n\n async #disconnectSessionQueued(namespace: WalletConnectNamespace) {\n const session = this.getSession(namespace);\n if (this.#universalProvider?.client && session) {\n await removeSessionRecord(this.#universalProvider.client, session).catch(\n (error) => debug(error)\n );\n }\n this.clearSession(namespace);\n if (session) {\n this.#cache.clearTopic(session.topic);\n }\n }\n\n #evmChainDeps() {\n return {\n meta: this.#meta,\n getSession: (namespace: 'evm') => this.getSession(namespace),\n cacheSession: (namespace: 'evm', session: SessionTypes.Struct) =>\n this.cacheSession(namespace, session),\n getClient: async () => this.getClient(),\n ensureSession: async (options: {\n namespace: 'evm';\n chainReference?: string;\n }) => this.ensureSession(options),\n };\n }\n}\n", "import type { Chain } from '@hub3js/evm';\nimport type { ISignClient, SessionTypes } from '@walletconnect/types';\nimport type { BlockchainMeta } from 'rango-types';\n\nimport { error as logError } from '@rango-dev/logging-core';\nimport { ChainId } from 'caip';\n\nimport {\n chainReferenceToHex,\n parseChainReference,\n resolveNetworkName,\n} from '../utils.js';\nimport { EthereumRPCMethods, NAMESPACES } from '../wcConstants.js';\n\nimport { getAccountsFromSession } from './accounts.js';\nimport { getPersistedChainId, persistCurrentChainId } from './chain-state.js';\nimport {\n filterEvmAccounts,\n ignoreNamespaceMethods,\n switchOrAddEvmChain,\n updateSessionAccounts,\n} from './evm.js';\n\nexport type EvmChainDeps = {\n meta: BlockchainMeta[];\n getSession: (namespace: 'evm') => SessionTypes.Struct | null;\n cacheSession: (namespace: 'evm', session: SessionTypes.Struct) => void;\n getClient: () => Promise<ISignClient>;\n ensureSession: (options: {\n namespace: 'evm';\n chainReference?: string;\n }) => Promise<SessionTypes.Struct>;\n};\n\nexport async function resolveActiveChainReference(\n client: ISignClient,\n session: SessionTypes.Struct\n): Promise<string | undefined> {\n const persistedChainId = await getPersistedChainId(client);\n if (persistedChainId) {\n return persistedChainId;\n }\n\n const accounts = getAccountsFromSession(session);\n const evmAccounts = filterEvmAccounts(accounts);\n return evmAccounts[0]?.chainId;\n}\n\nexport async function getCurrentChainId(\n client: ISignClient,\n session: SessionTypes.Struct\n): Promise<`0x${string}`> {\n const reference = await resolveActiveChainReference(client, session);\n if (!reference) {\n throw new Error(\n 'Unable to determine EVM chain id from WalletConnect session.'\n );\n }\n\n return chainReferenceToHex(reference);\n}\n\n/**\n * Returns the session to keep using: `updateSessionAccounts` may rebuild it, and\n * the caller's copy is stale from that point on.\n */\nexport async function switchEvmNetwork(options: {\n client: ISignClient;\n session: SessionTypes.Struct;\n meta: BlockchainMeta[];\n requestedChainId: string;\n currentChainId: string;\n}): Promise<SessionTypes.Struct> {\n const { client, session, meta, requestedChainId, currentChainId } = options;\n\n const requestedReference = parseChainReference(requestedChainId);\n if (!requestedReference) {\n const error = new Error(`There is no match for ${requestedChainId}`);\n logError(error);\n throw error;\n }\n\n const chainIdStr = new ChainId({\n namespace: NAMESPACES.ETHEREUM,\n reference: requestedReference,\n }).toString();\n\n const requestedNetwork = resolveNetworkName(requestedChainId, meta);\n const currentNetwork = resolveNetworkName(currentChainId, meta);\n\n const evmNamespace = session.namespaces[NAMESPACES.ETHEREUM];\n const authorizedChains = evmNamespace?.chains || [];\n const authorizedMethods = evmNamespace?.methods || [];\n let activeSession = session;\n\n if (\n authorizedMethods.includes(EthereumRPCMethods.SWITCH_CHAIN) &&\n !ignoreNamespaceMethods(session)\n ) {\n if (!requestedNetwork || !currentNetwork) {\n const error = new Error(`Chain ${requestedReference} is not configured.`);\n logError(error);\n throw error;\n }\n\n activeSession = await updateSessionAccounts(\n client,\n session,\n requestedNetwork,\n currentNetwork,\n meta\n );\n await switchOrAddEvmChain(\n client,\n activeSession,\n meta,\n requestedNetwork,\n currentNetwork\n );\n } else if (!authorizedChains.includes(chainIdStr)) {\n const error = new Error(`Chain ${requestedReference} is not configured.`);\n logError(error);\n throw error;\n }\n\n await persistCurrentChainId(client, requestedReference);\n return activeSession;\n}\n\nexport async function switchToChainIfNeeded(\n deps: EvmChainDeps,\n requestedReference: string\n): Promise<void> {\n const session = deps.getSession('evm');\n if (!session) {\n throw new Error('WalletConnect session is not available.');\n }\n\n const client = await deps.getClient();\n const currentReference = await resolveActiveChainReference(client, session);\n if (currentReference === requestedReference) {\n await persistCurrentChainId(client, requestedReference);\n return;\n }\n\n const currentChainId = currentReference\n ? chainReferenceToHex(currentReference)\n : chainReferenceToHex(requestedReference);\n\n deps.cacheSession(\n 'evm',\n await switchEvmNetwork({\n client,\n session,\n meta: deps.meta,\n requestedChainId: requestedReference,\n currentChainId,\n })\n );\n}\n\nexport async function ensureConnectedToChain(\n deps: EvmChainDeps,\n chain?: string | Chain\n): Promise<SessionTypes.Struct> {\n const requestedReference = chain ? parseChainReference(chain) : undefined;\n\n if (!deps.getSession('evm')) {\n await deps.ensureSession({\n namespace: 'evm',\n chainReference: requestedReference,\n });\n }\n\n if (requestedReference) {\n await switchToChainIfNeeded(deps, requestedReference);\n }\n\n const session = deps.getSession('evm');\n if (!session) {\n throw new Error('WalletConnect session is not available.');\n }\n\n return session;\n}\n", "import type { SessionTypes, SignClientTypes } from '@walletconnect/types';\n\nimport { AccountId } from 'caip';\n\n/**\n * `accountsChanged` entries are CAIP-10 (`eip155:1:0x\u2026`) from wallets that follow\n * WC and a bare `0x\u2026` from the ones forwarding the EIP-1193 payload as-is.\n */\nexport function extractAddress(account: string): string {\n return account.includes(':') ? new AccountId(account).address : account;\n}\n\nexport function getAccountsFromSession(session: SessionTypes.Struct) {\n const accounts = Object.values(session.namespaces)\n .map((namespace) => namespace.accounts)\n .flat()\n .map((account) => {\n const { address, chainId } = new AccountId(account);\n return {\n address,\n chainId: chainId.reference,\n };\n });\n return accounts;\n}\n\nexport function getAccountsFromEvent(\n event: SignClientTypes.BaseEventArgs<{\n namespaces: SessionTypes.Namespaces;\n }>\n) {\n const accounts = Object.values(event.params.namespaces)\n .map((namespace) => namespace.accounts)\n .flat()\n .map((account) => {\n const { address, chainId } = new AccountId(account);\n return {\n accounts: [address],\n chainId: chainId.reference,\n };\n });\n\n return accounts;\n}\n", "import type { ISignClient } from '@walletconnect/types';\nimport type { BlockchainMeta } from 'rango-types';\n\nimport { CHAIN_ID_STORAGE } from '../wcConstants.js';\n\nexport async function persistCurrentChainId(\n client: ISignClient,\n chainId?: string\n) {\n return client.core.storage.setItem(CHAIN_ID_STORAGE, {\n defaultChainId: chainId ? parseInt(chainId) : '',\n });\n}\n\nexport async function getPersistedChainId(client: ISignClient) {\n try {\n const chainId = (await client.core.storage.getItem(CHAIN_ID_STORAGE))\n ?.defaultChainId;\n return !!chainId ? String(chainId) : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function getChainIdByNetworkName(\n network: string,\n meta: BlockchainMeta[]\n): string | undefined {\n const targetBlockchain = meta.find(\n (blockchain) => blockchain.name === network\n );\n const chainIdInHex = targetBlockchain?.chainId;\n if (!chainIdInHex) {\n return undefined;\n }\n\n return String(parseInt(chainIdInHex));\n}\n", "import type { ISignClient, SessionTypes } from '@walletconnect/types';\nimport type { BlockchainMeta } from 'rango-types';\n\nimport { debug } from '@rango-dev/logging-core';\nimport { convertEvmBlockchainMetaToEvmChainInfo } from '@rango-dev/internal-blockchains';\nimport { AccountId, ChainId } from 'caip';\nimport { isAddress as isEvmAddress } from 'ethers';\nimport { isEvmBlockchain } from 'rango-types';\n\nimport { EthereumRPCMethods, NAMESPACES } from '../wcConstants.js';\n\nimport { getChainIdByNetworkName } from './chain-state.js';\n\nexport function getCurrentEvmAccountAddress(\n session: SessionTypes.Struct\n): string | undefined {\n return session.namespaces[NAMESPACES.ETHEREUM]?.accounts\n ?.map((account) => new AccountId(account).address)\n ?.filter((address) => isEvmAddress(address))?.[0];\n}\n\nexport function getEvmAccount(\n network: string,\n address: string,\n meta: BlockchainMeta[]\n): string | undefined {\n const currentChainId = getChainIdByNetworkName(network, meta);\n if (!currentChainId) {\n return undefined;\n }\n\n return AccountId.format({\n chainId: {\n namespace: NAMESPACES.ETHEREUM,\n reference: currentChainId,\n },\n address,\n });\n}\n\n// It's enough to return only connected network for the EVM networks and ignore others\nexport function filterEvmAccounts(\n accounts: {\n address: string;\n chainId: string;\n }[],\n currentChainId?: string\n) {\n let firstEvmAddress = false;\n return accounts\n .filter(({ address, chainId }) => {\n const isEvm = isEvmAddress(address);\n if (!isEvm) {\n return false;\n }\n if (currentChainId && chainId !== currentChainId) {\n return false;\n }\n if (!currentChainId) {\n if (firstEvmAddress) {\n return false;\n }\n firstEvmAddress = true;\n }\n return true;\n })\n .map(({ address, chainId }) => ({\n accounts: [address],\n chainId: chainId,\n }));\n}\n\nexport async function switchOrAddEvmChain(\n client: ISignClient,\n session: SessionTypes.Struct,\n meta: BlockchainMeta[],\n requestedNetwork: string,\n currentNetwork: string\n) {\n const evmBlockchains = meta.filter(isEvmBlockchain);\n const evmNetworksChainInfo =\n convertEvmBlockchainMetaToEvmChainInfo(evmBlockchains);\n const targetChain = evmNetworksChainInfo[requestedNetwork];\n const targetBlockchain = meta.find(\n (blockchain: BlockchainMeta) => blockchain.name === requestedNetwork\n );\n const chainIdInHex = targetBlockchain?.chainId;\n\n const currentChainId = getChainIdByNetworkName(currentNetwork, meta);\n const currentChainEip = ChainId.format({\n namespace: NAMESPACES.ETHEREUM,\n reference: String(currentChainId),\n });\n\n try {\n await client.request({\n topic: session.topic,\n request: {\n method: EthereumRPCMethods.SWITCH_CHAIN,\n params: [\n {\n chainId: chainIdInHex,\n },\n ],\n },\n // It's required to pass current chain, otherwise it won't work\n chainId: currentChainEip,\n });\n } catch (err) {\n // EIP-1193 \"Unrecognized chain ID\" - the wallet doesn't have this chain yet.\n const addChainError = 4902;\n const { code, message } = (err ?? {}) as {\n code?: number;\n message?: string;\n };\n if (code === addChainError || message?.includes(String(addChainError))) {\n await client.request({\n topic: session.topic,\n request: {\n method: EthereumRPCMethods.ADD_CHAIN,\n params: [targetChain],\n },\n // It's required to pass current chain, otherwise it won't work\n chainId: currentChainEip,\n });\n } else {\n throw err;\n }\n }\n}\n\n/**\n * Adds the requested and current chains' accounts to the session so sign-client\n * accepts a request carrying their CAIP chain id, and returns the session to use\n * from here on.\n *\n * The record is rebuilt rather than pushed into: the struct is shared with the\n * store and the adapter cache, and the write below can fail (it is logged, not\n * thrown), which would otherwise leave both holding accounts the store never\n * accepted.\n */\nexport async function updateSessionAccounts(\n client: ISignClient,\n session: SessionTypes.Struct,\n requestedNetwork: string,\n currentNetwork: string,\n meta: BlockchainMeta[]\n): Promise<SessionTypes.Struct> {\n const evmNamespace = session.namespaces[NAMESPACES.ETHEREUM];\n const currentAccountAddress = getCurrentEvmAccountAddress(session);\n if (!evmNamespace || !currentAccountAddress) {\n return session;\n }\n\n const existing = evmNamespace.accounts ?? [];\n const wanted = [\n getEvmAccount(requestedNetwork, currentAccountAddress, meta),\n getEvmAccount(currentNetwork, currentAccountAddress, meta),\n ].filter(\n (account): account is string => !!account && !existing.includes(account)\n );\n\n if (!wanted.length) {\n return session;\n }\n\n const updated: SessionTypes.Struct = {\n ...session,\n namespaces: {\n ...session.namespaces,\n [NAMESPACES.ETHEREUM]: {\n ...evmNamespace,\n accounts: [...existing, ...new Set(wanted)],\n },\n },\n };\n\n try {\n await client.session.update(session.topic, {\n namespaces: updated.namespaces,\n });\n } catch (err) {\n debug(err instanceof Error ? err : new Error(String(err)));\n return session;\n }\n\n return updated;\n}\n\nexport function ignoreNamespaceMethods(session: SessionTypes.Struct): boolean {\n const WALLETS_WITH_WRONG_NAMESPACE_METHODS = ['trust', '1inch'];\n const peerName = session.peer?.metadata?.name;\n return WALLETS_WITH_WRONG_NAMESPACE_METHODS.some((name) =>\n peerName?.toLowerCase()?.includes(name)\n );\n}\n", "import type { AppKitModal } from '../adapter/modal.js';\nimport type {\n ConnectParams,\n CreateSessionParams,\n Environments,\n SignClientInstance,\n WalletConnectNamespace,\n} from '../types.js';\nimport type { ISignClient, SessionTypes } from '@walletconnect/types';\nimport type UniversalProvider from '@walletconnect/universal-provider';\n\nimport { debug } from '@rango-dev/logging-core';\n\nimport { prepareModalForNamespace } from '../adapter/modal.js';\nimport { timeout } from '../utils.js';\nimport { PING_TIMEOUT, WC_NAMESPACE_TO_CAIP } from '../wcConstants.js';\n\nimport { getAccountsFromSession } from './accounts.js';\nimport { filterBip122Accounts, resolveBip122Session } from './bip122.js';\nimport { getPersistedChainId } from './chain-state.js';\nimport { filterEvmAccounts } from './evm.js';\nimport { findSessionByNamespace } from './lookup.js';\nimport { generateOptionalNamespace } from './proposals.js';\nimport {\n cleanupStaleSessionsForNamespace,\n hasActivePairing,\n hasActiveSession,\n purgeOrphanedPairings,\n purgeOrphanedSessions,\n removeSessionRecord,\n} from './teardown.js';\n\nexport type RestoreWalletConnectSessionOptions = {\n validateAccounts?: boolean;\n};\n\nexport async function restoreWalletConnectSession(\n client: SignClientInstance,\n namespace: WalletConnectNamespace,\n options: RestoreWalletConnectSessionOptions = {}\n): Promise<SessionTypes.Struct | undefined> {\n const session = await restoreNamespaceSession(client, namespace);\n if (!session) {\n return undefined;\n }\n\n /*\n * Never wait for `bip122_addressesChanged` here. The wallet only emits it just\n * after approval, so a stored session that still has no account will never be\n * given one - waiting would stall for the full timeout and fail anyway. Report\n * it as unrestorable instead and let the caller negotiate a fresh session.\n */\n if (namespace === 'utxo' && filterBip122Accounts(session).length === 0) {\n return undefined;\n }\n\n if (options.validateAccounts) {\n const isValid = await hasNamespaceAccounts(client, namespace, session);\n if (!isValid) {\n return undefined;\n }\n }\n\n return session;\n}\n\nasync function hasNamespaceAccounts(\n client: SignClientInstance,\n namespace: WalletConnectNamespace,\n session: SessionTypes.Struct\n): Promise<boolean> {\n if (namespace === 'utxo') {\n return filterBip122Accounts(session).length > 0;\n }\n\n const accounts = getAccountsFromSession(session);\n const currentChainId = await getPersistedChainId(client);\n return filterEvmAccounts(accounts, currentChainId).length > 0;\n}\n\n/**\n * Ping the session topic and return it if still valid.\n * Returns undefined (instead of throwing) when storage contains stale records.\n */\nexport async function restoreNamespaceSession(\n client: SignClientInstance,\n namespace: WalletConnectNamespace\n): Promise<SessionTypes.Struct | undefined> {\n const session = findSessionByNamespace(client, namespace);\n if (!session?.topic) {\n return undefined;\n }\n\n if (!hasActiveSession(client, session.topic)) {\n await removeSessionRecord(client, session);\n return undefined;\n }\n\n if (session.pairingTopic && !hasActivePairing(client, session.pairingTopic)) {\n await removeSessionRecord(client, session);\n return undefined;\n }\n\n try {\n await timeout(\n client.ping({\n topic: session.topic,\n }),\n PING_TIMEOUT\n );\n } catch (error) {\n debug(error instanceof Error ? error : new Error(String(error)));\n await removeSessionRecord(client, session);\n return undefined;\n }\n\n return findSessionByNamespace(client, namespace) ?? session;\n}\n\n/**\n * Clears unusable records ahead of a connect: orphaned sessions across every\n * namespace, plus `namespace`'s own stale ones.\n *\n * A *live* session belonging to another namespace is deliberately left alone -\n * EVM and UTXO each own an independent session, and only the namespace being\n * disconnected drops its own.\n */\nexport async function prepareWalletConnectNamespace(\n client: UniversalProvider['client'],\n namespace: WalletConnectNamespace\n): Promise<void> {\n await purgeOrphanedSessions(client);\n await cleanupStaleSessionsForNamespace(client, namespace);\n await purgeOrphanedPairings(client);\n}\n\n/**\n * Restores `namespace`'s session, or negotiates a new one.\n *\n * Callers are expected to have run {@link prepareWalletConnectNamespace} first -\n * this does not clean up on its own.\n */\nexport async function connectWalletConnectSession(\n client: UniversalProvider['client'],\n web3Modal: AppKitModal,\n params: ConnectParams\n): Promise<SessionTypes.Struct> {\n const { chains, namespace, chainReference } = params;\n\n const restored = await restoreWalletConnectSession(client, namespace);\n if (restored) {\n return restored;\n }\n\n const proposal = generateOptionalNamespace(\n chains,\n [namespace],\n chainReference\n );\n const session = await createSession(\n client,\n web3Modal,\n { optionalNamespaces: proposal ?? {} },\n {\n envs: params.envs,\n namespace,\n }\n );\n\n /*\n * Only a just-approved session can be waited on: bitcoin wallets routinely\n * approve bip122 with no account and send it moments later. A restored session\n * never reaches here, so the wait can't be spent on one that will never\n * receive the event.\n */\n if (namespace === 'utxo') {\n return resolveBip122Session(client, session);\n }\n\n return session;\n}\n\nasync function createSession(\n client: ISignClient,\n web3Modal: AppKitModal,\n options: CreateSessionParams,\n configs: {\n envs: Environments;\n namespace: WalletConnectNamespace;\n }\n): Promise<SessionTypes.Struct> {\n const { optionalNamespaces, pairingTopic } = options;\n\n try {\n const { uri, approval } = await client.connect({\n optionalNamespaces,\n pairingTopic,\n });\n\n let onCloseModal;\n if (uri) {\n const redirectLink = configs.envs.DISABLE_MODAL_AND_OPEN_LINK;\n if (redirectLink) {\n const url = `${redirectLink}/wc?uri=${encodeURIComponent(uri)}`;\n window.open(url, '_blank', 'noreferrer noopener');\n } else {\n await prepareModalForNamespace(web3Modal, configs.namespace);\n /*\n * `namespace` scopes the wallet list AppKit renders. It isn't in\n * AppKit's `OpenOptions` type but is honored at runtime, so it goes\n * through a pre-built object (an inline literal would trip the\n * excess-property check). `WC_NAMESPACE_TO_CAIP` is the single source\n * for the alias -> CAIP prefix instead of sniffing the payload keys.\n */\n const openOptions = {\n uri,\n namespace: WC_NAMESPACE_TO_CAIP[configs.namespace],\n };\n await web3Modal.open(openOptions);\n\n onCloseModal = new Promise((_, reject) => {\n web3Modal.subscribeState((state) => {\n if (!state.open) {\n reject(new Error('Modal has been closed.'));\n }\n });\n });\n }\n }\n\n const session = approval();\n\n if (onCloseModal) {\n const result = await Promise.race([session, onCloseModal]);\n return result as SessionTypes.Struct;\n }\n return await session;\n } finally {\n void web3Modal.close();\n }\n}\n", "import type { WalletConnectNamespace } from '../types.js';\nimport type { AppKitNetwork } from '@reown/appkit-common';\nimport type UniversalProvider from '@walletconnect/universal-provider';\n\nimport { createAppKit } from '@reown/appkit/core';\n\nimport { bitcoin, mainnet } from './networks.js';\n\nexport type AppKitModal = ReturnType<typeof createAppKitModal>;\n\nconst DEFAULT_MODAL_Z_INDEX = 999_999_999;\n\nexport type ModalParams = {\n projectId: string;\n universalProvider: UniversalProvider;\n themeMode?: 'light' | 'dark';\n zIndex?: number;\n};\n\n/*\n * Every WalletConnect namespace shares one AppKit instance with all networks\n * registered up front. A per-namespace instance had to be rebuilt on each\n * switch, and every rebuild re-ran AppKit init against its module-level\n * singleton controllers - leaving router history from the previous open mixed\n * into the next (a stray back button in the modal header). The active network\n * is chosen per connect with `switchNetwork` instead.\n *\n * The active network is now shared mutable state, so this is only safe while\n * connects are serialized (the adapter's `#sessionQueue`): the switch/open/close\n * for one namespace never interleaves with another's. A connect path that\n * bypassed that queue would race this switch.\n */\nconst NETWORKS: [AppKitNetwork, ...AppKitNetwork[]] = [mainnet, bitcoin];\n\n/**\n * The network to make active before opening the modal for a namespace. Keyed by\n * `WalletConnectNamespace` so a future namespace is a compile error until mapped.\n */\nconst NAMESPACE_NETWORK: Record<WalletConnectNamespace, AppKitNetwork> = {\n evm: mainnet,\n utxo: bitcoin,\n};\n\n/**\n * Make a namespace's network active before opening the shared modal.\n *\n * `open()` compares the requested namespace against AppKit's active chain: if\n * they differ it treats the open as a network switch and pushes an extra step\n * onto the router, which leaves a stray back button in the modal header. One\n * shared instance keeps whatever chain the previous connect left active, so we\n * switch it to the target here first - then `open()` sees a matching chain and\n * takes its clean, non-switching path.\n *\n * `ready()` first so AppKit init has registered the networks `switchNetwork`\n * looks up.\n */\nexport async function prepareModalForNamespace(\n web3Modal: AppKitModal,\n namespace: WalletConnectNamespace\n): Promise<void> {\n await web3Modal.ready();\n await web3Modal.switchNetwork(NAMESPACE_NETWORK[namespace]);\n}\n\nexport function createAppKitModal({\n projectId,\n universalProvider,\n themeMode = 'light',\n zIndex = DEFAULT_MODAL_Z_INDEX,\n}: ModalParams) {\n return createAppKit({\n projectId,\n networks: NETWORKS,\n universalProvider,\n /*\n * AppKit is intentionally kept out of the WalletConnect session lifecycle -\n * it renders the modal (QR + wallet list), nothing more. We drive the\n * handshake ourselves with `client.connect()` (see `session/lifecycle.ts`).\n *\n * Why: AppKit models one unified, multi-chain session with a single active\n * chain and its own reconnect/sync. The hub needs the opposite - EVM and\n * UTXO as independent sessions that connect, disconnect and eager-restore\n * separately (the adapter keeps one cache entry per namespace). Letting\n * AppKit drive via `provider.connect()` accumulates namespaces into a single\n * proposal, so connecting BTC after EVM asks the wallet for Ethereum - it was\n * tried and reverted. `manualWCControl: true` is AppKit's supported flag for\n * exactly this \"you render, I connect\" split.\n *\n * The visible cost: because we own the lifecycle, `provider.session` is never\n * set. With `enableReconnect: false`, AppKit init runs\n * `unSyncExistingConnection()`, whose `provider.disconnect()` hits a\n * `if (!this.session) throw` guard and AppKit logs the caught error as\n * `UniversalAdapter:disconnect - error: Please call connect() before\n * enable()`. It is expected and harmless - AppKit looking for a session to\n * clean up, finding none.\n *\n * Do NOT \"fix\" the log. Enabling reconnect makes AppKit actively restore/sync\n * connections it doesn't own, racing our own restore path and serialize\n * queue. Assigning `provider.session` removes the guard so that disconnect\n * (and every other AppKit-initiated disconnect) succeeds for real, tearing\n * down a live session on AppKit's schedule instead of ours. Both trade a\n * cosmetic log for real state conflicts.\n */\n enableReconnect: false,\n defaultNetwork: mainnet,\n defaultAccountTypes: { bip122: 'payment' },\n manualWCControl: true,\n /*\n * We register only one EVM network (`mainnet`) but the session approves every\n * EVM chain, so a network switch can land on a chain AppKit considers\n * \"unsupported\" and it auto-opens its UnsupportedChain modal\n * (ChainController.showUnsupportedChainUI). Allow it so AppKit doesn't police\n * the network we manage ourselves.\n */\n allowUnsupportedChain: true,\n themeMode,\n themeVariables: {\n '--apkt-z-index': zIndex,\n },\n });\n}\n", "import type { AppKitNetwork, CaipNetwork } from '@reown/appkit-common';\n\n/*\n * The two networks AppKit renders the modal for, defined here instead of\n * imported from `@reown/appkit/networks`.\n *\n * That entry point is `export * from 'viem/chains'` plus AppKit's own non-EVM\n * chains, so importing a single name off it pulls every viem chain definition\n * into the consumer's bundle. One of them (`tempo`) re-exports viem's tempo\n * chainConfig, which reaches `ox`'s salt-mining worker pool - and that module\n * routes `await import(id)` through a variable so bundlers skip\n * `node:worker_threads` in the browser. webpack can't resolve the expression\n * and warns \"Critical dependency: the request of a dependency is an\n * expression\"; react-scripts promotes warnings to errors on CI, which fails\n * the build for anyone consuming the widget through Create React App.\n *\n * viem publishes no per-chain subpath (`./chains` is the only export), so\n * there is no narrower import to reach for - the definitions are plain data,\n * so we carry the two we need.\n *\n * Keep these in sync with upstream if AppKit's `bitcoin` or viem's `mainnet`\n * changes: `@reown/appkit/dist/esm/src/networks/bitcoin.js` and\n * `viem/_esm/chains/definitions/mainnet.js`.\n */\n\n/**\n * Mirrors `defineChain` from both `viem/chains` and AppKit's networks module -\n * they are the same three-key spread. Declaring the viem-only formatter fields\n * keeps the objects structurally identical to the ones AppKit used to receive.\n */\nfunction defineChain<const chain extends AppKitNetwork>(chain: chain) {\n return {\n formatters: undefined,\n fees: undefined,\n serializers: undefined,\n ...chain,\n };\n}\n\n/** viem's `mainnet`, the only EVM network we register. */\nexport const mainnet = defineChain({\n id: 1,\n caipNetworkId: 'eip155:1',\n chainNamespace: 'eip155',\n name: 'Ethereum',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://eth.merkle.io'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Etherscan',\n url: 'https://etherscan.io',\n apiUrl: 'https://api.etherscan.io/api',\n },\n },\n contracts: {\n ensUniversalResolver: {\n address: '0xeeeeeeee14d718c2b47d9923deab1335e144eeee',\n blockCreated: 23_085_558,\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 14_353_601,\n },\n },\n} satisfies CaipNetwork);\n\n/** AppKit's `bitcoin`, the only UTXO network we register. */\nexport const bitcoin = defineChain({\n id: '000000000019d6689c085ae165831e93',\n caipNetworkId: 'bip122:000000000019d6689c085ae165831e93',\n chainNamespace: 'bip122',\n name: 'Bitcoin',\n nativeCurrency: {\n name: 'Bitcoin',\n symbol: 'BTC',\n decimals: 8,\n },\n rpcUrls: {\n default: { http: ['https://rpc.walletconnect.org/v1'] },\n },\n} satisfies CaipNetwork);\n", "import type { SignClientInstance } from '../types.js';\nimport type { SessionTypes, SignClientTypes } from '@walletconnect/types';\n\nimport { debug } from '@rango-dev/logging-core';\nimport { CAIP_BITCOIN_CHAIN_ID } from '@rango-dev/wallets-core/namespaces/utxo';\nimport { AccountId } from 'caip';\n\nimport { BitcoinEvents, NAMESPACES } from '../wcConstants.js';\n\nexport function getBip122AccountsFromSession(\n session: SessionTypes.Struct\n): string[] {\n return session.namespaces[NAMESPACES.BITCOIN]?.accounts ?? [];\n}\n\nexport function filterBip122Accounts(session: SessionTypes.Struct) {\n return getBip122AccountsFromSession(session).map((account) => ({\n address: new AccountId(account).address,\n }));\n}\n\nexport type Bip122AddressEntry = {\n address: string;\n intention?: 'payment' | 'ordinal';\n};\n\n/**\n * Every address a `bip122_addressesChanged` payload carries, in wallet order.\n * Unlike {@link pickPaymentAddress} it makes no guess about which one is active.\n */\nexport function getAnnouncedAddresses(\n data: Bip122AddressEntry[] | string[] | undefined\n): string[] {\n if (!data?.length) {\n return [];\n }\n\n return data\n .map((entry) => (typeof entry === 'string' ? entry : entry?.address))\n .filter((address): address is string => !!address);\n}\n\nexport function pickPaymentAddress(\n data: Bip122AddressEntry[] | string[] | undefined\n): string | undefined {\n if (!data?.length) {\n return undefined;\n }\n\n const first = data[0];\n if (typeof first === 'string') {\n return first;\n }\n\n const entries = data as Bip122AddressEntry[];\n return (\n entries.find((entry) => entry.intention === 'payment')?.address ??\n entries[0]?.address\n );\n}\n\nexport function patchBip122SessionAccount(\n session: SessionTypes.Struct,\n address: string\n): SessionTypes.Struct {\n const btcNamespace = session.namespaces[NAMESPACES.BITCOIN];\n if (!btcNamespace) {\n return session;\n }\n\n const caipAccount = new AccountId({\n chainId: {\n namespace: NAMESPACES.BITCOIN,\n reference: CAIP_BITCOIN_CHAIN_ID,\n },\n address,\n }).toString();\n\n const accounts = btcNamespace.accounts ?? [];\n const hasAccount = accounts.some(\n (account) =>\n new AccountId(account).address.toLowerCase() === address.toLowerCase()\n );\n\n if (hasAccount) {\n return session;\n }\n\n return {\n ...session,\n namespaces: {\n ...session.namespaces,\n [NAMESPACES.BITCOIN]: {\n ...btcNamespace,\n accounts: [...accounts, caipAccount],\n },\n },\n };\n}\n\nconst BIP122_ACCOUNT_TIMEOUT = 15_000;\n\n/**\n * Bitcoin wallets often approve bip122 without accounts in the session object.\n * They emit bip122_addressesChanged or session_update shortly after approval.\n */\nexport async function resolveBip122Session(\n client: SignClientInstance,\n session: SessionTypes.Struct\n): Promise<SessionTypes.Struct> {\n const existing = filterBip122Accounts(session);\n if (existing.length) {\n return session;\n }\n\n const freshSession = client.session.get(session.topic) ?? session;\n const freshAccounts = filterBip122Accounts(freshSession);\n if (freshAccounts.length) {\n return freshSession;\n }\n\n const { address, session: resolvedSession } =\n await waitForBip122PaymentAddress(client, freshSession);\n\n const patched = patchBip122SessionAccount(resolvedSession, address);\n await persistSessionNamespaces(client, patched);\n return patched;\n}\n\n/**\n * The address the wallet reports via `bip122_addressesChanged` lands only on our\n * patched copy, so write it back to `client.session` - the record that restore,\n * teardown and staleness checks all read. Left unpersisted, the stored session\n * keeps `bip122.accounts === []`: `cleanupStaleSessionsForNamespace` reads a live\n * session as stale and disconnects it, and a reload waits again for an event the\n * wallet only emits right after approval.\n */\nasync function persistSessionNamespaces(\n client: SignClientInstance,\n session: SessionTypes.Struct\n): Promise<void> {\n try {\n await client.session.update(session.topic, {\n namespaces: session.namespaces,\n });\n } catch (error) {\n debug(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\nasync function waitForBip122PaymentAddress(\n client: SignClientInstance,\n session: SessionTypes.Struct,\n timeoutMs = BIP122_ACCOUNT_TIMEOUT\n): Promise<{ address: string; session: SessionTypes.Struct }> {\n return await new Promise((resolve, reject) => {\n const topic = session.topic;\n let settled = false;\n\n const finish = (address: string, updatedSession: SessionTypes.Struct) => {\n if (settled) {\n return;\n }\n settled = true;\n cleanup();\n resolve({ address, session: updatedSession });\n };\n\n const fail = (error: Error) => {\n if (settled) {\n return;\n }\n settled = true;\n cleanup();\n reject(error);\n };\n\n const timer = setTimeout(() => {\n fail(\n new Error(\n 'Timed out waiting for Bitcoin account from wallet. Please try reconnecting.'\n )\n );\n }, timeoutMs);\n\n const cleanup = () => {\n clearTimeout(timer);\n client.off('session_event', onEvent);\n client.off('session_update', onUpdate);\n };\n\n const onEvent = (args: SignClientTypes.EventArguments['session_event']) => {\n if (args.topic !== topic) {\n return;\n }\n if (args.params.event.name !== BitcoinEvents.ADDRESSES_CHANGED) {\n return;\n }\n\n const address = pickPaymentAddress(\n args.params.event.data as Bip122AddressEntry[]\n );\n if (address) {\n finish(address, client.session.get(topic) ?? session);\n }\n };\n\n const onUpdate = (\n args: SignClientTypes.EventArguments['session_update']\n ) => {\n if (args.topic !== topic) {\n return;\n }\n\n const updatedSession = client.session.get(topic) ?? session;\n const accounts = filterBip122Accounts(updatedSession);\n if (accounts.length) {\n finish(accounts[0].address, updatedSession);\n }\n };\n\n client.on('session_event', onEvent);\n client.on('session_update', onUpdate);\n });\n}\n", "import type { WalletConnectNamespace } from '../types.js';\nimport type { ISignClient, SessionTypes } from '@walletconnect/types';\n\nimport { WC_NAMESPACE_TO_CAIP } from '../wcConstants.js';\n\nexport function getCaipNamespace(namespace: WalletConnectNamespace): string {\n return WC_NAMESPACE_TO_CAIP[namespace];\n}\n\nexport function findSessionByNamespace(\n client: ISignClient,\n namespace: WalletConnectNamespace\n): SessionTypes.Struct | undefined {\n const caipNamespace = getCaipNamespace(namespace);\n\n return client.session.getAll().find((session) => {\n const ns = session.namespaces[caipNamespace];\n if ((ns?.accounts?.length ?? 0) > 0) {\n return true;\n }\n\n return namespace === 'utxo' && (ns?.chains?.length ?? 0) > 0;\n });\n}\n\nexport function getSessionNamespace(\n session: SessionTypes.Struct\n): WalletConnectNamespace | undefined {\n const hasAccounts = (namespace: WalletConnectNamespace) =>\n (session.namespaces[WC_NAMESPACE_TO_CAIP[namespace]]?.accounts?.length ??\n 0) > 0;\n const hasChains = (namespace: WalletConnectNamespace) =>\n (session.namespaces[WC_NAMESPACE_TO_CAIP[namespace]]?.chains?.length ?? 0) >\n 0;\n\n /*\n * Prefer a namespace the wallet shared accounts for; fall back to one that\n * only negotiated chains (utxo can be chains-only before its account settles).\n */\n if (hasAccounts('evm')) {\n return 'evm';\n }\n if (hasAccounts('utxo')) {\n return 'utxo';\n }\n if (hasChains('utxo')) {\n return 'utxo';\n }\n if (hasChains('evm')) {\n return 'evm';\n }\n\n return undefined;\n}\n", "import type { WalletConnectNamespace } from '../types.js';\nimport type { ChainIdParams } from 'caip';\n\nimport { CAIP_BITCOIN_CHAIN_ID } from '@rango-dev/wallets-core/namespaces/utxo';\nimport { ChainId } from 'caip';\n\nimport {\n DEFAULT_BITCOIN_EVENTS,\n DEFAULT_BITCOIN_METHODS,\n DEFAULT_ETHEREUM_EVENTS,\n DEFAULT_ETHEREUM_METHODS,\n NAMESPACES,\n WC_NAMESPACE_TO_CAIP,\n} from '../wcConstants.js';\n\n/**\n * `chains` is required here so the same shape is assignable both to the\n * SignClient `ProposalTypes` (chains optional) and to the UniversalProvider\n * `NamespaceConfig` (chains required).\n */\nexport type FinalNamespaces = Record<\n string,\n { chains: string[]; methods: string[]; events: string[] }\n>;\n\ntype NamespaceProposal = {\n methods: string[];\n events: string[];\n resolveChains: (\n chains: ChainIdParams[],\n targetChainReference?: string\n ) => ChainIdParams[];\n};\n\n/**\n * Per-namespace proposal facts as data, keyed by `WalletConnectNamespace` so a\n * newly-added alias is a compile error until it's configured here. The CAIP\n * prefix comes from the shared `WC_NAMESPACE_TO_CAIP` map.\n */\nconst NAMESPACE_PROPOSALS: Record<WalletConnectNamespace, NamespaceProposal> = {\n evm: {\n methods: DEFAULT_ETHEREUM_METHODS,\n events: DEFAULT_ETHEREUM_EVENTS,\n resolveChains: (chains, targetChainReference) => {\n if (targetChainReference) {\n return [\n { namespace: NAMESPACES.ETHEREUM, reference: targetChainReference },\n ];\n }\n return chains.length > 0\n ? chains\n : [{ namespace: NAMESPACES.ETHEREUM, reference: '1' }];\n },\n },\n utxo: {\n methods: DEFAULT_BITCOIN_METHODS,\n events: DEFAULT_BITCOIN_EVENTS,\n resolveChains: () => [\n { namespace: NAMESPACES.BITCOIN, reference: CAIP_BITCOIN_CHAIN_ID },\n ],\n },\n};\n\n/**\n * Builds a WalletConnect namespace proposal (chains, methods, events).\n *\n * The result always goes to `optionalNamespaces`: sign-client merges\n * `requiredNamespaces` into `optionalNamespaces` and clears it before sending\n * the proposal, so passing anything as required only earns a deprecation\n * warning. Narrowing the proposal (see `targetChainReference`) is what actually\n * constrains what the wallet can approve.\n *\n * @param targetChainReference - When set for EVM, limits the proposal to this\n * single chain id (decimal string, e.g. `\"137\"`). Omit to include all EVM\n * chains from `chains`.\n */\nexport function generateOptionalNamespace(\n chains: ChainIdParams[],\n namespaces: WalletConnectNamespace[],\n targetChainReference?: string\n): FinalNamespaces | undefined {\n const proposal: FinalNamespaces = {};\n\n for (const namespace of namespaces) {\n const config = NAMESPACE_PROPOSALS[namespace];\n proposal[WC_NAMESPACE_TO_CAIP[namespace]] = {\n methods: config.methods,\n events: config.events,\n chains: config\n .resolveChains(chains, targetChainReference)\n .map((chain) => new ChainId(chain).toString()),\n };\n }\n\n return Object.keys(proposal).length > 0 ? proposal : undefined;\n}\n", "import type { SignClientInstance, WalletConnectNamespace } from '../types.js';\nimport type { ISignClient, SessionTypes } from '@walletconnect/types';\nimport type UniversalProvider from '@walletconnect/universal-provider';\n\nimport { debug } from '@rango-dev/logging-core';\nimport { getSdkError } from '@walletconnect/utils';\n\nimport { NAMESPACES } from '../wcConstants.js';\n\nimport { persistCurrentChainId } from './chain-state.js';\nimport { getSessionNamespace } from './lookup.js';\n\nfunction isNoMatchingKeyError(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error);\n return message.includes('No matching key');\n}\n\nexport function hasActiveSession(client: ISignClient, topic: string): boolean {\n try {\n return !!client.session.get(topic);\n } catch {\n return false;\n }\n}\n\nexport function hasActivePairing(\n client: SignClientInstance,\n topic: string\n): boolean {\n return client.pairing.getAll().some((pairing) => pairing.topic === topic);\n}\n\nexport async function expireWalletConnectTopic(\n client: SignClientInstance,\n topic: string\n) {\n const sessions = client.session.getAll();\n const pairings = client.pairing.getAll();\n\n sessions.forEach((session: SessionTypes.Struct) => {\n if (session.topic === topic || session.pairingTopic === topic) {\n const requestForDeleteTopic =\n session.pairingTopic === topic ? session.pairingTopic : session.topic;\n client.core.expirer.set(requestForDeleteTopic, 0);\n }\n });\n\n pairings.forEach((pairing) => {\n if (pairing.topic === topic) {\n client.core.expirer.set(topic, 0);\n }\n });\n}\n\nexport async function removeSessionRecord(\n client: SignClientInstance,\n session: SessionTypes.Struct\n) {\n const namespace = getSessionNamespace(session);\n const pairingTopic = session.pairingTopic;\n\n if (hasActiveSession(client, session.topic)) {\n try {\n await client.disconnect({\n topic: session.topic,\n reason: getSdkError('USER_DISCONNECTED'),\n });\n } catch (error) {\n debug(error instanceof Error ? error : new Error(String(error)));\n if (isNoMatchingKeyError(error)) {\n await expireWalletConnectTopic(client, session.topic);\n }\n }\n } else {\n await expireWalletConnectTopic(client, session.topic);\n }\n\n const remainingOnPairing = client.session\n .getAll()\n .filter((item) => item.pairingTopic === pairingTopic);\n\n if (!remainingOnPairing.length && pairingTopic) {\n if (hasActivePairing(client, pairingTopic)) {\n try {\n await client.disconnect({\n topic: pairingTopic,\n reason: getSdkError('USER_DISCONNECTED'),\n });\n } catch (error) {\n debug(error instanceof Error ? error : new Error(String(error)));\n if (isNoMatchingKeyError(error)) {\n await expireWalletConnectTopic(client, pairingTopic);\n }\n }\n } else {\n await expireWalletConnectTopic(client, pairingTopic);\n }\n }\n\n if (namespace === 'evm') {\n void persistCurrentChainId(client, undefined);\n }\n}\n\nexport async function purgeOrphanedSessions(\n client: SignClientInstance\n): Promise<void> {\n const pairingTopics = new Set(\n client.pairing.getAll().map((pairing) => pairing.topic)\n );\n\n for (const session of [...client.session.getAll()]) {\n const pairingOrphaned =\n !!session.pairingTopic && !pairingTopics.has(session.pairingTopic);\n const sessionMissing = !hasActiveSession(client, session.topic);\n\n if (pairingOrphaned || sessionMissing) {\n await removeSessionRecord(client, session);\n }\n }\n}\n\n/**\n * Drops pairings that no session is using.\n *\n * The inverse of {@link purgeOrphanedSessions}, and the only thing that collects\n * them: a cancelled connect leaves behind the pairing `client.connect()` minted,\n * and `cleanupPendingPairings` only unsubscribes pairings - it never deletes the\n * record. Without this they accumulate in `client.pairing` and in storage for the\n * lifetime of the origin.\n *\n * Only safe to call while no connect is in flight (the adapter's `#sessionQueue`\n * guarantees that): a pairing awaiting its first approval has no session yet, so\n * dropping it would kill that handshake.\n */\nexport async function purgeOrphanedPairings(\n client: SignClientInstance\n): Promise<void> {\n const usedPairingTopics = new Set(\n client.session\n .getAll()\n .map((session) => session.pairingTopic)\n .filter((topic): topic is string => !!topic)\n );\n\n for (const pairing of [...client.pairing.getAll()]) {\n if (usedPairingTopics.has(pairing.topic)) {\n continue;\n }\n\n try {\n await client.disconnect({\n topic: pairing.topic,\n reason: getSdkError('USER_DISCONNECTED'),\n });\n } catch (error) {\n debug(error instanceof Error ? error : new Error(String(error)));\n await expireWalletConnectTopic(client, pairing.topic);\n }\n }\n}\n\nexport async function cleanupStaleSessionsForNamespace(\n client: UniversalProvider['client'],\n namespace: WalletConnectNamespace\n): Promise<void> {\n for (const existing of client.session.getAll()) {\n if (getSessionNamespace(existing) !== namespace) {\n continue;\n }\n\n const btc = existing.namespaces[NAMESPACES.BITCOIN];\n if (\n btc &&\n (btc.chains?.length ?? 0) > 0 &&\n (btc.accounts?.length ?? 0) === 0\n ) {\n await removeSessionRecord(client, existing);\n }\n }\n}\n", "import type { SessionCache } from '../adapter/session-cache.js';\nimport type { SignClientInstance, WalletConnectNamespace } from '../types.js';\nimport type { SessionTypes } from '@walletconnect/types';\n\nimport { debug } from '@rango-dev/logging-core';\n\nimport {\n restoreWalletConnectSession,\n type RestoreWalletConnectSessionOptions,\n} from './lifecycle.js';\n\nexport async function restoreAndCacheSession(\n client: SignClientInstance,\n namespace: WalletConnectNamespace,\n cache: SessionCache,\n options?: RestoreWalletConnectSessionOptions,\n onDisconnect?: (namespace: WalletConnectNamespace) => Promise<void>\n): Promise<SessionTypes.Struct | null> {\n try {\n const session = await restoreWalletConnectSession(\n client,\n namespace,\n options\n );\n if (!session) {\n return null;\n }\n\n cache.set(namespace, session);\n return session;\n } catch (error) {\n debug(error instanceof Error ? error : new Error(String(error)));\n if (cache.get(namespace)) {\n await onDisconnect?.(namespace);\n }\n return null;\n }\n}\n", "import type { AppKitModal, ModalParams } from './modal.js';\n\nimport { createAppKitModal } from './modal.js';\n\n/**\n * Holds the single AppKit modal for the adapter's lifetime.\n *\n * One instance serves every namespace - all its networks are registered up front\n * and the active one is chosen per connect with `switchNetwork`. It is built once\n * and reused: rebuilding per namespace re-ran AppKit init against its shared\n * singleton controllers and left stale router/filter state behind.\n */\nexport class ModalCache {\n #web3Modal: AppKitModal | null = null;\n\n getModal(params: ModalParams): AppKitModal {\n if (!this.#web3Modal) {\n this.#web3Modal = createAppKitModal(params);\n }\n\n return this.#web3Modal;\n }\n}\n", "import UniversalProvider from '@walletconnect/universal-provider';\n\nimport { DEFAULT_APP_METADATA, RELAY_URL } from '../wcConstants.js';\n\nexport async function createUniversalProvider(\n projectId: string\n): Promise<UniversalProvider> {\n return UniversalProvider.init({\n relayUrl: RELAY_URL,\n projectId,\n metadata: DEFAULT_APP_METADATA,\n });\n}\n", "import type { WalletConnectNamespace } from '../types.js';\nimport type { SessionTypes } from '@walletconnect/types';\n\nexport type SessionCache = {\n get(namespace: WalletConnectNamespace): SessionTypes.Struct | null;\n set(namespace: WalletConnectNamespace, session: SessionTypes.Struct): void;\n clear(namespace: WalletConnectNamespace): void;\n /**\n * Drops every namespace holding `topic`. A wallet may approve more than was\n * proposed, so one settled session can back both namespaces - tearing its topic\n * down under one of them would otherwise leave the other pointing at a topic\n * the relay has already dropped.\n */\n clearTopic(topic: string): void;\n clearAll(): void;\n};\n\nexport function createSessionCache(): SessionCache {\n const sessions = new Map<WalletConnectNamespace, SessionTypes.Struct>();\n\n return {\n get: (namespace) => sessions.get(namespace) ?? null,\n\n set: (namespace, session) => void sessions.set(namespace, session),\n\n clear: (namespace) => void sessions.delete(namespace),\n\n clearTopic: (topic) => {\n for (const [namespace, session] of sessions) {\n if (session.topic === topic) {\n sessions.delete(namespace);\n }\n }\n },\n\n clearAll: () => sessions.clear(),\n };\n}\n", "/**\n * Runs tasks one at a time, in the order `run` was called.\n *\n * A task that rejects passes its rejection to its own caller and does not block\n * the tasks behind it.\n */\nexport class TaskQueue {\n /** Resolves once the task currently at the back of the queue has settled. */\n #tail: Promise<void> = Promise.resolve();\n\n async run<T>(task: () => Promise<T>): Promise<T> {\n const ourTurn = this.#tail;\n\n /*\n * Take our place at the back of the queue before awaiting anything, so\n * callers arriving in the same tick line up behind us rather than all\n * reading the same `#tail`. `releaseOurTurn` never rejects, which is what\n * lets the next task run even when this one throws.\n */\n let releaseOurTurn!: () => void;\n this.#tail = new Promise<void>((resolve) => {\n releaseOurTurn = resolve;\n });\n\n await ourTurn;\n try {\n return await task();\n } finally {\n releaseOurTurn();\n }\n }\n}\n", "import type { WalletConnectAdapter } from './adapter.js';\n\n/**\n * Holds the singleton adapter instance created in the provider's `init`.\n *\n * This lives in its own leaf module (importing nothing from `provider.ts` or the\n * namespaces) to break the `provider -> namespace -> provider` import cycle that\n * otherwise throws a TDZ error (\"Cannot access 'getAdapter' before initialization\")\n * when the namespace module evaluates its top-level subscriber factories.\n */\nlet adapter: WalletConnectAdapter;\n\nexport const getAdapter = () => adapter;\n\nexport const setAdapter = (instance: WalletConnectAdapter) => {\n adapter = instance;\n};\n", "import type { ProviderMetadata } from '@hub3js/core';\n\nimport { isEvmNamespace } from '@hub3js/evm';\n\nimport getSigners from './signer.js';\n\nexport const WALLET_ID = 'wallet-connect-2';\n\nexport const metadata: ProviderMetadata = {\n name: 'WalletConnect',\n icon: 'https://raw.githubusercontent.com/rango-exchange/assets/main/wallets/walletconnect/icon.svg',\n extensions: {\n homepage: 'https://walletconnect.com/',\n },\n properties: [\n {\n name: 'namespaces',\n value: {\n selection: 'single',\n data: [\n {\n label: 'EVM',\n value: 'EVM',\n id: 'ETH',\n isChainSupported: isEvmNamespace,\n },\n ],\n },\n },\n {\n name: 'signers',\n value: { getSigners: async () => getSigners() },\n },\n {\n name: 'details',\n value: {\n mobileWallet: true,\n showOnMobile: true,\n },\n },\n ],\n};\n", "import type { SignerFactory } from 'rango-types';\n\nimport { DefaultSignerFactory, TransactionType as TxType } from 'rango-types';\n\nimport { getAdapter } from './adapter/registry.js';\n\nexport default async function getSigners(): Promise<SignerFactory> {\n const adapter = getAdapter();\n if (!adapter) {\n throw new Error('WalletConnect provider has not been initialized.');\n }\n\n const client = await adapter.getClient();\n\n const signers = new DefaultSignerFactory();\n const EVMSigner = (await import('./signers/evm.js')).default;\n signers.registerSigner(\n TxType.EVM,\n new EVMSigner(client, () => adapter.getSession('evm'))\n );\n\n return signers;\n}\n", "import type { Context } from '@hub3js/core';\nimport type { EvmActions } from '@hub3js/evm';\n\nimport { NamespaceBuilder } from '@hub3js/core';\nimport { actions, builders, utils } from '@hub3js/evm';\nimport * as commonBuilders from '@hub3js/std/builders';\nimport { standardizeAndThrowError } from '@hub3js/std/operators';\n\nimport { getAdapter } from '../../adapter/registry.js';\nimport { WALLET_ID } from '../../constants.js';\nimport { getAccountsFromSession } from '../../session/accounts.js';\nimport { filterEvmAccounts } from '../../session/evm.js';\nimport { chainReferenceToHex, parseChainReference } from '../../utils.js';\n\nimport {\n sessionDeleteSubscriber,\n sessionEventSubscriber,\n sessionUpdateSubscriber,\n} from './hooks.js';\n\nconst [sessionUpdate, sessionUpdateCleanup] = sessionUpdateSubscriber();\nconst [sessionEvent, sessionEventCleanup] = sessionEventSubscriber();\nconst [sessionDelete, sessionDeleteCleanup] = sessionDeleteSubscriber();\n\nconst connect = builders\n .connect()\n .action(async function (_context: Context<EvmActions>, chain?: string) {\n const adapter = getAdapter();\n // `chain` is set when connecting to a specific network (swap auto-switch or hub connect with network).\n const requestedReference = chain ? parseChainReference(chain) : undefined;\n const session = await adapter.ensureConnectedToChain(chain);\n const activeReference =\n requestedReference ?? (await adapter.resolveActiveChainReference());\n\n if (!activeReference) {\n throw new Error(\n 'Unable to determine EVM chain id from WalletConnect session.'\n );\n }\n\n const accounts = getAccountsFromSession(session);\n const evmAccounts = filterEvmAccounts(accounts, activeReference);\n\n if (!evmAccounts.length) {\n throw new Error('No EVM accounts found in WalletConnect session.');\n }\n\n return {\n accounts: utils.formatAccountsToCAIP(\n evmAccounts.map((account) => account.accounts[0]),\n activeReference\n ),\n network: chainReferenceToHex(activeReference),\n };\n })\n .before(sessionUpdate)\n .before(sessionEvent)\n .before(sessionDelete)\n .or(sessionUpdateCleanup)\n .or(sessionEventCleanup)\n .or(sessionDeleteCleanup)\n .or((_, err) => {\n void getAdapter().disconnectSession('evm');\n return err;\n })\n .or(standardizeAndThrowError)\n .build();\n\nconst canEagerConnect = builders\n .canEagerConnect()\n .action(async () => getAdapter().tryRestoreEagerSession('evm'))\n .build();\n\nconst canSwitchNetwork = builders\n .canSwitchNetwork()\n .action(actions.canSwitchNetwork())\n .build();\n\nconst disconnect = commonBuilders\n .disconnect<EvmActions>()\n .before(async () => {\n await getAdapter().disconnectSession('evm');\n })\n .after(sessionUpdateCleanup)\n .after(sessionEventCleanup)\n .after(sessionDeleteCleanup)\n .build();\n\nconst getChainId = builders\n .getChainId()\n .action(async () => getAdapter().getCurrentChainId())\n .build();\n\nconst evm = new NamespaceBuilder<EvmActions>('EVM', WALLET_ID)\n .action(connect)\n .action(canEagerConnect)\n .action(canSwitchNetwork)\n .action(disconnect)\n .action(getChainId)\n .build();\n\nexport { evm };\n", "import type { EvmActions } from '@hub3js/evm';\n\nimport { utils } from '@hub3js/evm';\nimport { ChainId } from 'caip';\n\nimport {\n extractAddress,\n getAccountsFromEvent,\n} from '../../session/accounts.js';\nimport {\n getPersistedChainId,\n persistCurrentChainId,\n} from '../../session/chain-state.js';\nimport { filterEvmAccounts } from '../../session/evm.js';\nimport { expireWalletConnectTopic } from '../../session/teardown.js';\nimport { chainReferenceToHex, parseChainReference } from '../../utils.js';\nimport { EthereumEvents, NAMESPACES } from '../../wcConstants.js';\nimport { createSessionSubscriber } from '../subscriber.js';\n\n/**\n * WC signals an account switch via `session_update` (re-shared namespaces with the\n * newly-selected account first), so the active account is published from this event.\n */\nexport function sessionUpdateSubscriber() {\n return createSessionSubscriber<'session_update', EvmActions>(\n 'evm',\n 'session_update',\n async ({ args, session, adapter, context }) => {\n /*\n * Keep the cached struct in step with what the wallet just re-shared.\n * `switchEvmNetwork` reads the authorized chains and methods back out\n * of it, so a stale copy rejects a chain the wallet has since added\n * (`wallet_addEthereumChain` lands here as a `session_update`) with\n * \"Chain X is not configured\".\n */\n if (args.params.namespaces[NAMESPACES.ETHEREUM]) {\n adapter.cacheSession('evm', {\n ...session,\n namespaces: args.params.namespaces,\n });\n }\n\n const allAccounts = getAccountsFromEvent(args);\n if (!allAccounts.length) {\n return;\n }\n\n const entries = allAccounts.map((accountsWithChain) => ({\n address: accountsWithChain.accounts[0],\n chainId: accountsWithChain.chainId,\n }));\n\n const [getState, setState] = context.state();\n const hubNetwork = getState().network;\n const persistedChain = await getPersistedChainId(\n await adapter.getClient()\n );\n const activeReference =\n parseChainReference(hubNetwork ?? undefined) ?? persistedChain;\n\n let evmAccounts = filterEvmAccounts(entries, activeReference);\n if (!evmAccounts.length) {\n evmAccounts = filterEvmAccounts(entries);\n }\n if (!evmAccounts.length) {\n return;\n }\n\n const chainIdHex = chainReferenceToHex(evmAccounts[0].chainId);\n setState(\n 'accounts',\n utils.formatAccountsToCAIP([evmAccounts[0].accounts[0]], chainIdHex)\n );\n setState('network', chainIdHex);\n }\n );\n}\n\n/**\n * Addresses out of an `accountsChanged` payload. Spec says `string[]`, but wallets\n * forwarding the EIP-1193 event as-is send a bare value, so the shape is coerced\n * before anything reads it.\n */\nfunction eventAccounts(data: unknown): string[] {\n return (Array.isArray(data) ? data : [data])\n .filter((entry): entry is string => typeof entry === 'string' && !!entry)\n .map(extractAddress);\n}\n\n/**\n * Handles WC `session_event` payloads: EIP-1193 `accountsChanged` (publish the new\n * accounts, or disconnect when the wallet revokes them all) and `chainChanged`\n * (update and persist the active chain). Any other event is ignored.\n */\nexport function sessionEventSubscriber() {\n return createSessionSubscriber<'session_event', EvmActions>(\n 'evm',\n 'session_event',\n ({ args, adapter, context }) => {\n const [, setState] = context.state();\n\n if (args.params.event.name === EthereumEvents.ACCOUNTS_CHANGED) {\n const accounts = eventAccounts(args.params.event.data);\n /*\n * An empty payload is the wallet revoking access (locked, or the account\n * unlinked from this dApp), not a switch - there is nothing to publish.\n */\n if (!accounts.length) {\n void context.action('disconnect');\n return;\n }\n\n const chainIdHex = chainReferenceToHex(\n ChainId.parse(args.params.chainId).reference\n );\n setState('network', chainIdHex);\n setState('accounts', utils.formatAccountsToCAIP(accounts, chainIdHex));\n return;\n }\n\n if (args.params.event.name === EthereumEvents.CHAIN_CHANGED) {\n const chainIdHex = chainReferenceToHex(args.params.event.data);\n setState('network', chainIdHex);\n void adapter\n .getClient()\n .then(async (client) => persistCurrentChainId(client, chainIdHex));\n }\n }\n );\n}\n\n/**\n * Reflects a wallet-initiated `session_delete` into the hub: clears the cached\n * session, expires the WC topic, and runs the hub `disconnect` action.\n */\nexport function sessionDeleteSubscriber() {\n return createSessionSubscriber<'session_delete', EvmActions>(\n 'evm',\n 'session_delete',\n ({ args, adapter, context }) => {\n adapter.clearSession('evm');\n void adapter\n .getClient()\n .then(async (client) => expireWalletConnectTopic(client, args.topic));\n context.action('disconnect');\n }\n );\n}\n", "import type { WalletConnectAdapter } from '../adapter/adapter.js';\nimport type { WalletConnectNamespace } from '../types.js';\nimport type {\n Actions,\n Context,\n Subscriber,\n SubscriberCleanUp,\n} from '@hub3js/core';\nimport type { SessionTypes, SignClientTypes } from '@walletconnect/types';\n\nimport { debug } from '@rango-dev/logging-core';\n\nimport { getAdapter } from '../adapter/registry.js';\n\n/** The WC client events a namespace subscribes to. */\nexport type SessionEventName =\n | 'session_update'\n | 'session_event'\n | 'session_delete';\n\nexport type SessionEventHandler<\n Name extends SessionEventName,\n ActionsType extends Actions<ActionsType>\n> = (event: {\n args: SignClientTypes.EventArguments[Name];\n /** The cached session this event was matched against. */\n session: SessionTypes.Struct;\n adapter: WalletConnectAdapter;\n context: Context<ActionsType>;\n}) => void | Promise<void>;\n\nfunction logHandlerError(error: unknown) {\n debug(error instanceof Error ? error : new Error(String(error)));\n}\n\n/**\n * Builds a hub subscriber for one WC client event, scoped to one namespace.\n *\n * Every namespace hook needs the same four things - resolve the client, only act\n * on events for the session this namespace has cached, register, and unregister\n * the exact same handler reference. Getting the topic guard wrong is what makes a\n * hook act on the other namespace's session, so it lives here rather than being\n * repeated per hook.\n */\nexport function createSessionSubscriber<\n Name extends SessionEventName,\n ActionsType extends Actions<ActionsType>\n>(\n namespace: WalletConnectNamespace,\n event: Name,\n handle: SessionEventHandler<Name, ActionsType>\n): [Subscriber<ActionsType>, SubscriberCleanUp<ActionsType>] {\n let handler: ((args: SignClientTypes.EventArguments[Name]) => void) | null =\n null;\n\n return [\n async (context) => {\n const adapter = getAdapter();\n const client = await adapter.getClient();\n\n /*\n * A namespace re-runs its `before` subscribers on every connect, so drop the\n * previous registration first - otherwise each reconnect leaves another live\n * handler behind and only the last one is ever removed.\n */\n if (handler) {\n client.off(event, handler);\n }\n\n handler = (args) => {\n const session = adapter.getSession(namespace);\n if (!session || args.topic !== session.topic) {\n return;\n }\n\n /*\n * WC dispatches these from its own async request pipeline with nothing\n * catching downstream, so a throw here (a payload shaped unlike anything\n * the handler expects) would surface as an unhandled rejection and take\n * the rest of that pipeline's processing with it. Async handlers are\n * covered too - their rejection lands nowhere otherwise.\n */\n try {\n const handled = handle({ args, session, adapter, context });\n if (handled instanceof Promise) {\n void handled.catch(logHandlerError);\n }\n } catch (error) {\n logHandlerError(error);\n }\n };\n\n client.on(event, handler);\n },\n (_, err) => {\n const currentHandler = handler;\n if (currentHandler) {\n handler = null;\n void getAdapter()\n .getClient()\n .then((client) => client.off(event, currentHandler));\n }\n return err;\n },\n ];\n}\n"],
|
|
5
|
+
"mappings": "2IAAA,OAAS,kBAAAA,OAAsB,qBCE/B,OAAS,mBAAAC,OAAuB,eCIhC,OAAS,SAAAC,OAAa,0BCFtB,OAAS,SAAS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,EAAa,4BAC/B,UAAWA,EAAa,UACxB,YAAaA,EAAa,WAC5B,CAAC,CACH,EACAC,EAAS,YAAa,EAAI,EAC1B,QAAQ,MAAM,2CAA4CF,CAAO,EACnE,CAAC,EACA,OAAO,WAAYK,EAAQ,EAC3B,IAAI,MAAOC,EAAG,EACd,MAAM,EAvBW,iBDHtB,IAAMC,GAAWC,EAAA,IACfC,GAAe,EAAE,QAAQ,QAASC,GAAc,CAAC,EAAE,MAAM,EAD1C",
|
|
6
|
+
"names": ["defineVersions", "ProviderBuilder", "debug", "logError", "ChainId", "AccountId", "extractAddress", "account", "AccountId", "__name", "getAccountsFromSession", "session", "namespace", "address", "chainId", "getAccountsFromEvent", "event", "persistCurrentChainId", "client", "chainId", "CHAIN_ID_STORAGE", "__name", "getPersistedChainId", "getChainIdByNetworkName", "network", "meta", "chainIdInHex", "blockchain", "debug", "convertEvmBlockchainMetaToEvmChainInfo", "AccountId", "ChainId", "isEvmAddress", "isEvmBlockchain", "getCurrentEvmAccountAddress", "session", "account", "AccountId", "address", "isEvmAddress", "__name", "getEvmAccount", "network", "meta", "currentChainId", "getChainIdByNetworkName", "filterEvmAccounts", "accounts", "firstEvmAddress", "chainId", "switchOrAddEvmChain", "client", "requestedNetwork", "currentNetwork", "evmBlockchains", "isEvmBlockchain", "targetChain", "convertEvmBlockchainMetaToEvmChainInfo", "chainIdInHex", "blockchain", "currentChainEip", "ChainId", "err", "code", "message", "updateSessionAccounts", "evmNamespace", "currentAccountAddress", "existing", "wanted", "updated", "debug", "ignoreNamespaceMethods", "WALLETS_WITH_WRONG_NAMESPACE_METHODS", "peerName", "name", "resolveActiveChainReference", "client", "session", "persistedChainId", "getPersistedChainId", "accounts", "getAccountsFromSession", "filterEvmAccounts", "__name", "getCurrentChainId", "reference", "chainReferenceToHex", "switchEvmNetwork", "options", "meta", "requestedChainId", "currentChainId", "requestedReference", "parseChainReference", "error", "logError", "chainIdStr", "ChainId", "requestedNetwork", "resolveNetworkName", "currentNetwork", "evmNamespace", "authorizedChains", "authorizedMethods", "activeSession", "ignoreNamespaceMethods", "updateSessionAccounts", "switchOrAddEvmChain", "persistCurrentChainId", "switchToChainIfNeeded", "deps", "currentReference", "ensureConnectedToChain", "chain", "debug", "createAppKit", "defineChain", "chain", "__name", "mainnet", "bitcoin", "DEFAULT_MODAL_Z_INDEX", "NETWORKS", "mainnet", "bitcoin", "NAMESPACE_NETWORK", "prepareModalForNamespace", "web3Modal", "namespace", "__name", "createAppKitModal", "projectId", "universalProvider", "themeMode", "zIndex", "createAppKit", "debug", "CAIP_BITCOIN_CHAIN_ID", "AccountId", "getBip122AccountsFromSession", "session", "__name", "filterBip122Accounts", "account", "AccountId", "pickPaymentAddress", "data", "first", "entries", "entry", "__name", "patchBip122SessionAccount", "session", "address", "btcNamespace", "caipAccount", "AccountId", "CAIP_BITCOIN_CHAIN_ID", "accounts", "account", "BIP122_ACCOUNT_TIMEOUT", "resolveBip122Session", "client", "filterBip122Accounts", "freshSession", "resolvedSession", "waitForBip122PaymentAddress", "patched", "persistSessionNamespaces", "error", "debug", "timeoutMs", "resolve", "reject", "topic", "settled", "finish", "updatedSession", "cleanup", "fail", "timer", "onEvent", "onUpdate", "args", "getCaipNamespace", "namespace", "WC_NAMESPACE_TO_CAIP", "__name", "findSessionByNamespace", "client", "caipNamespace", "session", "ns", "getSessionNamespace", "hasAccounts", "hasChains", "CAIP_BITCOIN_CHAIN_ID", "ChainId", "NAMESPACE_PROPOSALS", "DEFAULT_ETHEREUM_METHODS", "DEFAULT_ETHEREUM_EVENTS", "chains", "targetChainReference", "DEFAULT_BITCOIN_METHODS", "DEFAULT_BITCOIN_EVENTS", "CAIP_BITCOIN_CHAIN_ID", "generateOptionalNamespace", "namespaces", "proposal", "namespace", "config", "WC_NAMESPACE_TO_CAIP", "chain", "ChainId", "__name", "debug", "getSdkError", "isNoMatchingKeyError", "error", "__name", "hasActiveSession", "client", "topic", "hasActivePairing", "pairing", "expireWalletConnectTopic", "sessions", "pairings", "session", "requestForDeleteTopic", "removeSessionRecord", "namespace", "getSessionNamespace", "pairingTopic", "getSdkError", "debug", "item", "persistCurrentChainId", "purgeOrphanedSessions", "pairingTopics", "pairingOrphaned", "sessionMissing", "purgeOrphanedPairings", "usedPairingTopics", "cleanupStaleSessionsForNamespace", "existing", "btc", "restoreWalletConnectSession", "client", "namespace", "options", "session", "restoreNamespaceSession", "filterBip122Accounts", "hasNamespaceAccounts", "__name", "accounts", "getAccountsFromSession", "currentChainId", "getPersistedChainId", "filterEvmAccounts", "findSessionByNamespace", "hasActiveSession", "removeSessionRecord", "hasActivePairing", "timeout", "error", "debug", "prepareWalletConnectNamespace", "purgeOrphanedSessions", "cleanupStaleSessionsForNamespace", "purgeOrphanedPairings", "connectWalletConnectSession", "web3Modal", "params", "chains", "chainReference", "restored", "proposal", "generateOptionalNamespace", "createSession", "resolveBip122Session", "configs", "optionalNamespaces", "pairingTopic", "uri", "approval", "onCloseModal", "redirectLink", "url", "prepareModalForNamespace", "openOptions", "WC_NAMESPACE_TO_CAIP", "_", "reject", "state", "debug", "restoreAndCacheSession", "client", "namespace", "cache", "options", "onDisconnect", "session", "restoreWalletConnectSession", "error", "debug", "__name", "ModalCache", "__name", "#web3Modal", "params", "createAppKitModal", "UniversalProvider", "createUniversalProvider", "projectId", "UniversalProvider", "RELAY_URL", "DEFAULT_APP_METADATA", "__name", "createSessionCache", "sessions", "namespace", "session", "topic", "__name", "TaskQueue", "__name", "#tail", "task", "ourTurn", "releaseOurTurn", "resolve", "WalletConnectAdapter", "__name", "#projectId", "#disableModalLink", "#themeMode", "#modalZIndex", "#meta", "#universalProvider", "#universalProviderPromise", "#cache", "createSessionCache", "#modalCache", "ModalCache", "#sessionQueue", "TaskQueue", "config", "createUniversalProvider", "provider", "error", "namespace", "session", "client", "restoreAndCacheSession", "targetNamespace", "#disconnectSessionQueued", "options", "#ensureSessionQueued", "resolveActiveChainReference", "getCurrentChainId", "chain", "ensureConnectedToChain", "#evmChainDeps", "requestedChainId", "currentChainId", "switchEvmNetwork", "chainReference", "restored", "prepareWalletConnectNamespace", "universalProvider", "connectWalletConnectSession", "evmMetaToCaipChainIds", "removeSessionRecord", "debug", "adapter", "getAdapter", "__name", "setAdapter", "instance", "isEvmNamespace", "DefaultSignerFactory", "TxType", "getSigners", "adapter", "getAdapter", "client", "signers", "DefaultSignerFactory", "EVMSigner", "TxType", "__name", "WALLET_ID", "metadata", "isEvmNamespace", "getSigners", "NamespaceBuilder", "actions", "builders", "utils", "commonBuilders", "standardizeAndThrowError", "utils", "ChainId", "debug", "logHandlerError", "error", "debug", "__name", "createSessionSubscriber", "namespace", "event", "handle", "handler", "context", "adapter", "getAdapter", "client", "args", "session", "handled", "_", "err", "currentHandler", "sessionUpdateSubscriber", "createSessionSubscriber", "args", "session", "adapter", "context", "allAccounts", "getAccountsFromEvent", "entries", "accountsWithChain", "getState", "setState", "hubNetwork", "persistedChain", "getPersistedChainId", "activeReference", "parseChainReference", "evmAccounts", "filterEvmAccounts", "chainIdHex", "chainReferenceToHex", "utils", "__name", "eventAccounts", "data", "entry", "extractAddress", "sessionEventSubscriber", "accounts", "ChainId", "client", "persistCurrentChainId", "sessionDeleteSubscriber", "expireWalletConnectTopic", "sessionUpdate", "sessionUpdateCleanup", "sessionUpdateSubscriber", "sessionEvent", "sessionEventCleanup", "sessionEventSubscriber", "sessionDelete", "sessionDeleteCleanup", "sessionDeleteSubscriber", "connect", "builders", "_context", "chain", "adapter", "getAdapter", "requestedReference", "parseChainReference", "session", "activeReference", "accounts", "getAccountsFromSession", "evmAccounts", "filterEvmAccounts", "utils", "account", "chainReferenceToHex", "_", "err", "standardizeAndThrowError", "canEagerConnect", "canSwitchNetwork", "actions", "disconnect", "getChainId", "evm", "NamespaceBuilder", "WALLET_ID", "buildProvider", "__name", "ProviderBuilder", "WALLET_ID", "context", "environments", "setState", "setAdapter", "WalletConnectAdapter", "metadata", "evm", "versions", "__name", "defineVersions", "buildProvider"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"evm.d.ts","sourceRoot":"","sources":["../../src/session/evm.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACtE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"evm.d.ts","sourceRoot":"","sources":["../../src/session/evm.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACtE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAYlD,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,YAAY,CAAC,MAAM,GAC3B,MAAM,GAAG,SAAS,CAIpB;AAED,wBAAgB,aAAa,CAC3B,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,cAAc,EAAE,GACrB,MAAM,GAAG,SAAS,CAapB;AAGD,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE;IACR,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CACjB,EAAE,EACH,cAAc,CAAC,EAAE,MAAM;;;IAwBxB;AAED,wBAAsB,mBAAmB,CACvC,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,YAAY,CAAC,MAAM,EAC5B,IAAI,EAAE,cAAc,EAAE,EACtB,gBAAgB,EAAE,MAAM,EACxB,cAAc,EAAE,MAAM,iBAoDvB;AAED;;;;;;;;;GASG;AACH,wBAAsB,qBAAqB,CACzC,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,YAAY,CAAC,MAAM,EAC5B,gBAAgB,EAAE,MAAM,EACxB,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,cAAc,EAAE,GACrB,OAAO,CAAC,YAAY,CAAC,MAAM,CAAC,CAwC9B;AAED,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,YAAY,CAAC,MAAM,GAAG,OAAO,CAM5E"}
|
package/dist/utils.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Chain } from '@hub3js/evm';
|
|
2
2
|
import type { ChainIdParams } from 'caip';
|
|
3
3
|
import type { BlockchainMeta } from 'rango-types';
|
|
4
|
+
export declare function timeout<T = any>(forPromise: Promise<any>, time: number): Promise<T>;
|
|
4
5
|
export declare function utf8ToHex(value: string, prefixed?: boolean): string;
|
|
5
6
|
/** Normalizes hub chain input (hex, decimal, or AddEthereumChainParameter) to a decimal reference. */
|
|
6
7
|
export declare function parseChainReference(chain?: string | Chain): string | undefined;
|
package/dist/utils.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AASlD,wBAAsB,OAAO,CAAC,CAAC,GAAG,GAAG,EAEnC,UAAU,EAAE,OAAO,CAAC,GAAG,CAAC,EACxB,IAAI,EAAE,MAAM,GACX,OAAO,CAAC,CAAC,CAAC,CAQZ;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,UAAQ,GAAG,MAAM,CAMjE;AAED,sGAAsG;AACtG,wBAAgB,mBAAmB,CACjC,KAAK,CAAC,EAAE,MAAM,GAAG,KAAK,GACrB,MAAM,GAAG,SAAS,CAYpB;AAED,4EAA4E;AAC5E,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,MAAM,GAAG,KAAK,GAAG,IAAI,GAAG,SAAS,EACxC,IAAI,EAAE,cAAc,EAAE,GACrB,MAAM,GAAG,SAAS,CAWpB;AAED,mGAAmG;AACnG,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,GAAG,KAAK,MAAM,EAAE,CAEpE;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,cAAc,EAAE,GAAG,aAAa,EAAE,CAK7E"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rango-dev/provider-walletconnect-2",
|
|
3
|
-
"version": "0.57.1-next.
|
|
3
|
+
"version": "0.57.1-next.4",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"source": "./src/mod.ts",
|
|
@@ -22,13 +22,13 @@
|
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"@bitcoinerlab/secp256k1": "^1.2.0",
|
|
25
|
-
"@hub3js/core": "^0.
|
|
26
|
-
"@hub3js/evm": "^0.
|
|
27
|
-
"@hub3js/std": "^0.
|
|
25
|
+
"@hub3js/core": "^0.62.0",
|
|
26
|
+
"@hub3js/evm": "^0.5.0",
|
|
27
|
+
"@hub3js/std": "^0.4.0",
|
|
28
|
+
"@rango-dev/internal-blockchains": "^0.1.1-next.1",
|
|
28
29
|
"@rango-dev/logging-core": "^0.14.0",
|
|
29
|
-
"@rango-dev/signer-evm": "^0.45.
|
|
30
|
-
"@rango-dev/wallets-core": "^0.61.
|
|
31
|
-
"@rango-dev/wallets-shared": "^0.62.1-next.2",
|
|
30
|
+
"@rango-dev/signer-evm": "^0.45.1-next.1",
|
|
31
|
+
"@rango-dev/wallets-core": "^0.61.1-next.1",
|
|
32
32
|
"@reown/appkit": "1.8.20",
|
|
33
33
|
"@walletconnect/encoding": "^1.0.2",
|
|
34
34
|
"@walletconnect/sign-client": "2.23.7",
|
|
@@ -37,6 +37,7 @@
|
|
|
37
37
|
"bitcoinjs-lib": "^6.1.7",
|
|
38
38
|
"bs58": "^5.0.0",
|
|
39
39
|
"caip": "^1.1.1",
|
|
40
|
+
"ethers": "^6.13.2",
|
|
40
41
|
"rango-types": "^0.5.0"
|
|
41
42
|
},
|
|
42
43
|
"devDependencies": {
|
package/src/mod.ts
CHANGED
package/src/session/evm.ts
CHANGED
|
@@ -2,11 +2,9 @@ import type { ISignClient, SessionTypes } from '@walletconnect/types';
|
|
|
2
2
|
import type { BlockchainMeta } from 'rango-types';
|
|
3
3
|
|
|
4
4
|
import { debug } from '@rango-dev/logging-core';
|
|
5
|
-
import {
|
|
6
|
-
convertEvmBlockchainMetaToEvmChainInfo,
|
|
7
|
-
isEvmAddress,
|
|
8
|
-
} from '@rango-dev/wallets-shared';
|
|
5
|
+
import { convertEvmBlockchainMetaToEvmChainInfo } from '@rango-dev/internal-blockchains';
|
|
9
6
|
import { AccountId, ChainId } from 'caip';
|
|
7
|
+
import { isAddress as isEvmAddress } from 'ethers';
|
|
10
8
|
import { isEvmBlockchain } from 'rango-types';
|
|
11
9
|
|
|
12
10
|
import { EthereumRPCMethods, NAMESPACES } from '../wcConstants.js';
|
package/src/session/lifecycle.ts
CHANGED
|
@@ -10,9 +10,9 @@ import type { ISignClient, SessionTypes } from '@walletconnect/types';
|
|
|
10
10
|
import type UniversalProvider from '@walletconnect/universal-provider';
|
|
11
11
|
|
|
12
12
|
import { debug } from '@rango-dev/logging-core';
|
|
13
|
-
import { timeout } from '@rango-dev/wallets-shared';
|
|
14
13
|
|
|
15
14
|
import { prepareModalForNamespace } from '../adapter/modal.js';
|
|
15
|
+
import { timeout } from '../utils.js';
|
|
16
16
|
import { PING_TIMEOUT, WC_NAMESPACE_TO_CAIP } from '../wcConstants.js';
|
|
17
17
|
|
|
18
18
|
import { getAccountsFromSession } from './accounts.js';
|
package/src/utils.ts
CHANGED
|
@@ -8,6 +8,21 @@ import { NAMESPACES } from './wcConstants.js';
|
|
|
8
8
|
|
|
9
9
|
const HEX_RADIX = 16;
|
|
10
10
|
|
|
11
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
12
|
+
export async function timeout<T = any>(
|
|
13
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
14
|
+
forPromise: Promise<any>,
|
|
15
|
+
time: number
|
|
16
|
+
): Promise<T> {
|
|
17
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
18
|
+
setTimeout(() => {
|
|
19
|
+
reject('Timeout!');
|
|
20
|
+
}, time);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
return Promise.race([forPromise, timeoutPromise]);
|
|
24
|
+
}
|
|
25
|
+
|
|
11
26
|
export function utf8ToHex(value: string, prefixed = false): string {
|
|
12
27
|
const hex = Array.from(new TextEncoder().encode(value))
|
|
13
28
|
.map((byte) => byte.toString(HEX_RADIX).padStart(2, '0'))
|
package/dist/chunk-GEAT645O.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var i=Object.defineProperty;var t=(e,n)=>i(e,"name",{value:n,configurable:!0});var T={evm:"eip155",utxo:"bip122"},_="wc@2:client//namespaces";var A=["chainChanged","accountsChanged"],N=["personal_sign","eth_sendTransaction","eth_signTransaction","wallet_switchEthereumChain","wallet_addEthereumChain","eth_chainId"];var c=["bip122_addressesChanged"],I=["signPsbt","getAccountAddresses"],S={name:"Rango Exchange",description:"The Ultimate Cross-Chain Solution",url:"https://app.rango.exchange/",icons:["https://app.rango.exchange/logo-rounded.png"]},C="wss://relay.walletconnect.com";import{isEvmBlockchain as a}from"rango-types";var s=16;function u(e,n=!1){let r=Array.from(new TextEncoder().encode(e)).map(o=>o.toString(s).padStart(2,"0")).join("");return n?`0x${r}`:r}t(u,"utf8ToHex");function p(e){if(e)return typeof e=="string"?e.startsWith("0x")?String(parseInt(e)):String(parseInt(e,10)||e):String(parseInt(e.chainId))}t(p,"parseChainReference");function x(e,n){let r=p(e??void 0);if(r)return n.find(o=>a(o)&&String(parseInt(o.chainId))===r)?.name}t(x,"resolveNetworkName");function f(e){return`0x${parseInt(e).toString(s)}`}t(f,"chainReferenceToHex");function l(e){return e.filter(a).map(n=>({namespace:"eip155",reference:String(parseInt(n.chainId))}))}t(l,"evmMetaToCaipChainIds");export{t as a,T as b,_ as c,A as d,N as e,c as f,I as g,S as h,C as i,u as j,p as k,x as l,f as m,l as n};
|
|
2
|
-
//# sourceMappingURL=chunk-GEAT645O.js.map
|
|
File without changes
|