@tuwaio/orbit-evm 0.0.4 → 0.1.1
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 +103 -22
- package/dist/index.d.mts +4 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +9 -9
package/README.md
CHANGED
|
@@ -2,54 +2,139 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/@tuwaio/orbit-evm)
|
|
4
4
|
[](./LICENSE)
|
|
5
|
-
[](https://github.com/TuwaIO/orbit/actions)
|
|
6
6
|
|
|
7
|
-
EVM-specific implementation for the
|
|
7
|
+
EVM-specific adapter implementation and utilities for the **Orbit Utils** ecosystem by **TUWA**. Provides helpers for interacting with EVM-compatible blockchains like Ethereum, Polygon, BSC, etc., leveraging **wagmi** and **viem**.
|
|
8
8
|
|
|
9
9
|
---
|
|
10
10
|
|
|
11
11
|
## 🏛️ What is `@tuwaio/orbit-evm`?
|
|
12
12
|
|
|
13
|
-
`@tuwaio/orbit-evm`
|
|
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.
|
|
14
|
+
|
|
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.
|
|
14
16
|
|
|
15
17
|
---
|
|
16
18
|
|
|
17
19
|
## ✨ Key Features
|
|
18
20
|
|
|
19
|
-
-
|
|
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
32
|
|
|
22
33
|
---
|
|
23
34
|
|
|
24
35
|
## 💾 Installation
|
|
25
36
|
|
|
26
37
|
### Requirements
|
|
27
|
-
|
|
28
|
-
-
|
|
38
|
+
|
|
39
|
+
- Node.js 20+
|
|
40
|
+
- TypeScript 5.9+
|
|
41
|
+
- `@tuwaio/orbit-core` (as a foundational peer dependency)
|
|
29
42
|
|
|
30
43
|
```bash
|
|
31
44
|
# Using pnpm (recommended)
|
|
32
|
-
pnpm add @tuwaio/orbit-evm @wagmi/core viem
|
|
45
|
+
pnpm add @tuwaio/orbit-evm @tuwaio/orbit-core @wagmi/core viem
|
|
46
|
+
|
|
33
47
|
# Using npm
|
|
34
|
-
npm install @tuwaio/orbit-evm @wagmi/core viem
|
|
48
|
+
npm install @tuwaio/orbit-evm @tuwaio/orbit-core @wagmi/core viem
|
|
49
|
+
|
|
35
50
|
# Using yarn
|
|
36
|
-
yarn add @tuwaio/orbit-evm @wagmi/core viem
|
|
51
|
+
yarn add @tuwaio/orbit-evm @tuwaio/orbit-core @wagmi/core viem
|
|
52
|
+
````
|
|
53
|
+
|
|
54
|
+
*Note: `@wagmi/core` and `viem` are **peer dependencies** and must be installed alongside `@tuwaio/orbit-evm`*.
|
|
55
|
+
|
|
56
|
+
-----
|
|
57
|
+
|
|
58
|
+
## 🚀 Quick Start
|
|
59
|
+
|
|
60
|
+
### Check and Switch Network
|
|
61
|
+
|
|
62
|
+
Ensure the user's wallet is connected to the desired EVM chain (e.g., Sepolia testnet, ID 11155111).
|
|
63
|
+
|
|
64
|
+
```typescript
|
|
65
|
+
import { checkAndSwitchChain } from '@tuwaio/orbit-evm';
|
|
66
|
+
import { type Config } from '@wagmi/core'; // Assuming you have your wagmi config
|
|
67
|
+
|
|
68
|
+
// Assume 'wagmiConfig' is your initialized wagmi Config object
|
|
69
|
+
declare const wagmiConfig: Config;
|
|
70
|
+
const targetChainId = 11155111; // Sepolia
|
|
71
|
+
|
|
72
|
+
async function ensureCorrectChain() {
|
|
73
|
+
try {
|
|
74
|
+
await checkAndSwitchChain(targetChainId, wagmiConfig);
|
|
75
|
+
console.log(`Wallet is now connected to chain ID ${targetChainId}`);
|
|
76
|
+
// Proceed with actions requiring the target chain
|
|
77
|
+
} catch (error) {
|
|
78
|
+
console.error('Failed to switch chain:', error);
|
|
79
|
+
// Handle the error (e.g., show a message to the user)
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
ensureCorrectChain();
|
|
84
|
+
|
|
37
85
|
```
|
|
38
86
|
|
|
39
|
-
|
|
87
|
+
### Resolve ENS Name
|
|
88
|
+
|
|
89
|
+
Get the primary ENS name for an Ethereum address.
|
|
90
|
+
|
|
91
|
+
```typescript
|
|
92
|
+
import { getName, isEnsName } from '@tuwaio/orbit-evm';
|
|
93
|
+
|
|
94
|
+
async function displayEnsName(address: `0x${string}`) {
|
|
95
|
+
if (isEnsName(address)) { // Basic check, though getName expects an address
|
|
96
|
+
console.log(`${address} looks like an ENS name, not an address.`);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const name = await getName(address);
|
|
100
|
+
if (name) {
|
|
101
|
+
console.log(`The ENS name for ${address} is: ${name}`);
|
|
102
|
+
} else {
|
|
103
|
+
console.log(`No primary ENS name found for ${address}.`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
displayEnsName('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'); // Example: Vitalik's address
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
-----
|
|
40
111
|
|
|
41
112
|
## 🔧 Architecture
|
|
42
113
|
|
|
43
|
-
|
|
114
|
+
`@tuwaio/orbit-evm` acts as an **adapter implementation** for the `OrbitAdapter.EVM` type defined in `@tuwaio/orbit-core`. It provides concrete functions that fulfill the `BaseAdapter` interface requirements (like `getName`, `getAvatar`) and adds EVM-specific utilities.
|
|
115
|
+
|
|
116
|
+
### Core Modules & Exports (`index.ts`)
|
|
117
|
+
|
|
118
|
+
- **Chain Utilities (`checkAndSwitchChain`)**: Handles network switching logic using `@wagmi/core`.
|
|
119
|
+
- **Client Utilities (`createViemClient`)**: Manages `viem` public client instances with caching.
|
|
120
|
+
- **ENS Utilities (`ensUtils`)**: Provides functions (`getAddress`, `getAvatar`, `getName`, `isEnsName`) for interacting with the Ethereum Name Service on Mainnet, using `viem/ens`.
|
|
44
121
|
|
|
45
122
|
### Build System
|
|
46
|
-
- Built with `tsup` for optimal bundling
|
|
47
|
-
- Outputs both CommonJS and ESM formats
|
|
48
|
-
- Generates TypeScript declarations
|
|
49
123
|
|
|
50
|
-
|
|
51
|
-
-
|
|
52
|
-
|
|
124
|
+
- Built using `tsup`.
|
|
125
|
+
- Outputs CommonJS (`cjs`) and ECMAScript Module (`esm`) formats.
|
|
126
|
+
- Generates TypeScript declaration files (`.d.ts`).
|
|
127
|
+
- Configured for tree-shaking and minification.
|
|
128
|
+
|
|
129
|
+
-----
|
|
130
|
+
|
|
131
|
+
## ✨ How It Connects to the Ecosystem
|
|
132
|
+
|
|
133
|
+
- **Depends on `@tuwaio/orbit-core`:** Inherits core types (`OrbitAdapter`, `BaseAdapter`) and potentially uses core utilities.
|
|
134
|
+
- **Provides EVM Functionality:** Offers the specific logic needed for EVM chain interactions within applications using Orbit Utils.
|
|
135
|
+
- **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
|
+
|
|
137
|
+
-----
|
|
53
138
|
|
|
54
139
|
## 🤝 Contributing & Support
|
|
55
140
|
|
|
@@ -62,7 +147,3 @@ If you find this library useful, please consider supporting its development. Eve
|
|
|
62
147
|
## 📄 License
|
|
63
148
|
|
|
64
149
|
This project is licensed under the **Apache-2.0 License** - see the [LICENSE](./LICENSE) file for details.
|
|
65
|
-
|
|
66
|
-
## 👥 Contributors
|
|
67
|
-
|
|
68
|
-
- **Oleksandr Tkach** - [GitHub](https://github.com/Argeare5)
|
package/dist/index.d.mts
CHANGED
|
@@ -26,7 +26,7 @@ declare function checkAndSwitchChain(chainId: number, config: Config): Promise<v
|
|
|
26
26
|
*/
|
|
27
27
|
|
|
28
28
|
/**
|
|
29
|
-
* Creates a viem Public Client for a specific chain.
|
|
29
|
+
* Creates or retrieves a cached viem Public Client for a specific chain.
|
|
30
30
|
*
|
|
31
31
|
* This client is used for read-only interactions with the blockchain, such as fetching
|
|
32
32
|
* transaction receipts or reading contract state, without needing a wallet connection.
|
|
@@ -47,6 +47,7 @@ declare function createViemClient(chainId: number, chains: readonly [Chain, ...C
|
|
|
47
47
|
|
|
48
48
|
/**
|
|
49
49
|
* Fetches the primary ENS name for a given Ethereum address from the Ethereum Mainnet.
|
|
50
|
+
* Includes caching for performance.
|
|
50
51
|
*
|
|
51
52
|
* @param {Hex} address - The Ethereum address to look up.
|
|
52
53
|
* @returns {Promise<string | null>} The ENS name if found, otherwise null.
|
|
@@ -54,6 +55,7 @@ declare function createViemClient(chainId: number, chains: readonly [Chain, ...C
|
|
|
54
55
|
declare const getName: (address: Hex) => Promise<string | null>;
|
|
55
56
|
/**
|
|
56
57
|
* Fetches the avatar URL for a given ENS name from the Ethereum Mainnet.
|
|
58
|
+
* Includes caching for performance.
|
|
57
59
|
*
|
|
58
60
|
* @param {string} name - The ENS name (e.g., 'vitalik.eth').
|
|
59
61
|
* @returns {Promise<string | null>} The URL of the avatar image if found, otherwise null.
|
|
@@ -61,6 +63,7 @@ declare const getName: (address: Hex) => Promise<string | null>;
|
|
|
61
63
|
declare const getAvatar: (name: string) => Promise<string | null>;
|
|
62
64
|
/**
|
|
63
65
|
* Fetches the Ethereum address associated with a given ENS name from the Ethereum Mainnet.
|
|
66
|
+
* Includes caching for performance.
|
|
64
67
|
*
|
|
65
68
|
* @param {string} name - The ENS name to resolve (e.g., 'vitalik.eth').
|
|
66
69
|
* @returns {Promise<Address | null>} The associated Ethereum address (lowercase) or null if not found.
|
package/dist/index.d.ts
CHANGED
|
@@ -26,7 +26,7 @@ declare function checkAndSwitchChain(chainId: number, config: Config): Promise<v
|
|
|
26
26
|
*/
|
|
27
27
|
|
|
28
28
|
/**
|
|
29
|
-
* Creates a viem Public Client for a specific chain.
|
|
29
|
+
* Creates or retrieves a cached viem Public Client for a specific chain.
|
|
30
30
|
*
|
|
31
31
|
* This client is used for read-only interactions with the blockchain, such as fetching
|
|
32
32
|
* transaction receipts or reading contract state, without needing a wallet connection.
|
|
@@ -47,6 +47,7 @@ declare function createViemClient(chainId: number, chains: readonly [Chain, ...C
|
|
|
47
47
|
|
|
48
48
|
/**
|
|
49
49
|
* Fetches the primary ENS name for a given Ethereum address from the Ethereum Mainnet.
|
|
50
|
+
* Includes caching for performance.
|
|
50
51
|
*
|
|
51
52
|
* @param {Hex} address - The Ethereum address to look up.
|
|
52
53
|
* @returns {Promise<string | null>} The ENS name if found, otherwise null.
|
|
@@ -54,6 +55,7 @@ declare function createViemClient(chainId: number, chains: readonly [Chain, ...C
|
|
|
54
55
|
declare const getName: (address: Hex) => Promise<string | null>;
|
|
55
56
|
/**
|
|
56
57
|
* Fetches the avatar URL for a given ENS name from the Ethereum Mainnet.
|
|
58
|
+
* Includes caching for performance.
|
|
57
59
|
*
|
|
58
60
|
* @param {string} name - The ENS name (e.g., 'vitalik.eth').
|
|
59
61
|
* @returns {Promise<string | null>} The URL of the avatar image if found, otherwise null.
|
|
@@ -61,6 +63,7 @@ declare const getName: (address: Hex) => Promise<string | null>;
|
|
|
61
63
|
declare const getAvatar: (name: string) => Promise<string | null>;
|
|
62
64
|
/**
|
|
63
65
|
* Fetches the Ethereum address associated with a given ENS name from the Ethereum Mainnet.
|
|
66
|
+
* Includes caching for performance.
|
|
64
67
|
*
|
|
65
68
|
* @param {string} name - The ENS name to resolve (e.g., 'vitalik.eth').
|
|
66
69
|
* @returns {Promise<Address | null>} The associated Ethereum address (lowercase) or null if not found.
|
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
|
|
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
|
|
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","createViemClient","chains","chain","c","createPublicClient","http","ensClient","mainnet","getName","address","getEnsName","getAvatar","name","getEnsAvatar","normalize","getAddress","getEnsAddress","isEnsName","nameOrAddress","isAddress"],"mappings":"wHAmBA,eAAsBA,CAAAA,CAAoBC,CAAAA,CAAiBC,CAAAA,CAA+B,CACxF,GAAM,CAAE,SAAA,CAAAC,EAAW,OAAA,CAASC,CAAc,CAAA,CAAIC,eAAAA,CAAWH,CAAM,CAAA,CAG/D,GAAIC,CAAAA,EAAaC,CAAAA,GAAkBH,CAAAA,CACjC,GAAI,CAEF,MAAMK,gBAAAA,CAAYJ,EAAQ,CAAE,OAAA,CAAAD,CAAQ,CAAC,EACvC,CAAA,MAASM,CAAAA,CAAO,CACd,MAAKA,CAAAA,CAAc,KAAA,EAAO,IAAA,GAAS,0BAAA,CAC3B,IAAI,KAAA,CAAM,8CAA8C,CAAA,EAEhE,OAAA,CAAQ,KAAA,CAAM,2BAAA,CAA6BA,CAAK,CAAA,CAC1C,IAAI,KAAA,CAAM,gDAAgD,CAAA,CAClE,CAEJ,CChBO,SAASC,CAAAA,CAAiBP,CAAAA,CAAiBQ,CAAAA,CAAgE,CAChH,IAAMC,CAAAA,CAAQD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CAAC,CAAA,CAExE,OAAOH,CAAAA,CAAWA,CAAAA,CAAQ,WAAA,EAAY,CAAgB,IACxD,CAAA,MAASV,CAAAA,CAAO,CACd,OAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,mCAAA,EAAsCa,CAAI,CAAA,CAAA,CAAA,CAAKb,CAAK,CAAA,CAC3D,IACT,CACF,CAAA,CAgBakB,CAAAA,CAAaC,CAAAA,EACjBA,CAAAA,CAAc,QAAA,CAAS,GAAG,CAAA,EAAK,CAACC,cAAAA,CAAUD,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\n/**\n * Creates a 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 chain = chains.find((c) => c.id === chainId);\n\n if (chain) {\n return createPublicClient({\n chain: chain,\n transport: http(),\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\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 *\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 try {\n // getEnsName returns the name or null if not found.\n return await getEnsName(ensClient, { address });\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 *\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 try {\n // getEnsAvatar returns the URL or null if not found.\n return await getEnsAvatar(ensClient, { name: normalize(name) });\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 *\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 try {\n const address = await getEnsAddress(ensClient, { name: normalize(name) });\n // viem returns the address or null. We ensure it's lowercase if it exists.\n return address ? (address.toLowerCase() as Address) : null;\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","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,CAA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U,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"]}
|
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,getEnsAvatar,
|
|
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
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.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","createViemClient","chains","chain","c","createPublicClient","http","ensClient","mainnet","getName","address","getEnsName","getAvatar","name","getEnsAvatar","normalize","getAddress","getEnsAddress","isEnsName","nameOrAddress","isAddress"],"mappings":"+MAmBA,eAAsBA,CAAAA,CAAoBC,CAAAA,CAAiBC,CAAAA,CAA+B,CACxF,GAAM,CAAE,SAAA,CAAAC,EAAW,OAAA,CAASC,CAAc,CAAA,CAAIC,UAAAA,CAAWH,CAAM,CAAA,CAG/D,GAAIC,CAAAA,EAAaC,CAAAA,GAAkBH,CAAAA,CACjC,GAAI,CAEF,MAAMK,WAAAA,CAAYJ,EAAQ,CAAE,OAAA,CAAAD,CAAQ,CAAC,EACvC,CAAA,MAASM,CAAAA,CAAO,CACd,MAAKA,CAAAA,CAAc,KAAA,EAAO,IAAA,GAAS,0BAAA,CAC3B,IAAI,KAAA,CAAM,8CAA8C,CAAA,EAEhE,OAAA,CAAQ,KAAA,CAAM,2BAAA,CAA6BA,CAAK,CAAA,CAC1C,IAAI,KAAA,CAAM,gDAAgD,CAAA,CAClE,CAEJ,CChBO,SAASC,CAAAA,CAAiBP,CAAAA,CAAiBQ,CAAAA,CAAgE,CAChH,IAAMC,CAAAA,CAAQD,CAAAA,CAAO,IAAA,CAAME,CAAAA,EAAMA,CAAAA,CAAE,KAAOV,CAAO,CAAA,CAEjD,GAAIS,CAAAA,CACF,OAAOE,kBAAAA,CAAmB,CAC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,KAAA,CAAM,CAAA,mCAAA,EAAsCa,CAAI,CAAA,CAAA,CAAA,CAAKb,CAAK,CAAA,CAC3D,IACT,CACF,CAAA,CAgBakB,CAAAA,CAAaC,CAAAA,EACjBA,CAAAA,CAAc,QAAA,CAAS,GAAG,CAAA,EAAK,CAACC,SAAAA,CAAUD,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\n/**\n * Creates a 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 chain = chains.find((c) => c.id === chainId);\n\n if (chain) {\n return createPublicClient({\n chain: chain,\n transport: http(),\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\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 *\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 try {\n // getEnsName returns the name or null if not found.\n return await getEnsName(ensClient, { address });\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 *\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 try {\n // getEnsAvatar returns the URL or null if not found.\n return await getEnsAvatar(ensClient, { name: normalize(name) });\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 *\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 try {\n const address = await getEnsAddress(ensClient, { name: normalize(name) });\n // viem returns the address or null. We ensure it's lowercase if it exists.\n return address ? (address.toLowerCase() as Address) : null;\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","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+B,CACxF,GAAM,CAAE,SAAA,CAAAC,EAAW,OAAA,CAASC,CAAc,EAAIC,UAAAA,CAAWH,CAAM,CAAA,CAG/D,GAAIC,GAAaC,CAAAA,GAAkBH,CAAAA,CACjC,G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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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tuwaio/orbit-evm",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"author": "Oleksandr Tkach",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -22,12 +22,12 @@
|
|
|
22
22
|
],
|
|
23
23
|
"repository": {
|
|
24
24
|
"type": "git",
|
|
25
|
-
"url": "git+https://github.com/TuwaIO/
|
|
25
|
+
"url": "git+https://github.com/TuwaIO/orbit.git",
|
|
26
26
|
"directory": "packages/orbit-evm"
|
|
27
27
|
},
|
|
28
|
-
"homepage": "https://github.com/TuwaIO/
|
|
28
|
+
"homepage": "https://github.com/TuwaIO/orbit",
|
|
29
29
|
"bugs": {
|
|
30
|
-
"url": "https://github.com/TuwaIO/
|
|
30
|
+
"url": "https://github.com/TuwaIO/orbit/issues"
|
|
31
31
|
},
|
|
32
32
|
"contributors": [
|
|
33
33
|
{
|
|
@@ -36,14 +36,14 @@
|
|
|
36
36
|
}
|
|
37
37
|
],
|
|
38
38
|
"peerDependencies": {
|
|
39
|
-
"@wagmi/core": "
|
|
40
|
-
"viem": "
|
|
39
|
+
"@wagmi/core": "2.x.x",
|
|
40
|
+
"viem": "2.x.x"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
|
-
"@wagmi/core": "^2.
|
|
43
|
+
"@wagmi/core": "^2.22.1",
|
|
44
44
|
"tsup": "^8.5.0",
|
|
45
|
-
"typescript": "^5.9.
|
|
46
|
-
"viem": "^2.
|
|
45
|
+
"typescript": "^5.9.3",
|
|
46
|
+
"viem": "^2.38.3"
|
|
47
47
|
},
|
|
48
48
|
"scripts": {
|
|
49
49
|
"start": "tsup src/index.ts --watch",
|