@tuwaio/orbit-evm 0.1.2 → 0.2.0

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/README.md CHANGED
@@ -10,7 +10,7 @@ EVM-specific adapter implementation and utilities for the **Orbit Utils** ecosys
10
10
 
11
11
  ## 🏛️ What is `@tuwaio/orbit-evm`?
12
12
 
13
- `@tuwaio/orbit-evm` extends the core capabilities of `@tuwaio/orbit-core` by providing concrete implementations and utilities tailored specifically for **EVM (Ethereum Virtual Machine)** compatible blockchains. It acts as the EVM adapter within the Orbit Utils ecosystem, designed to simplify interactions with networks like Ethereum, Polygon, Binance Smart Chain, and others.
13
+ `@tuwaio/orbit-evm` provides concrete implementations and utilities tailored specifically for **EVM (Ethereum Virtual Machine)** compatible blockchains. It acts as the EVM adapter within the Orbit Utils ecosystem, designed to simplify interactions with networks like Ethereum, Polygon, Binance Smart Chain, and others.
14
14
 
15
15
  Built with **TypeScript** and leveraging powerful libraries like **`@wagmi/core`** and **`viem`**, this package offers specialized tools for common EVM tasks required in web3 UI development.
16
16
 
@@ -18,17 +18,17 @@ Built with **TypeScript** and leveraging powerful libraries like **`@wagmi/core`
18
18
 
19
19
  ## ✨ Key Features
20
20
 
21
- - **Chain Switching:** Utility (`checkAndSwitchChain`) to prompt users to switch their wallet to the correct EVM network.
22
- - **Viem Public Client Management:** Efficiently creates and caches `viem` Public Clients for read-only blockchain interactions (`createViemClient`).
23
- - **ENS (Ethereum Name Service) Utilities:**
24
- * Resolve ENS names to addresses (`getAddress`).
25
- * Reverse resolve addresses to primary ENS names (`getName`).
26
- * Fetch ENS avatar URLs (`getAvatar`).
27
- * Basic ENS name format checking (`isEnsName`).
28
- * All ENS lookups target Ethereum Mainnet and include caching.
29
- - **Built on Wagmi & Viem:** Leverages the robust and type-safe functionalities provided by `@wagmi/core` and `viem`.
30
- - **Type-Safe Development:** Fully typed with TypeScript 5.9+.
31
- - **Optimized Bundling:** Built with `tsup` for efficient CommonJS and ESM outputs with tree-shaking.
21
+ - **Chain Switching:** Utility (`checkAndSwitchChain`) to prompt users to switch their wallet to the correct EVM network.
22
+ - **Viem Public Client Management:** Efficiently creates and caches `viem` Public Clients for read-only blockchain interactions (`createViemClient`).
23
+ - **ENS (Ethereum Name Service) Utilities:**
24
+ - Resolve ENS names to addresses (`getAddress`).
25
+ - Reverse resolve addresses to primary ENS names (`getName`).
26
+ - Fetch ENS avatar URLs (`getAvatar`).
27
+ - Basic ENS name format checking (`isEnsName`).
28
+ - All ENS lookups target Ethereum Mainnet and include caching.
29
+ - **Built on Wagmi & Viem:** Leverages the robust and type-safe functionalities provided by `@wagmi/core` and `viem`.
30
+ - **Type-Safe Development:** Fully typed with TypeScript 5.9+.
31
+ - **Optimized Bundling:** Built with `tsup` for efficient CommonJS and ESM outputs with tree-shaking.
32
32
 
33
33
  ---
34
34
 
@@ -36,19 +36,18 @@ Built with **TypeScript** and leveraging powerful libraries like **`@wagmi/core`
36
36
 
37
37
  ### Requirements
38
38
 
39
- - Node.js 20+
40
- - TypeScript 5.9+
41
- - `@tuwaio/orbit-core` (as a foundational peer dependency)
39
+ - Node.js 20+
40
+ - TypeScript 5.9+
42
41
 
43
42
  ```bash
44
43
  # Using pnpm (recommended)
45
- pnpm add @tuwaio/orbit-evm @tuwaio/orbit-core @wagmi/core viem
44
+ pnpm add @tuwaio/orbit-evm @wagmi/core viem
46
45
 
47
46
  # Using npm
48
- npm install @tuwaio/orbit-evm @tuwaio/orbit-core @wagmi/core viem
47
+ npm install @tuwaio/orbit-evm @wagmi/core viem
49
48
 
50
49
  # Using yarn
51
- yarn add @tuwaio/orbit-evm @tuwaio/orbit-core @wagmi/core viem
50
+ yarn add @tuwaio/orbit-evm @wagmi/core viem
52
51
  ````
53
52
 
54
53
  *Note: `@wagmi/core` and `viem` are **peer dependencies** and must be installed alongside `@tuwaio/orbit-evm`*.
@@ -130,7 +129,6 @@ displayEnsName('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'); // Example: Vitali
130
129
 
131
130
  ## ✨ How It Connects to the Ecosystem
132
131
 
133
- - **Depends on `@tuwaio/orbit-core`:** Inherits core types (`OrbitAdapter`, `BaseAdapter`) and potentially uses core utilities.
134
132
  - **Provides EVM Functionality:** Offers the specific logic needed for EVM chain interactions within applications using Orbit Utils.
135
133
  - **Leverages Wagmi/Viem:** Relies on `@wagmi/core` for wallet actions (like chain switching) and `viem` for RPC interactions (like ENS resolution and client creation).
136
134
 
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var core=require('@wagmi/core'),viem=require('viem'),chains=require('viem/chains'),ens=require('viem/ens');async function N(e,r){let{connector:n,chainId:t}=core.getAccount(r);if(n&&t!==e)try{await core.switchChain(r,{chainId:e});}catch(o){throw o.cause?.name==="UserRejectedRequestError"?new Error("User rejected the request to switch network."):(console.error("Failed to switch network:",o),new Error("An error occurred while switching the network."))}}var s=new Map;function a(e,r){let n=s.get(e);if(n)return n;let t=r.find(o=>o.id===e);if(t){let o=viem.createPublicClient({chain:t,transport:viem.http()});return s.set(e,o),o}console.warn(`createViemClient: No chain configuration found for chainId ${e}. A client could not be created.`);}var l=new Map,u=new Map,d=new Map,i=a(chains.mainnet.id,[chains.mainnet]),V=async e=>{if(!i)return null;let r=l.get(e);if(r!==void 0)return r;try{let n=await ens.getEnsName(i,{address:e});return l.set(e,n),n}catch(n){return console.error(`ENS name lookup failed for address ${e}:`,n),null}},j=async e=>{if(!i)return null;let r=ens.normalize(e),n=u.get(r);if(n!==void 0)return n;try{let t=await ens.getEnsAvatar(i,{name:r});return u.set(r,t),t}catch(t){return console.error(`ENS avatar lookup failed for name ${e}:`,t),null}},q=async e=>{if(!i)return null;let r=ens.normalize(e),n=d.get(r);if(n!==void 0)return n;try{let t=await ens.getEnsAddress(i,{name:r}),o=t?t.toLowerCase():null;return d.set(r,o),o}catch(t){return console.error(`ENS address lookup failed for name ${e}:`,t),null}},R=e=>e.includes(".")&&!viem.isAddress(e);exports.checkAndSwitchChain=N;exports.createViemClient=a;exports.getAddress=q;exports.getAvatar=j;exports.getName=V;exports.isEnsName=R;//# sourceMappingURL=index.js.map
1
+ 'use strict';var core=require('@wagmi/core'),viem=require('viem'),chains=require('viem/chains'),ens=require('viem/ens');async function N(e,r){let{connector:n,chainId:t}=core.getConnection(r);if(n&&t!==e)try{await core.switchChain(r,{chainId:e});}catch(o){throw o.cause?.name==="UserRejectedRequestError"?new Error("User rejected the request to switch network."):(console.error("Failed to switch network:",o),new Error("An error occurred while switching the network."))}}var s=new Map;function a(e,r){let n=s.get(e);if(n)return n;let t=r.find(o=>o.id===e);if(t){let o=viem.createPublicClient({chain:t,transport:viem.http()});return s.set(e,o),o}console.warn(`createViemClient: No chain configuration found for chainId ${e}. A client could not be created.`);}var l=new Map,u=new Map,d=new Map,i=a(chains.mainnet.id,[chains.mainnet]),V=async e=>{if(!i)return null;let r=l.get(e);if(r!==void 0)return r;try{let n=await ens.getEnsName(i,{address:e});return l.set(e,n),n}catch(n){return console.error(`ENS name lookup failed for address ${e}:`,n),null}},j=async e=>{if(!i)return null;let r=ens.normalize(e),n=u.get(r);if(n!==void 0)return n;try{let t=await ens.getEnsAvatar(i,{name:r});return u.set(r,t),t}catch(t){return console.error(`ENS avatar lookup failed for name ${e}:`,t),null}},q=async e=>{if(!i)return null;let r=ens.normalize(e),n=d.get(r);if(n!==void 0)return n;try{let t=await ens.getEnsAddress(i,{name:r}),o=t?t.toLowerCase():null;return d.set(r,o),o}catch(t){return console.error(`ENS address lookup failed for name ${e}:`,t),null}},R=e=>e.includes(".")&&!viem.isAddress(e);exports.checkAndSwitchChain=N;exports.createViemClient=a;exports.getAddress=q;exports.getAvatar=j;exports.getName=V;exports.isEnsName=R;//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/checkAndSwitchChain.ts","../src/utils/createViemClient.ts","../src/utils/ensUtils.ts"],"names":["checkAndSwitchChain","chainId","config","connector","activeChainId","getAccount","switchChain","error","viemClientCache","createViemClient","chains","cachedClient","chain","c","newClient","createPublicClient","http","nameCache","avatarCache","addressCache","ensClient","mainnet","getName","address","cachedName","name","getEnsName","getAvatar","normalizedName","normalize","cachedAvatar","avatarUrl","getEnsAvatar","getAddress","cachedAddress","getEnsAddress","lowercasedAddress","isEnsName","nameOrAddress","isAddress"],"mappings":"wHAmBA,eAAsBA,CAAAA,CAAoBC,CAAAA,CAAiBC,CAAAA,CAA+B,CACxF,GAAM,CAAE,SAAA,CAAAC,EAAW,OAAA,CAASC,CAAc,EAAIC,eAAAA,CAAWH,CAAM,CAAA,CAG/D,GAAIC,GAAaC,CAAAA,GAAkBH,CAAAA,CACjC,GAAI,CAEF,MAAMK,gBAAAA,CAAYJ,CAAAA,CAAQ,CAAE,OAAA,CAAAD,CAAQ,CAAC,EACvC,OAASM,CAAAA,CAAO,CACd,MAAKA,CAAAA,CAAc,KAAA,EAAO,IAAA,GAAS,0BAAA,CAC3B,IAAI,KAAA,CAAM,8CAA8C,CAAA,EAEhE,OAAA,CAAQ,MAAM,2BAAA,CAA6BA,CAAK,CAAA,CAC1C,IAAI,MAAM,gDAAgD,CAAA,CAClE,CAEJ,CC5BA,IAAMC,CAAAA,CAAkB,IAAI,GAAA,CAgBrB,SAASC,EAAiBR,CAAAA,CAAiBS,CAAAA,CAAgE,CAChH,IAAMC,EAAeH,CAAAA,CAAgB,GAAA,CAAIP,CAAO,CAAA,CAChD,GAAIU,EACF,OAAOA,CAAAA,CAGT,IAAMC,CAAAA,CAAQF,EAAO,IAAA,CAAMG,CAAAA,EAAMA,CAAAA,CAAE,EAAA,GAAOZ,CAAO,CAAA,CAEjD,GAAIW,CAAAA,CAAO,CACT,IAAME,CAAAA,CAAYC,uBAAAA,CAAmB,CACnC,KAAA,CAAOH,CAAAA,CACP,UAAWI,SAAAA,EACb,CAAC,CAAA,CACD,OAAAR,CAAAA,CAAgB,GAAA,CAAIP,CAAA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,KAAA,CAAM,CAAA,kCAAA,EAAqCkB,CAAI,IAAKlB,CAAK,CAAA,CAC1D,IACT,CACF,EASa0B,CAAAA,CAAa,MAAOR,GAA0C,CACzE,GAAI,CAACL,CAAAA,CAAW,OAAO,IAAA,CACvB,IAAMQ,EAAiBC,aAAAA,CAAUJ,CAAI,CAAA,CAE/BS,CAAAA,CAAgBf,EAAa,GAAA,CAAIS,CAAc,CAAA,CACrD,GAAIM,IAAkB,MAAA,CACpB,OAAOA,EAGT,GAAI,CACF,IAAMX,CAAAA,CAAU,MAAMY,iBAAAA,CAAcf,CAAAA,CAAW,CAAE,IAAA,CAAMQ,CAAe,CAAC,CAAA,CACjEQ,EAAoBb,CAAAA,CAAWA,CAAAA,CAAQ,WAAA,EAAY,CAAgB,KACzE,OAAAJ,CAAAA,CAAa,IAAIS,CAAAA,CAAgBQ,CAAiB,EAC3CA,CACT,CAAA,MAAS7B,CAAAA,CAAO,CACd,eAAQ,KAAA,CAAM,CAAA,mCAAA,EAAsCkB,CAAI,CAAA,CAAA,CAAA,CAAKlB,CAAK,EAC3D,IACT,CACF,CAAA,CAgBa8B,CAAAA,CAAaC,GACjBA,CAAAA,CAAc,QAAA,CAAS,GAAG,CAAA,EAAK,CAACC,eAAUD,CAAa","file":"index.js","sourcesContent":["/**\n * @file This file contains a utility to ensure the user's wallet is connected to the correct chain before proceeding with a transaction.\n */\n\nimport { Config, getAccount, switchChain } from '@wagmi/core';\n\n/**\n * Checks if the user's wallet is connected to the specified chain. If not, it prompts\n * the user to switch to the correct chain.\n *\n * This function is a crucial prerequisite for any action that requires a specific network.\n *\n * @param {number} chainId - The ID of the desired blockchain network.\n * @param {Config} config - The wagmi configuration object.\n * @returns {Promise<void>} A promise that resolves when the wallet is on the correct chain.\n * It rejects if the user cancels the switch or if another error occurs.\n *\n * @throws {Error} Throws a specific error if the user rejects the chain switch or if the switch fails for other reasons.\n */\nexport async function checkAndSwitchChain(chainId: number, config: Config): Promise<void> {\n const { connector, chainId: activeChainId } = getAccount(config);\n\n // Proceed only if a wallet is connected and it is on a different chain than required.\n if (connector && activeChainId !== chainId) {\n try {\n // Pause execution and wait for the user to confirm the chain switch in their wallet.\n await switchChain(config, { chainId });\n } catch (error) {\n if ((error as any).cause?.name === 'UserRejectedRequestError') {\n throw new Error('User rejected the request to switch network.');\n }\n console.error('Failed to switch network:', error);\n throw new Error('An error occurred while switching the network.');\n }\n }\n}\n","/**\n * @file This file contains a utility function for creating a viem Public Client.\n */\n\nimport { createPublicClient, http, PublicClient } from 'viem';\nimport { Chain } from 'viem/chains';\n\nconst viemClientCache = new Map<number, PublicClient>();\n\n// -------------------\n\n/**\n * Creates or retrieves a cached viem Public Client for a specific chain.\n *\n * This client is used for read-only interactions with the blockchain, such as fetching\n * transaction receipts or reading contract state, without needing a wallet connection.\n *\n * @param {number} chainId - The ID of the chain for which to create the client.\n * @param {Chain[]} chains - An array of supported viem Chain objects.\n *\n * @returns {import('viem').PublicClient | undefined} A viem PublicClient instance if a matching chain is found, otherwise undefined.\n * It will also log a warning to the console if the chain is not configured.\n */\nexport function createViemClient(chainId: number, chains: readonly [Chain, ...Chain[]]): PublicClient | undefined {\n const cachedClient = viemClientCache.get(chainId);\n if (cachedClient) {\n return cachedClient;\n }\n\n const chain = chains.find((c) => c.id === chainId);\n\n if (chain) {\n const newClient = createPublicClient({\n chain: chain,\n transport: http(),\n });\n viemClientCache.set(chainId, newClient);\n return newClient;\n }\n\n // Log a warning for easier debugging if a chain configuration is missing.\n console.warn(`createViemClient: No chain configuration found for chainId ${chainId}. A client could not be created.`);\n\n return undefined;\n}\n","/**\n * @file This file contains utility functions for interacting with the Ethereum Name Service (ENS).\n * It provides methods for resolving names to addresses, addresses to names, and fetching avatars,\n * all specifically targeting the Ethereum Mainnet where ENS is deployed.\n */\n\nimport { Address, Hex, isAddress } from 'viem';\nimport { mainnet } from 'viem/chains';\nimport { getEnsAddress, getEnsAvatar, getEnsName, normalize } from 'viem/ens';\n\nimport { createViemClient } from './createViemClient';\n\nconst nameCache = new Map<Hex, string | null>();\nconst avatarCache = new Map<string, string | null>();\nconst addressCache = new Map<string, Address | null>();\n\n// -------------------\n\n// A single, shared viem client for all ENS lookups.\n// ENS lookups are always performed against Ethereum Mainnet, regardless of the app's connected chain.\nconst ensClient = createViemClient(mainnet.id, [mainnet]);\n\n/**\n * Fetches the primary ENS name for a given Ethereum address from the Ethereum Mainnet.\n * Includes caching for performance.\n *\n * @param {Hex} address - The Ethereum address to look up.\n * @returns {Promise<string | null>} The ENS name if found, otherwise null.\n */\nexport const getName = async (address: Hex): Promise<string | null> => {\n if (!ensClient) return null;\n\n const cachedName = nameCache.get(address);\n if (cachedName !== undefined) {\n return cachedName;\n }\n\n try {\n const name = await getEnsName(ensClient, { address });\n nameCache.set(address, name);\n return name;\n } catch (error) {\n console.error(`ENS name lookup failed for address ${address}:`, error);\n return null;\n }\n};\n\n/**\n * Fetches the avatar URL for a given ENS name from the Ethereum Mainnet.\n * Includes caching for performance.\n *\n * @param {string} name - The ENS name (e.g., 'vitalik.eth').\n * @returns {Promise<string | null>} The URL of the avatar image if found, otherwise null.\n */\nexport const getAvatar = async (name: string): Promise<string | null> => {\n if (!ensClient) return null;\n const normalizedName = normalize(name);\n\n const cachedAvatar = avatarCache.get(normalizedName);\n if (cachedAvatar !== undefined) {\n return cachedAvatar;\n }\n\n try {\n const avatarUrl = await getEnsAvatar(ensClient, { name: normalizedName });\n avatarCache.set(normalizedName, avatarUrl);\n return avatarUrl;\n } catch (error) {\n console.error(`ENS avatar lookup failed for name ${name}:`, error);\n return null;\n }\n};\n\n/**\n * Fetches the Ethereum address associated with a given ENS name from the Ethereum Mainnet.\n * Includes caching for performance.\n *\n * @param {string} name - The ENS name to resolve (e.g., 'vitalik.eth').\n * @returns {Promise<Address | null>} The associated Ethereum address (lowercase) or null if not found.\n */\nexport const getAddress = async (name: string): Promise<Address | null> => {\n if (!ensClient) return null;\n const normalizedName = normalize(name);\n\n const cachedAddress = addressCache.get(normalizedName);\n if (cachedAddress !== undefined) {\n return cachedAddress;\n }\n\n try {\n const address = await getEnsAddress(ensClient, { name: normalizedName });\n const lowercasedAddress = address ? (address.toLowerCase() as Address) : null;\n addressCache.set(normalizedName, lowercasedAddress);\n return lowercasedAddress;\n } catch (error) {\n console.error(`ENS address lookup failed for name ${name}:`, error);\n return null;\n }\n};\n\n/**\n * A heuristic to check if a string is likely an ENS name.\n *\n * This is not a foolproof validation but a quick check. A valid ENS name\n * must contain at least one dot and should not be a valid Ethereum address.\n *\n * @param {string} nameOrAddress - The string to check.\n * @returns {boolean} True if the string is likely an ENS name.\n *\n * @example\n * isEnsName('vitalik.eth') // true\n * isEnsName('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045') // false\n * isEnsName('notanaddress') // false (doesn't contain a dot)\n */\nexport const isEnsName = (nameOrAddress: string): boolean => {\n return nameOrAddress.includes('.') && !isAddress(nameOrAddress);\n};\n"]}
1
+ {"version":3,"sources":["../src/utils/checkAndSwitchChain.ts","../src/utils/createViemClient.ts","../src/utils/ensUtils.ts"],"names":["checkAndSwitchChain","chainId","config","connector","activeChainId","getConnection","switchChain","error","viemClientCache","createViemClient","chains","cachedClient","chain","c","newClient","createPublicClient","http","nameCache","avatarCache","addressCache","ensClient","mainnet","getName","address","cachedName","name","getEnsName","getAvatar","normalizedName","normalize","cachedAvatar","avatarUrl","getEnsAvatar","getAddress","cachedAddress","getEnsAddress","lowercasedAddress","isEnsName","nameOrAddress","isAddress"],"mappings":"wHAmBA,eAAsBA,CAAAA,CAAoBC,CAAAA,CAAiBC,CAAAA,CAA+B,CACxF,GAAM,CAAE,SAAA,CAAAC,EAAW,OAAA,CAASC,CAAc,EAAIC,kBAAAA,CAAcH,CAAM,CAAA,CAGlE,GAAIC,GAAaC,CAAAA,GAAkBH,CAAAA,CACjC,GAAI,CAEF,MAAMK,gBAAAA,CAAYJ,CAAAA,CAAQ,CAAE,OAAA,CAAAD,CAAQ,CAAC,EACvC,OAASM,CAAAA,CAAO,C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A,CAAO,CACd,eAAQ,KAAA,CAAM,CAAA,mCAAA,EAAsCkB,CAAI,CAAA,CAAA,CAAA,CAAKlB,CAAK,EAC3D,IACT,CACF,CAAA,CAgBa8B,CAAAA,CAAaC,GACjBA,CAAAA,CAAc,QAAA,CAAS,GAAG,CAAA,EAAK,CAACC,eAAUD,CAAa","file":"index.js","sourcesContent":["/**\n * @file This file contains a utility to ensure the user's wallet is connected to the correct chain before proceeding with a transaction.\n */\n\nimport { Config, getConnection, switchChain } from '@wagmi/core';\n\n/**\n * Checks if the user's wallet is connected to the specified chain. If not, it prompts\n * the user to switch to the correct chain.\n *\n * This function is a crucial prerequisite for any action that requires a specific network.\n *\n * @param {number} chainId - The ID of the desired blockchain network.\n * @param {Config} config - The wagmi configuration object.\n * @returns {Promise<void>} A promise that resolves when the wallet is on the correct chain.\n * It rejects if the user cancels the switch or if another error occurs.\n *\n * @throws {Error} Throws a specific error if the user rejects the chain switch or if the switch fails for other reasons.\n */\nexport async function checkAndSwitchChain(chainId: number, config: Config): Promise<void> {\n const { connector, chainId: activeChainId } = getConnection(config);\n\n // Proceed only if a wallet is connected and it is on a different chain than required.\n if (connector && activeChainId !== chainId) {\n try {\n // Pause execution and wait for the user to confirm the chain switch in their wallet.\n await switchChain(config, { chainId });\n } catch (error) {\n if ((error as any).cause?.name === 'UserRejectedRequestError') {\n throw new Error('User rejected the request to switch network.');\n }\n console.error('Failed to switch network:', error);\n throw new Error('An error occurred while switching the network.');\n }\n }\n}\n","/**\n * @file This file contains a utility function for creating a viem Public Client.\n */\n\nimport { createPublicClient, http, PublicClient } from 'viem';\nimport { Chain } from 'viem/chains';\n\nconst viemClientCache = new Map<number, PublicClient>();\n\n// -------------------\n\n/**\n * Creates or retrieves a cached viem Public Client for a specific chain.\n *\n * This client is used for read-only interactions with the blockchain, such as fetching\n * transaction receipts or reading contract state, without needing a wallet connection.\n *\n * @param {number} chainId - The ID of the chain for which to create the client.\n * @param {Chain[]} chains - An array of supported viem Chain objects.\n *\n * @returns {import('viem').PublicClient | undefined} A viem PublicClient instance if a matching chain is found, otherwise undefined.\n * It will also log a warning to the console if the chain is not configured.\n */\nexport function createViemClient(chainId: number, chains: readonly [Chain, ...Chain[]]): PublicClient | undefined {\n const cachedClient = viemClientCache.get(chainId);\n if (cachedClient) {\n return cachedClient;\n }\n\n const chain = chains.find((c) => c.id === chainId);\n\n if (chain) {\n const newClient = createPublicClient({\n chain: chain,\n transport: http(),\n });\n viemClientCache.set(chainId, newClient);\n return newClient;\n }\n\n // Log a warning for easier debugging if a chain configuration is missing.\n console.warn(`createViemClient: No chain configuration found for chainId ${chainId}. A client could not be created.`);\n\n return undefined;\n}\n","/**\n * @file This file contains utility functions for interacting with the Ethereum Name Service (ENS).\n * It provides methods for resolving names to addresses, addresses to names, and fetching avatars,\n * all specifically targeting the Ethereum Mainnet where ENS is deployed.\n */\n\nimport { Address, Hex, isAddress } from 'viem';\nimport { mainnet } from 'viem/chains';\nimport { getEnsAddress, getEnsAvatar, getEnsName, normalize } from 'viem/ens';\n\nimport { createViemClient } from './createViemClient';\n\nconst nameCache = new Map<Hex, string | null>();\nconst avatarCache = new Map<string, string | null>();\nconst addressCache = new Map<string, Address | null>();\n\n// -------------------\n\n// A single, shared viem client for all ENS lookups.\n// ENS lookups are always performed against Ethereum Mainnet, regardless of the app's connected chain.\nconst ensClient = createViemClient(mainnet.id, [mainnet]);\n\n/**\n * Fetches the primary ENS name for a given Ethereum address from the Ethereum Mainnet.\n * Includes caching for performance.\n *\n * @param {Hex} address - The Ethereum address to look up.\n * @returns {Promise<string | null>} The ENS name if found, otherwise null.\n */\nexport const getName = async (address: Hex): Promise<string | null> => {\n if (!ensClient) return null;\n\n const cachedName = nameCache.get(address);\n if (cachedName !== undefined) {\n return cachedName;\n }\n\n try {\n const name = await getEnsName(ensClient, { address });\n nameCache.set(address, name);\n return name;\n } catch (error) {\n console.error(`ENS name lookup failed for address ${address}:`, error);\n return null;\n }\n};\n\n/**\n * Fetches the avatar URL for a given ENS name from the Ethereum Mainnet.\n * Includes caching for performance.\n *\n * @param {string} name - The ENS name (e.g., 'vitalik.eth').\n * @returns {Promise<string | null>} The URL of the avatar image if found, otherwise null.\n */\nexport const getAvatar = async (name: string): Promise<string | null> => {\n if (!ensClient) return null;\n const normalizedName = normalize(name);\n\n const cachedAvatar = avatarCache.get(normalizedName);\n if (cachedAvatar !== undefined) {\n return cachedAvatar;\n }\n\n try {\n const avatarUrl = await getEnsAvatar(ensClient, { name: normalizedName });\n avatarCache.set(normalizedName, avatarUrl);\n return avatarUrl;\n } catch (error) {\n console.error(`ENS avatar lookup failed for name ${name}:`, error);\n return null;\n }\n};\n\n/**\n * Fetches the Ethereum address associated with a given ENS name from the Ethereum Mainnet.\n * Includes caching for performance.\n *\n * @param {string} name - The ENS name to resolve (e.g., 'vitalik.eth').\n * @returns {Promise<Address | null>} The associated Ethereum address (lowercase) or null if not found.\n */\nexport const getAddress = async (name: string): Promise<Address | null> => {\n if (!ensClient) return null;\n const normalizedName = normalize(name);\n\n const cachedAddress = addressCache.get(normalizedName);\n if (cachedAddress !== undefined) {\n return cachedAddress;\n }\n\n try {\n const address = await getEnsAddress(ensClient, { name: normalizedName });\n const lowercasedAddress = address ? (address.toLowerCase() as Address) : null;\n addressCache.set(normalizedName, lowercasedAddress);\n return lowercasedAddress;\n } catch (error) {\n console.error(`ENS address lookup failed for name ${name}:`, error);\n return null;\n }\n};\n\n/**\n * A heuristic to check if a string is likely an ENS name.\n *\n * This is not a foolproof validation but a quick check. A valid ENS name\n * must contain at least one dot and should not be a valid Ethereum address.\n *\n * @param {string} nameOrAddress - The string to check.\n * @returns {boolean} True if the string is likely an ENS name.\n *\n * @example\n * isEnsName('vitalik.eth') // true\n * isEnsName('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045') // false\n * isEnsName('notanaddress') // false (doesn't contain a dot)\n */\nexport const isEnsName = (nameOrAddress: string): boolean => {\n return nameOrAddress.includes('.') && !isAddress(nameOrAddress);\n};\n"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import {getAccount,switchChain}from'@wagmi/core';import {createPublicClient,http,isAddress}from'viem';import {mainnet}from'viem/chains';import {getEnsName,normalize,getEnsAvatar,getEnsAddress}from'viem/ens';async function N(e,r){let{connector:n,chainId:t}=getAccount(r);if(n&&t!==e)try{await switchChain(r,{chainId:e});}catch(o){throw o.cause?.name==="UserRejectedRequestError"?new Error("User rejected the request to switch network."):(console.error("Failed to switch network:",o),new Error("An error occurred while switching the network."))}}var s=new Map;function a(e,r){let n=s.get(e);if(n)return n;let t=r.find(o=>o.id===e);if(t){let o=createPublicClient({chain:t,transport:http()});return s.set(e,o),o}console.warn(`createViemClient: No chain configuration found for chainId ${e}. A client could not be created.`);}var l=new Map,u=new Map,d=new Map,i=a(mainnet.id,[mainnet]),V=async e=>{if(!i)return null;let r=l.get(e);if(r!==void 0)return r;try{let n=await getEnsName(i,{address:e});return l.set(e,n),n}catch(n){return console.error(`ENS name lookup failed for address ${e}:`,n),null}},j=async e=>{if(!i)return null;let r=normalize(e),n=u.get(r);if(n!==void 0)return n;try{let t=await getEnsAvatar(i,{name:r});return u.set(r,t),t}catch(t){return console.error(`ENS avatar lookup failed for name ${e}:`,t),null}},q=async e=>{if(!i)return null;let r=normalize(e),n=d.get(r);if(n!==void 0)return n;try{let t=await getEnsAddress(i,{name:r}),o=t?t.toLowerCase():null;return d.set(r,o),o}catch(t){return console.error(`ENS address lookup failed for name ${e}:`,t),null}},R=e=>e.includes(".")&&!isAddress(e);export{N as checkAndSwitchChain,a as createViemClient,q as getAddress,j as getAvatar,V as getName,R as isEnsName};//# sourceMappingURL=index.mjs.map
1
+ import {getConnection,switchChain}from'@wagmi/core';import {createPublicClient,http,isAddress}from'viem';import {mainnet}from'viem/chains';import {getEnsName,normalize,getEnsAvatar,getEnsAddress}from'viem/ens';async function N(e,r){let{connector:n,chainId:t}=getConnection(r);if(n&&t!==e)try{await switchChain(r,{chainId:e});}catch(o){throw o.cause?.name==="UserRejectedRequestError"?new Error("User rejected the request to switch network."):(console.error("Failed to switch network:",o),new Error("An error occurred while switching the network."))}}var s=new Map;function a(e,r){let n=s.get(e);if(n)return n;let t=r.find(o=>o.id===e);if(t){let o=createPublicClient({chain:t,transport:http()});return s.set(e,o),o}console.warn(`createViemClient: No chain configuration found for chainId ${e}. A client could not be created.`);}var l=new Map,u=new Map,d=new Map,i=a(mainnet.id,[mainnet]),V=async e=>{if(!i)return null;let r=l.get(e);if(r!==void 0)return r;try{let n=await getEnsName(i,{address:e});return l.set(e,n),n}catch(n){return console.error(`ENS name lookup failed for address ${e}:`,n),null}},j=async e=>{if(!i)return null;let r=normalize(e),n=u.get(r);if(n!==void 0)return n;try{let t=await getEnsAvatar(i,{name:r});return u.set(r,t),t}catch(t){return console.error(`ENS avatar lookup failed for name ${e}:`,t),null}},q=async e=>{if(!i)return null;let r=normalize(e),n=d.get(r);if(n!==void 0)return n;try{let t=await getEnsAddress(i,{name:r}),o=t?t.toLowerCase():null;return d.set(r,o),o}catch(t){return console.error(`ENS address lookup failed for name ${e}:`,t),null}},R=e=>e.includes(".")&&!isAddress(e);export{N as checkAndSwitchChain,a as createViemClient,q as getAddress,j as getAvatar,V as getName,R as isEnsName};//# sourceMappingURL=index.mjs.map
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/checkAndSwitchChain.ts","../src/utils/createViemClient.ts","../src/utils/ensUtils.ts"],"names":["checkAndSwitchChain","chainId","config","connector","activeChainId","getAccount","switchChain","error","viemClientCache","createViemClient","chains","cachedClient","chain","c","newClient","createPublicClient","http","nameCache","avatarCache","addressCache","ensClient","mainnet","getName","address","cachedName","name","getEnsName","getAvatar","normalizedName","normalize","cachedAvatar","avatarUrl","getEnsAvatar","getAddress","cachedAddress","getEnsAddress","lowercasedAddress","isEnsName","nameOrAddress","isAddress"],"mappings":"+MAmBA,eAAsBA,CAAAA,CAAoBC,CAAAA,CAAiBC,CAAAA,CAA+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AMX,CAAAA,CAAU,MAAMY,aAAAA,CAAcf,CAAAA,CAAW,CAAE,IAAA,CAAMQ,CAAe,CAAC,CAAA,CACjEQ,EAAoBb,CAAAA,CAAWA,CAAAA,CAAQ,WAAA,EAAY,CAAgB,KACzE,OAAAJ,CAAAA,CAAa,IAAIS,CAAAA,CAAgBQ,CAAiB,EAC3CA,CACT,CAAA,MAAS7B,CAAAA,CAAO,CACd,eAAQ,KAAA,CAAM,CAAA,mCAAA,EAAsCkB,CAAI,CAAA,CAAA,CAAA,CAAKlB,CAAK,EAC3D,IACT,CACF,CAAA,CAgBa8B,CAAAA,CAAaC,GACjBA,CAAAA,CAAc,QAAA,CAAS,GAAG,CAAA,EAAK,CAACC,UAAUD,CAAa","file":"index.mjs","sourcesContent":["/**\n * @file This file contains a utility to ensure the user's wallet is connected to the correct chain before proceeding with a transaction.\n */\n\nimport { Config, getAccount, switchChain } from '@wagmi/core';\n\n/**\n * Checks if the user's wallet is connected to the specified chain. If not, it prompts\n * the user to switch to the correct chain.\n *\n * This function is a crucial prerequisite for any action that requires a specific network.\n *\n * @param {number} chainId - The ID of the desired blockchain network.\n * @param {Config} config - The wagmi configuration object.\n * @returns {Promise<void>} A promise that resolves when the wallet is on the correct chain.\n * It rejects if the user cancels the switch or if another error occurs.\n *\n * @throws {Error} Throws a specific error if the user rejects the chain switch or if the switch fails for other reasons.\n */\nexport async function checkAndSwitchChain(chainId: number, config: Config): Promise<void> {\n const { connector, chainId: activeChainId } = getAccount(config);\n\n // Proceed only if a wallet is connected and it is on a different chain than required.\n if (connector && activeChainId !== chainId) {\n try {\n // Pause execution and wait for the user to confirm the chain switch in their wallet.\n await switchChain(config, { chainId });\n } catch (error) {\n if ((error as any).cause?.name === 'UserRejectedRequestError') {\n throw new Error('User rejected the request to switch network.');\n }\n console.error('Failed to switch network:', error);\n throw new Error('An error occurred while switching the network.');\n }\n }\n}\n","/**\n * @file This file contains a utility function for creating a viem Public Client.\n */\n\nimport { createPublicClient, http, PublicClient } from 'viem';\nimport { Chain } from 'viem/chains';\n\nconst viemClientCache = new Map<number, PublicClient>();\n\n// -------------------\n\n/**\n * Creates or retrieves a cached viem Public Client for a specific chain.\n *\n * This client is used for read-only interactions with the blockchain, such as fetching\n * transaction receipts or reading contract state, without needing a wallet connection.\n *\n * @param {number} chainId - The ID of the chain for which to create the client.\n * @param {Chain[]} chains - An array of supported viem Chain objects.\n *\n * @returns {import('viem').PublicClient | undefined} A viem PublicClient instance if a matching chain is found, otherwise undefined.\n * It will also log a warning to the console if the chain is not configured.\n */\nexport function createViemClient(chainId: number, chains: readonly [Chain, ...Chain[]]): PublicClient | undefined {\n const cachedClient = viemClientCache.get(chainId);\n if (cachedClient) {\n return cachedClient;\n }\n\n const chain = chains.find((c) => c.id === chainId);\n\n if (chain) {\n const newClient = createPublicClient({\n chain: chain,\n transport: http(),\n });\n viemClientCache.set(chainId, newClient);\n return newClient;\n }\n\n // Log a warning for easier debugging if a chain configuration is missing.\n console.warn(`createViemClient: No chain configuration found for chainId ${chainId}. A client could not be created.`);\n\n return undefined;\n}\n","/**\n * @file This file contains utility functions for interacting with the Ethereum Name Service (ENS).\n * It provides methods for resolving names to addresses, addresses to names, and fetching avatars,\n * all specifically targeting the Ethereum Mainnet where ENS is deployed.\n */\n\nimport { Address, Hex, isAddress } from 'viem';\nimport { mainnet } from 'viem/chains';\nimport { getEnsAddress, getEnsAvatar, getEnsName, normalize } from 'viem/ens';\n\nimport { createViemClient } from './createViemClient';\n\nconst nameCache = new Map<Hex, string | null>();\nconst avatarCache = new Map<string, string | null>();\nconst addressCache = new Map<string, Address | null>();\n\n// -------------------\n\n// A single, shared viem client for all ENS lookups.\n// ENS lookups are always performed against Ethereum Mainnet, regardless of the app's connected chain.\nconst ensClient = createViemClient(mainnet.id, [mainnet]);\n\n/**\n * Fetches the primary ENS name for a given Ethereum address from the Ethereum Mainnet.\n * Includes caching for performance.\n *\n * @param {Hex} address - The Ethereum address to look up.\n * @returns {Promise<string | null>} The ENS name if found, otherwise null.\n */\nexport const getName = async (address: Hex): Promise<string | null> => {\n if (!ensClient) return null;\n\n const cachedName = nameCache.get(address);\n if (cachedName !== undefined) {\n return cachedName;\n }\n\n try {\n const name = await getEnsName(ensClient, { address });\n nameCache.set(address, name);\n return name;\n } catch (error) {\n console.error(`ENS name lookup failed for address ${address}:`, error);\n return null;\n }\n};\n\n/**\n * Fetches the avatar URL for a given ENS name from the Ethereum Mainnet.\n * Includes caching for performance.\n *\n * @param {string} name - The ENS name (e.g., 'vitalik.eth').\n * @returns {Promise<string | null>} The URL of the avatar image if found, otherwise null.\n */\nexport const getAvatar = async (name: string): Promise<string | null> => {\n if (!ensClient) return null;\n const normalizedName = normalize(name);\n\n const cachedAvatar = avatarCache.get(normalizedName);\n if (cachedAvatar !== undefined) {\n return cachedAvatar;\n }\n\n try {\n const avatarUrl = await getEnsAvatar(ensClient, { name: normalizedName });\n avatarCache.set(normalizedName, avatarUrl);\n return avatarUrl;\n } catch (error) {\n console.error(`ENS avatar lookup failed for name ${name}:`, error);\n return null;\n }\n};\n\n/**\n * Fetches the Ethereum address associated with a given ENS name from the Ethereum Mainnet.\n * Includes caching for performance.\n *\n * @param {string} name - The ENS name to resolve (e.g., 'vitalik.eth').\n * @returns {Promise<Address | null>} The associated Ethereum address (lowercase) or null if not found.\n */\nexport const getAddress = async (name: string): Promise<Address | null> => {\n if (!ensClient) return null;\n const normalizedName = normalize(name);\n\n const cachedAddress = addressCache.get(normalizedName);\n if (cachedAddress !== undefined) {\n return cachedAddress;\n }\n\n try {\n const address = await getEnsAddress(ensClient, { name: normalizedName });\n const lowercasedAddress = address ? (address.toLowerCase() as Address) : null;\n addressCache.set(normalizedName, lowercasedAddress);\n return lowercasedAddress;\n } catch (error) {\n console.error(`ENS address lookup failed for name ${name}:`, error);\n return null;\n }\n};\n\n/**\n * A heuristic to check if a string is likely an ENS name.\n *\n * This is not a foolproof validation but a quick check. A valid ENS name\n * must contain at least one dot and should not be a valid Ethereum address.\n *\n * @param {string} nameOrAddress - The string to check.\n * @returns {boolean} True if the string is likely an ENS name.\n *\n * @example\n * isEnsName('vitalik.eth') // true\n * isEnsName('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045') // false\n * isEnsName('notanaddress') // false (doesn't contain a dot)\n */\nexport const isEnsName = (nameOrAddress: string): boolean => {\n return nameOrAddress.includes('.') && !isAddress(nameOrAddress);\n};\n"]}
1
+ {"version":3,"sources":["../src/utils/checkAndSwitchChain.ts","../src/utils/createViemClient.ts","../src/utils/ensUtils.ts"],"names":["checkAndSwitchChain","chainId","config","connector","activeChainId","getConnection","switchChain","error","viemClientCache","createViemClient","chains","cachedClient","chain","c","newClient","createPublicClient","http","nameCache","avatarCache","addressCache","ensClient","mainnet","getName","address","cachedName","name","getEnsName","getAvatar","normalizedName","normalize","cachedAvatar","avatarUrl","getEnsAvatar","getAddress","cachedAddress","getEnsAddress","lowercasedAddress","isEnsName","nameOrAddress","isAddress"],"mappings":"kNAmBA,eAAsBA,CAAAA,CAAoBC,CAAAA,CAAiBC,CAAAA,CAA+B,CACxF,GAAM,CAAE,SAAA,CAAAC,EAAW,OAAA,CAASC,CAAc,EAAIC,aAAAA,CAAcH,CAAM,CAAA,CAGlE,GAAIC,GAAaC,CAAAA,GAAkBH,CAAAA,CACjC,GAAI,CAEF,MAAMK,WAAAA,CAAYJ,CAAAA,CAAQ,CAAE,OAAA,CAAAD,CAAQ,CAAC,EACvC,OAASM,CAAAA,CAAO,CACd,MAAKA,CAAAA,CAAc,KAAA,EAAO,IAAA,GAAS,0BAAA,CAC3B,IAAI,KAAA,CAAM,8CAA8C,CAAA,EAEhE,OAAA,CAAQ,MAAM,2BAAA,CAA6BA,CAAK,CAAA,CAC1C,IAAI,MAAM,gDAAgD,CAAA,CAClE,CAEJ,CC5BA,IAAMC,CAAAA,CAAkB,IAAI,GAAA,CAgBrB,SAASC,EAAiBR,CAAAA,CAAiBS,CAAAA,CAAgE,CAChH,IAAMC,EAAeH,CAAAA,CAAgB,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E/BK,CAAAA,CAAeZ,CAAAA,CAAY,IAAIU,CAAc,CAAA,CACnD,GAAIE,CAAAA,GAAiB,MAAA,CACnB,OAAOA,CAAAA,CAGT,GAAI,CACF,IAAMC,CAAAA,CAAY,MAAMC,aAAaZ,CAAAA,CAAW,CAAE,IAAA,CAAMQ,CAAe,CAAC,CAAA,CACxE,OAAAV,EAAY,GAAA,CAAIU,CAAAA,CAAgBG,CAAS,CAAA,CAClCA,CACT,CAAA,MAASxB,CAAAA,CAAO,CACd,OAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,kCAAA,EAAqCkB,CAAI,IAAKlB,CAAK,CAAA,CAC1D,IACT,CACF,EASa0B,CAAAA,CAAa,MAAOR,GAA0C,CACzE,GAAI,CAACL,CAAAA,CAAW,OAAO,IAAA,CACvB,IAAMQ,EAAiBC,SAAAA,CAAUJ,CAAI,CAAA,CAE/BS,CAAAA,CAAgBf,EAAa,GAAA,CAAIS,CAAc,CAAA,CACrD,GAAIM,IAAkB,MAAA,CACpB,OAAOA,EAGT,GAAI,CACF,IAAMX,CAAAA,CAAU,MAAMY,aAAAA,CAAcf,CAAAA,CAAW,CAAE,IAAA,CAAMQ,CAAe,CAAC,CAAA,CACjEQ,EAAoBb,CAAAA,CAAWA,CAAAA,CAAQ,WAAA,EAAY,CAAgB,KACzE,OAAAJ,CAAAA,CAAa,IAAIS,CAAAA,CAAgBQ,CAAiB,EAC3CA,CACT,CAAA,MAAS7B,CAAAA,CAAO,CACd,eAAQ,KAAA,CAAM,CAAA,mCAAA,EAAsCkB,CAAI,CAAA,CAAA,CAAA,CAAKlB,CAAK,EAC3D,IACT,CACF,CAAA,CAgBa8B,CAAAA,CAAaC,GACjBA,CAAAA,CAAc,QAAA,CAAS,GAAG,CAAA,EAAK,CAACC,UAAUD,CAAa","file":"index.mjs","sourcesContent":["/**\n * @file This file contains a utility to ensure the user's wallet is connected to the correct chain before proceeding with a transaction.\n */\n\nimport { Config, getConnection, switchChain } from '@wagmi/core';\n\n/**\n * Checks if the user's wallet is connected to the specified chain. If not, it prompts\n * the user to switch to the correct chain.\n *\n * This function is a crucial prerequisite for any action that requires a specific network.\n *\n * @param {number} chainId - The ID of the desired blockchain network.\n * @param {Config} config - The wagmi configuration object.\n * @returns {Promise<void>} A promise that resolves when the wallet is on the correct chain.\n * It rejects if the user cancels the switch or if another error occurs.\n *\n * @throws {Error} Throws a specific error if the user rejects the chain switch or if the switch fails for other reasons.\n */\nexport async function checkAndSwitchChain(chainId: number, config: Config): Promise<void> {\n const { connector, chainId: activeChainId } = getConnection(config);\n\n // Proceed only if a wallet is connected and it is on a different chain than required.\n if (connector && activeChainId !== chainId) {\n try {\n // Pause execution and wait for the user to confirm the chain switch in their wallet.\n await switchChain(config, { chainId });\n } catch (error) {\n if ((error as any).cause?.name === 'UserRejectedRequestError') {\n throw new Error('User rejected the request to switch network.');\n }\n console.error('Failed to switch network:', error);\n throw new Error('An error occurred while switching the network.');\n }\n }\n}\n","/**\n * @file This file contains a utility function for creating a viem Public Client.\n */\n\nimport { createPublicClient, http, PublicClient } from 'viem';\nimport { Chain } from 'viem/chains';\n\nconst viemClientCache = new Map<number, PublicClient>();\n\n// -------------------\n\n/**\n * Creates or retrieves a cached viem Public Client for a specific chain.\n *\n * This client is used for read-only interactions with the blockchain, such as fetching\n * transaction receipts or reading contract state, without needing a wallet connection.\n *\n * @param {number} chainId - The ID of the chain for which to create the client.\n * @param {Chain[]} chains - An array of supported viem Chain objects.\n *\n * @returns {import('viem').PublicClient | undefined} A viem PublicClient instance if a matching chain is found, otherwise undefined.\n * It will also log a warning to the console if the chain is not configured.\n */\nexport function createViemClient(chainId: number, chains: readonly [Chain, ...Chain[]]): PublicClient | undefined {\n const cachedClient = viemClientCache.get(chainId);\n if (cachedClient) {\n return cachedClient;\n }\n\n const chain = chains.find((c) => c.id === chainId);\n\n if (chain) {\n const newClient = createPublicClient({\n chain: chain,\n transport: http(),\n });\n viemClientCache.set(chainId, newClient);\n return newClient;\n }\n\n // Log a warning for easier debugging if a chain configuration is missing.\n console.warn(`createViemClient: No chain configuration found for chainId ${chainId}. A client could not be created.`);\n\n return undefined;\n}\n","/**\n * @file This file contains utility functions for interacting with the Ethereum Name Service (ENS).\n * It provides methods for resolving names to addresses, addresses to names, and fetching avatars,\n * all specifically targeting the Ethereum Mainnet where ENS is deployed.\n */\n\nimport { Address, Hex, isAddress } from 'viem';\nimport { mainnet } from 'viem/chains';\nimport { getEnsAddress, getEnsAvatar, getEnsName, normalize } from 'viem/ens';\n\nimport { createViemClient } from './createViemClient';\n\nconst nameCache = new Map<Hex, string | null>();\nconst avatarCache = new Map<string, string | null>();\nconst addressCache = new Map<string, Address | null>();\n\n// -------------------\n\n// A single, shared viem client for all ENS lookups.\n// ENS lookups are always performed against Ethereum Mainnet, regardless of the app's connected chain.\nconst ensClient = createViemClient(mainnet.id, [mainnet]);\n\n/**\n * Fetches the primary ENS name for a given Ethereum address from the Ethereum Mainnet.\n * Includes caching for performance.\n *\n * @param {Hex} address - The Ethereum address to look up.\n * @returns {Promise<string | null>} The ENS name if found, otherwise null.\n */\nexport const getName = async (address: Hex): Promise<string | null> => {\n if (!ensClient) return null;\n\n const cachedName = nameCache.get(address);\n if (cachedName !== undefined) {\n return cachedName;\n }\n\n try {\n const name = await getEnsName(ensClient, { address });\n nameCache.set(address, name);\n return name;\n } catch (error) {\n console.error(`ENS name lookup failed for address ${address}:`, error);\n return null;\n }\n};\n\n/**\n * Fetches the avatar URL for a given ENS name from the Ethereum Mainnet.\n * Includes caching for performance.\n *\n * @param {string} name - The ENS name (e.g., 'vitalik.eth').\n * @returns {Promise<string | null>} The URL of the avatar image if found, otherwise null.\n */\nexport const getAvatar = async (name: string): Promise<string | null> => {\n if (!ensClient) return null;\n const normalizedName = normalize(name);\n\n const cachedAvatar = avatarCache.get(normalizedName);\n if (cachedAvatar !== undefined) {\n return cachedAvatar;\n }\n\n try {\n const avatarUrl = await getEnsAvatar(ensClient, { name: normalizedName });\n avatarCache.set(normalizedName, avatarUrl);\n return avatarUrl;\n } catch (error) {\n console.error(`ENS avatar lookup failed for name ${name}:`, error);\n return null;\n }\n};\n\n/**\n * Fetches the Ethereum address associated with a given ENS name from the Ethereum Mainnet.\n * Includes caching for performance.\n *\n * @param {string} name - The ENS name to resolve (e.g., 'vitalik.eth').\n * @returns {Promise<Address | null>} The associated Ethereum address (lowercase) or null if not found.\n */\nexport const getAddress = async (name: string): Promise<Address | null> => {\n if (!ensClient) return null;\n const normalizedName = normalize(name);\n\n const cachedAddress = addressCache.get(normalizedName);\n if (cachedAddress !== undefined) {\n return cachedAddress;\n }\n\n try {\n const address = await getEnsAddress(ensClient, { name: normalizedName });\n const lowercasedAddress = address ? (address.toLowerCase() as Address) : null;\n addressCache.set(normalizedName, lowercasedAddress);\n return lowercasedAddress;\n } catch (error) {\n console.error(`ENS address lookup failed for name ${name}:`, error);\n return null;\n }\n};\n\n/**\n * A heuristic to check if a string is likely an ENS name.\n *\n * This is not a foolproof validation but a quick check. A valid ENS name\n * must contain at least one dot and should not be a valid Ethereum address.\n *\n * @param {string} nameOrAddress - The string to check.\n * @returns {boolean} True if the string is likely an ENS name.\n *\n * @example\n * isEnsName('vitalik.eth') // true\n * isEnsName('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045') // false\n * isEnsName('notanaddress') // false (doesn't contain a dot)\n */\nexport const isEnsName = (nameOrAddress: string): boolean => {\n return nameOrAddress.includes('.') && !isAddress(nameOrAddress);\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tuwaio/orbit-evm",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "private": false,
5
5
  "author": "Oleksandr Tkach",
6
6
  "license": "Apache-2.0",
@@ -36,14 +36,14 @@
36
36
  }
37
37
  ],
38
38
  "peerDependencies": {
39
- "@wagmi/core": "2.x.x",
39
+ "@wagmi/core": "3.x.x",
40
40
  "viem": "2.x.x"
41
41
  },
42
42
  "devDependencies": {
43
- "@wagmi/core": "^2.22.1",
44
- "tsup": "^8.5.0",
43
+ "@wagmi/core": "^3.0.0",
44
+ "tsup": "^8.5.1",
45
45
  "typescript": "^5.9.3",
46
- "viem": "^2.38.5"
46
+ "viem": "^2.40.3"
47
47
  },
48
48
  "scripts": {
49
49
  "start": "tsup src/index.ts --watch",