@tuwaio/nova-connect 1.0.0-fix-test-alpha.51.1ef6db6
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/LICENSE +201 -0
- package/README.md +142 -0
- package/dist/evm/index.cjs +2 -0
- package/dist/evm/index.cjs.map +1 -0
- package/dist/evm/index.d.cts +31 -0
- package/dist/evm/index.d.ts +31 -0
- package/dist/evm/index.js +2 -0
- package/dist/evm/index.js.map +1 -0
- package/dist/hooks/index.cjs +2 -0
- package/dist/hooks/index.cjs.map +1 -0
- package/dist/hooks/index.js +2 -0
- package/dist/hooks/index.js.map +1 -0
- package/dist/index.cjs +12 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.css +2126 -0
- package/dist/index.d.cts +1607 -0
- package/dist/index.d.ts +1607 -0
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -0
- package/dist/providers/index.cjs +6 -0
- package/dist/providers/index.cjs.map +1 -0
- package/dist/providers/index.d.cts +190 -0
- package/dist/providers/index.d.ts +190 -0
- package/dist/providers/index.js +6 -0
- package/dist/providers/index.js.map +1 -0
- package/dist/solana/index.cjs +2 -0
- package/dist/solana/index.cjs.map +1 -0
- package/dist/solana/index.js +2 -0
- package/dist/solana/index.js.map +1 -0
- package/package.json +162 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 FOP Tkach Oleksandr
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# Satellite Connect React
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@tuwaio/satellite-react)
|
|
4
|
+
[](./LICENSE)
|
|
5
|
+
[](https://github.com/TuwaIO/satellite-connect/actions)
|
|
6
|
+
|
|
7
|
+
React components and hooks for the Satellite Connect ecosystem, providing an easy-to-use interface for integrating Web3 wallet functionality into React applications.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## 🏛️ What is `@tuwaio/satellite-react`?
|
|
12
|
+
|
|
13
|
+
`@tuwaio/satellite-react` is the React integration layer for the Satellite Connect ecosystem. It provides a collection of React hooks and components that make it easy to integrate Web3 wallet functionality into your React applications.
|
|
14
|
+
|
|
15
|
+
Built on top of `@tuwaio/satellite-core`, this package offers a seamless developer experience for React applications requiring Web3 wallet integration.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## ✨ Key Features
|
|
20
|
+
|
|
21
|
+
- **Type Safety:** Full TypeScript support with proper type definitions
|
|
22
|
+
- **Chain Agnostic:** Unified support for both EVM and Solana wallets
|
|
23
|
+
- **Modern React:** Built with React 19+ features and best practices
|
|
24
|
+
- **Multi-Chain Support:** Seamless integration with multiple blockchain networks
|
|
25
|
+
- **State Management:** Zustand-based store for efficient state handling
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## 💾 Installation
|
|
30
|
+
|
|
31
|
+
### Requirements
|
|
32
|
+
- React 19+
|
|
33
|
+
- Node.js 24+
|
|
34
|
+
- TypeScript 5.9+
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
# Using pnpm (recommended)
|
|
38
|
+
pnpm add @tuwaio/satellite-react @tuwaio/satellite-core @tuwaio/orbit-core @wagmi/core @wallet-standard/react gill react immer zustand
|
|
39
|
+
|
|
40
|
+
# Using npm
|
|
41
|
+
npm install @tuwaio/satellite-react @tuwaio/satellite-core @tuwaio/orbit-core @wagmi/core @wallet-standard/react gill react immer zustand
|
|
42
|
+
|
|
43
|
+
# Using yarn
|
|
44
|
+
yarn add @tuwaio/satellite-react @tuwaio/satellite-core @tuwaio/orbit-core @wagmi/core @wallet-standard/react gill react immer zustand
|
|
45
|
+
```
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## 🚀 Quick Start
|
|
49
|
+
|
|
50
|
+
### Basic Setup
|
|
51
|
+
```tsx
|
|
52
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
|
53
|
+
import { satelliteEVMAdapter } from '@tuwaio/satellite-evm';
|
|
54
|
+
import { EVMWalletsWatcher, SatelliteConnectProvider, SolanaWalletsWatcher } from '@tuwaio/satellite-react';
|
|
55
|
+
import { initializeSolanaMobileConnectors, satelliteSolanaAdapter } from '@tuwaio/satellite-solana';
|
|
56
|
+
import { ReactNode } from 'react';
|
|
57
|
+
import { WagmiProvider } from 'wagmi';
|
|
58
|
+
import { createWagmiConfig } from '@tuwaio/satellite-evm';
|
|
59
|
+
import { Chain, mainnet, sepolia } from 'viem/chains';
|
|
60
|
+
|
|
61
|
+
export const appConfig = {
|
|
62
|
+
appName: 'Satellite EVM Test App',
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
export const solanaRPCUrls = {
|
|
66
|
+
devnet: 'https://api.devnet.solana.com',
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
export const appEVMChains = [mainnet, sepolia] as readonly [Chain, ...Chain[]];
|
|
70
|
+
|
|
71
|
+
export const wagmiConfig = createWagmiConfig({
|
|
72
|
+
...appConfig,
|
|
73
|
+
chains: appEVMChains,
|
|
74
|
+
ssr: true,
|
|
75
|
+
syncConnectedChain: true,
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
const queryClient = new QueryClient();
|
|
80
|
+
|
|
81
|
+
initializeSolanaMobileConnectors({
|
|
82
|
+
rpcUrls: solanaRPCUrls,
|
|
83
|
+
...appConfig,
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
export function Providers({ children }: { children: ReactNode }) {
|
|
87
|
+
return (
|
|
88
|
+
<WagmiProvider config={wagmiConfig}>
|
|
89
|
+
<QueryClientProvider client={queryClient}>
|
|
90
|
+
<SatelliteConnectProvider
|
|
91
|
+
adapter={[satelliteEVMAdapter(wagmiConfig), satelliteSolanaAdapter({ rpcUrls: solanaRPCUrls })]}
|
|
92
|
+
autoConnect={true}
|
|
93
|
+
>
|
|
94
|
+
<EVMWalletsWatcher wagmiConfig={wagmiConfig} />
|
|
95
|
+
<SolanaWalletsWatcher />
|
|
96
|
+
{children}
|
|
97
|
+
</SatelliteConnectProvider>
|
|
98
|
+
</QueryClientProvider>
|
|
99
|
+
</WagmiProvider>
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Using Hooks
|
|
105
|
+
```tsx
|
|
106
|
+
import { useSatelliteConnectStore } from '@tuwaio/satellite-react';
|
|
107
|
+
|
|
108
|
+
function ExampleGettingActiveWalletFromStore() {
|
|
109
|
+
const activeWallet = useSatelliteConnectStore((state) => state.activeWallet);
|
|
110
|
+
return <div>{activeWallet?.address}</div>
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
---
|
|
114
|
+
|
|
115
|
+
### Core Components
|
|
116
|
+
|
|
117
|
+
1. **Store Access**
|
|
118
|
+
- `useSatelliteConnectStore`: Access to satellite connect store with full type safety
|
|
119
|
+
- Provides access to wallet state, connection methods, and chain management
|
|
120
|
+
|
|
121
|
+
2. **Provider Components**
|
|
122
|
+
- `SatelliteConnectProvider`: Global context provider with all necessary configurations
|
|
123
|
+
- `EVMWalletsWatcher`: EVM wallet connection state management
|
|
124
|
+
- `SolanaWalletsWatcher`: Solana wallet connection state management
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## 🤝 Contributing & Support
|
|
129
|
+
|
|
130
|
+
Contributions are welcome! Please read our main **[Contribution Guidelines](https://github.com/TuwaIO/workflows/blob/main/CONTRIBUTING.md)**.
|
|
131
|
+
|
|
132
|
+
If you find this library useful, please consider supporting its development. Every contribution helps!
|
|
133
|
+
|
|
134
|
+
[**➡️ View Support Options**](https://github.com/TuwaIO/workflows/blob/main/Donation.md)
|
|
135
|
+
|
|
136
|
+
## 📄 License
|
|
137
|
+
|
|
138
|
+
This project is licensed under the **Apache-2.0 License** - see the [LICENSE](./LICENSE) file for details.
|
|
139
|
+
|
|
140
|
+
## 👥 Contributors
|
|
141
|
+
|
|
142
|
+
- **Oleksandr Tkach** - [GitHub](https://github.com/Argeare5)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';function r(e){return e!=null&&typeof e=="number"&&e>0}function t(e){return !e||e.length===0?[]:e.map(n=>n.id).filter(r)}function i(e){return e.length>0&&e.every(n=>typeof n=="number")}exports.getEvmChains=t;exports.isEvmChainList=i;//# sourceMappingURL=index.cjs.map
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/evm/utils.ts"],"names":["isValidEvmChainId","id","getEvmChains","appChains","chain","isEvmChainList","chains"],"mappings":"aAKA,SAASA,CAAAA,CAAkBC,EAA2B,CACpD,OAA2BA,GAAO,IAAA,EAAQ,OAAOA,CAAAA,EAAO,QAAA,EAAYA,CAAAA,CAAK,CAC3E,CAKO,SAASC,CAAAA,CAAaC,EAAoD,CAC/E,OAAI,CAACA,CAAAA,EAAaA,CAAAA,CAAU,MAAA,GAAW,CAAA,CAC9B,EAAC,CAGHA,EAAU,GAAA,CAAKC,CAAAA,EAAUA,EAAM,EAAE,CAAA,CAAE,OAAOJ,CAAiB,CACpE,CAKO,SAASK,CAAAA,CAAeC,CAAAA,CAAiD,CAC9E,OAAOA,CAAAA,CAAO,OAAS,CAAA,EAAKA,CAAAA,CAAO,MAAOF,CAAAA,EAAU,OAAOA,CAAAA,EAAU,QAAQ,CAC/E","file":"index.cjs","sourcesContent":["import type { Chain } from 'viem/chains';\n\n/**\n * Type guard to check if a value is a valid EVM chain ID\n */\nfunction isValidEvmChainId(id: unknown): id is number {\n return id !== undefined && id !== null && typeof id === 'number' && id > 0;\n}\n\n/**\n * Get EVM chain IDs from app chains configuration\n */\nexport function getEvmChains(appChains?: readonly [Chain, ...Chain[]]): number[] {\n if (!appChains || appChains.length === 0) {\n return [];\n }\n\n return appChains.map((chain) => chain.id).filter(isValidEvmChainId);\n}\n\n/**\n * Type guard to check if a chain list contains EVM chain IDs\n */\nexport function isEvmChainList(chains: (string | number)[]): chains is number[] {\n return chains.length > 0 && chains.every((chain) => typeof chain === 'number');\n}\n"]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { OrbitAdapter } from '@tuwaio/orbit-core';
|
|
2
|
+
import { Chain } from 'viem/chains';
|
|
3
|
+
export { Chain } from 'viem/chains';
|
|
4
|
+
import { EVMWallet, ConnectorEVM } from '@tuwaio/satellite-evm';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Get EVM chain IDs from app chains configuration
|
|
8
|
+
*/
|
|
9
|
+
declare function getEvmChains(appChains?: readonly [Chain, ...Chain[]]): number[];
|
|
10
|
+
/**
|
|
11
|
+
* Type guard to check if a chain list contains EVM chain IDs
|
|
12
|
+
*/
|
|
13
|
+
declare function isEvmChainList(chains: (string | number)[]): chains is number[];
|
|
14
|
+
|
|
15
|
+
declare module '@tuwaio/nova-connect' {
|
|
16
|
+
interface AllChainConfigs {
|
|
17
|
+
/**
|
|
18
|
+
* EVM chains configuration - enhanced from default any type
|
|
19
|
+
* @override Replaces default `any` with specific Chain typing when viem is available
|
|
20
|
+
*/
|
|
21
|
+
appChains?: readonly [Chain, ...Chain[]];
|
|
22
|
+
}
|
|
23
|
+
interface AllWallets {
|
|
24
|
+
[OrbitAdapter.EVM]: EVMWallet;
|
|
25
|
+
}
|
|
26
|
+
interface AllConnectors {
|
|
27
|
+
[OrbitAdapter.EVM]: ConnectorEVM;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export { getEvmChains, isEvmChainList };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { OrbitAdapter } from '@tuwaio/orbit-core';
|
|
2
|
+
import { Chain } from 'viem/chains';
|
|
3
|
+
export { Chain } from 'viem/chains';
|
|
4
|
+
import { EVMWallet, ConnectorEVM } from '@tuwaio/satellite-evm';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Get EVM chain IDs from app chains configuration
|
|
8
|
+
*/
|
|
9
|
+
declare function getEvmChains(appChains?: readonly [Chain, ...Chain[]]): number[];
|
|
10
|
+
/**
|
|
11
|
+
* Type guard to check if a chain list contains EVM chain IDs
|
|
12
|
+
*/
|
|
13
|
+
declare function isEvmChainList(chains: (string | number)[]): chains is number[];
|
|
14
|
+
|
|
15
|
+
declare module '@tuwaio/nova-connect' {
|
|
16
|
+
interface AllChainConfigs {
|
|
17
|
+
/**
|
|
18
|
+
* EVM chains configuration - enhanced from default any type
|
|
19
|
+
* @override Replaces default `any` with specific Chain typing when viem is available
|
|
20
|
+
*/
|
|
21
|
+
appChains?: readonly [Chain, ...Chain[]];
|
|
22
|
+
}
|
|
23
|
+
interface AllWallets {
|
|
24
|
+
[OrbitAdapter.EVM]: EVMWallet;
|
|
25
|
+
}
|
|
26
|
+
interface AllConnectors {
|
|
27
|
+
[OrbitAdapter.EVM]: ConnectorEVM;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export { getEvmChains, isEvmChainList };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function r(e){return e!=null&&typeof e=="number"&&e>0}function t(e){return !e||e.length===0?[]:e.map(n=>n.id).filter(r)}function i(e){return e.length>0&&e.every(n=>typeof n=="number")}export{t as getEvmChains,i as isEvmChainList};//# sourceMappingURL=index.js.map
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/evm/utils.ts"],"names":["isValidEvmChainId","id","getEvmChains","appChains","chain","isEvmChainList","chains"],"mappings":"AAKA,SAASA,CAAAA,CAAkBC,EAA2B,CACpD,OAA2BA,GAAO,IAAA,EAAQ,OAAOA,CAAAA,EAAO,QAAA,EAAYA,CAAAA,CAAK,CAC3E,CAKO,SAASC,CAAAA,CAAaC,EAAoD,CAC/E,OAAI,CAACA,CAAAA,EAAaA,CAAAA,CAAU,MAAA,GAAW,CAAA,CAC9B,EAAC,CAGHA,EAAU,GAAA,CAAKC,CAAAA,EAAUA,EAAM,EAAE,CAAA,CAAE,OAAOJ,CAAiB,CACpE,CAKO,SAASK,CAAAA,CAAeC,CAAAA,CAAiD,CAC9E,OAAOA,CAAAA,CAAO,OAAS,CAAA,EAAKA,CAAAA,CAAO,MAAOF,CAAAA,EAAU,OAAOA,CAAAA,EAAU,QAAQ,CAC/E","file":"index.js","sourcesContent":["import type { Chain } from 'viem/chains';\n\n/**\n * Type guard to check if a value is a valid EVM chain ID\n */\nfunction isValidEvmChainId(id: unknown): id is number {\n return id !== undefined && id !== null && typeof id === 'number' && id > 0;\n}\n\n/**\n * Get EVM chain IDs from app chains configuration\n */\nexport function getEvmChains(appChains?: readonly [Chain, ...Chain[]]): number[] {\n if (!appChains || appChains.length === 0) {\n return [];\n }\n\n return appChains.map((chain) => chain.id).filter(isValidEvmChainId);\n}\n\n/**\n * Type guard to check if a chain list contains EVM chain IDs\n */\nexport function isEvmChainList(chains: (string | number)[]): chains is number[] {\n return chains.length > 0 && chains.every((chain) => typeof chain === 'number');\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var novaCore=require('@tuwaio/nova-core'),orbitCore=require('@tuwaio/orbit-core'),react=require('react');function z(w){let{abbreviateSymbols:r=12,maxNameLength:y=30,autoRetry:C=false,retryDelay:u=3e3,store:f}=w,n=f.getState().activeWallet,N=f.getState().getAdapter,a=react.useMemo(()=>n?.address,[n?.address]),l=react.useMemo(()=>n?.walletType,[n?.walletType]),e=react.useMemo(()=>l?N(orbitCore.getAdapterFromWalletType(l??`${orbitCore.OrbitAdapter.EVM}:not-connected`)):null,[N,l]),[t,o]=react.useState(null),[p,m]=react.useState(null),[W,g]=react.useState(false),[b,s]=react.useState(null),c=react.useRef(null),v=react.useRef(null),x=react.useMemo(()=>{if(!e)return {hasNameResolver:false,hasAvatarResolver:false};let d="getName"in e&&typeof e.getName=="function",i="getAvatar"in e&&typeof e.getAvatar=="function";return {hasNameResolver:d,hasAvatarResolver:i}},[e]),A=react.useCallback(()=>{c.current&&(c.current.abort(),c.current=null),v.current!==null&&(clearTimeout(v.current),v.current=null);},[]),h=react.useCallback(async()=>{if(A(),!a||!e||!x.hasNameResolver){o(null),m(null),g(false),s(null);return}c.current=new AbortController;let{signal:d}=c.current;g(true),s(null),o(null),m(null);try{if(d.aborted)return;let i=await e.getName?.(a);if(d.aborted)return;if(i&&(o(i),x.hasAvatarResolver))try{let B=await e.getAvatar?.(i);d.aborted||m(B??null);}catch(B){console.warn("Failed to fetch avatar:",B),d.aborted||m(null);}}catch(i){if(d.aborted)return;let B=i instanceof Error?i.message:"Failed to fetch name service data";console.error("Failed to fetch name service data:",i),s(B),o(null),m(null),C&&(v.current=setTimeout(()=>{h();},u));}finally{d.aborted||g(false);}},[a,e,x,C,u,A]),I=react.useCallback(()=>{s(null),h();},[h]);react.useEffect(()=>(h(),A),[h,A]),react.useEffect(()=>A,[A]);let M=react.useMemo(()=>t?t.length>y?novaCore.textCenterEllipsis(t,r,r):t:a?novaCore.textCenterEllipsis(a,r,r):void 0,[t,a,y,r]);return {ensName:t,ensAvatar:p,isLoading:W,ensNameAbbreviated:M,error:b,retry:I}}function X({store:w}){let[r,y]=react.useState({}),[C,u]=react.useState(false),f=react.useRef(null),n=w.getState().activeWallet,N=w.getState().getAdapter,a=n?.address,l=n?.chainId,e=react.useMemo(()=>a&&l?`${a}-${l}`:null,[a,l]),t=react.useMemo(()=>n?.walletType?N(orbitCore.getAdapterFromWalletType(n.walletType)):null,[N,n?.walletType]),o=react.useMemo(()=>t&&"getBalance"in t&&typeof t.getBalance=="function",[t]),p=react.useCallback(async(g=false)=>{if(!a||!t||!l||!e||!o){u(false);return}let b=`${e}-${Date.now()}`;if(f.current=b,!g&&r[e]){u(false);return}u(true);try{let s=await t.getBalance(a,l);f.current===b&&y(c=>({...c,[e]:s}));}catch(s){console.error(`Failed to fetch native balance for ${e}:`,s),g&&f.current===b&&y(c=>{let v={...c};return delete v[e],v});}finally{f.current===b&&u(false);}},[a,t,l,e,o,r]),m=react.useCallback(()=>{p(true);},[p]);return react.useEffect(()=>{e&&o&&!r[e]?p(false):(!e||!o)&&u(false);},[e,o,r,p]),react.useEffect(()=>()=>{f.current=null;},[]),{balance:react.useMemo(()=>e&&r[e]||null,[e,r]),isLoading:C,refetch:m}}exports.useGetWalletNameAndAvatar=z;exports.useWalletNativeBalance=X;//# sourceMappingURL=index.cjs.map
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/hooks/useGetWalletNameAndAvatar.ts","../../src/hooks/useWalletNativeBalance.ts"],"names":["useGetWalletNameAndAvatar","options","abbreviateSymbols","maxNameLength","autoRetry","retryDelay","store","wallet","getAdapter","walletAddress","useMemo","walletType","foundAdapter","getAdapterFromWalletType","OrbitAdapter","ensName","setEnsName","useState","ensAvatar","setEnsAvatar","isLoading","setIsLoading","error","setError","abortControllerRef","useRef","retryTimeoutRef","adapterCapabilities","hasNameResolver","hasAvatarResolver","cleanup","useCallback","fetchNameData","signal","name","avatar","avatarError","errorMessage","retry","useEffect","ensNameAbbreviated","textCenterEllipsis","useWalletNativeBalance","balanceCache","setBalanceCache","fetchOperationRef","currentChainId","cacheKey","hasBalanceResolver","fetchBalance","forceRefresh","operationId","balanceResult","prevCache","newCache","refetch"],"mappings":"sHAsEO,SAASA,CAAAA,CAA0BC,EAAoE,CAC5G,GAAM,CAAE,iBAAA,CAAAC,CAAAA,CAAoB,GAAI,aAAA,CAAAC,CAAAA,CAAgB,GAAI,SAAA,CAAAC,CAAAA,CAAY,MAAO,U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AA,GAEvB3B,CAAAA,CAAa,KAAK,EAEtB,CAAA,CAAG,CAAC0B,CAAAA,CAAUC,CAAAA,CAAoBL,EAAcM,CAAY,CAAC,EAI7DV,eAAAA,CAAU,IACD,IAAM,CAEXM,CAAAA,CAAkB,QAAU,KAC9B,CAAA,CACC,EAAE,EAUE,CACL,OAAA,CANkCnC,cAAQ,IACnCqC,CAAAA,EAAWJ,EAAaI,CAAQ,CAAA,EAAK,KAC3C,CAACA,CAAAA,CAAUJ,CAAY,CAAC,CAAA,CAKzB,UAAAvB,CAAAA,CACA,OAAA,CAAAmC,CACF,CACF","file":"index.cjs","sourcesContent":["import { textCenterEllipsis } from '@tuwaio/nova-core';\nimport { getAdapterFromWalletType, OrbitAdapter } from '@tuwaio/orbit-core';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport { NovaConnectProviderProps } from './useNovaConnect';\n\nexport interface WalletNameAndAvatarData {\n /** The resolved name from the Name Service (e.g., ENS, like \"alice.eth\"), or null if not found. */\n ensName: string | null;\n /** The URL of the avatar associated with the name, or null if not found. */\n ensAvatar: string | null;\n /** True while the name service data is being fetched. */\n isLoading: boolean;\n /** A truncated version of the name for display, or the abbreviated address if no name. */\n ensNameAbbreviated: string | undefined;\n /** Error message if the name resolution failed. */\n error: string | null;\n /** Function to retry the name resolution manually. */\n retry: () => void;\n}\n\ninterface UseGetWalletNameAndAvatarOptions extends Pick<NovaConnectProviderProps, 'store'> {\n /** Number of characters to show on each side when abbreviating (default: 12) */\n abbreviateSymbols?: number;\n /** Maximum length before abbreviation is applied (default: 30) */\n maxNameLength?: number;\n /** Whether to automatically retry on failure (default: false) */\n autoRetry?: boolean;\n /** Retry delay in milliseconds (default: 3000) */\n retryDelay?: number;\n}\n\n/**\n * A custom hook to fetch the Name Service (e.g., ENS) name and avatar\n * for the currently active wallet.\n *\n * This hook automatically detects the active wallet and its corresponding\n * adapter via the `useSatelliteConnectStore` and attempts to resolve the\n * wallet address to a human-readable name and avatar.\n *\n * @param options Configuration options for the hook\n * @returns An object containing the resolved name, avatar, loading state, and utility functions\n *\n * @example\n * ```typescript\n * import { useGetWalletNameAndAvatar } from './useGetWalletNameAndAvatar';\n *\n * function DisplayWalletInfo() {\n * const { ensName, ensAvatar, isLoading, ensNameAbbreviated, error, retry } = useGetWalletNameAndAvatar({\n * abbreviateSymbols: 8,\n * maxNameLength: 25\n * });\n *\n * if (isLoading) {\n * return <div>Resolving name...</div>;\n * }\n *\n * if (error) {\n * return <div>Error: {error} <button onClick={retry}>Retry</button></div>;\n * }\n *\n * return (\n * <div className=\"wallet-info\">\n * {ensAvatar && <img src={ensAvatar} alt=\"Wallet Avatar\" />}\n * <p title={ensName || ''}>{ensNameAbbreviated || 'No Name Found'}</p>\n * </div>\n * );\n * }\n * ```\n */\nexport function useGetWalletNameAndAvatar(options: UseGetWalletNameAndAvatarOptions): WalletNameAndAvatarData {\n const { abbreviateSymbols = 12, maxNameLength = 30, autoRetry = false, retryDelay = 3000, store } = options;\n\n // Store state selectors - memoized for performance\n const wallet = store.getState().activeWallet;\n const getAdapter = store.getState().getAdapter;\n\n // Memoize wallet address and adapter for dependency tracking\n const walletAddress = useMemo(() => wallet?.address, [wallet?.address]);\n const walletType = useMemo(() => wallet?.walletType, [wallet?.walletType]);\n\n const foundAdapter = useMemo(() => {\n if (!walletType) return null;\n return getAdapter(getAdapterFromWalletType(walletType ?? `${OrbitAdapter.EVM}:not-connected`));\n }, [getAdapter, walletType]);\n\n // State variables\n const [ensName, setEnsName] = useState<string | null>(null);\n const [ensAvatar, setEnsAvatar] = useState<string | null>(null);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n // Refs for cleanup and retry functionality\n const abortControllerRef = useRef<AbortController | null>(null);\n const retryTimeoutRef = useRef<number | null>(null);\n\n // Memoize adapter capabilities\n const adapterCapabilities = useMemo(() => {\n if (!foundAdapter) {\n return { hasNameResolver: false, hasAvatarResolver: false };\n }\n\n const hasNameResolver = 'getName' in foundAdapter && typeof foundAdapter.getName === 'function';\n const hasAvatarResolver = 'getAvatar' in foundAdapter && typeof foundAdapter.getAvatar === 'function';\n\n return { hasNameResolver, hasAvatarResolver };\n }, [foundAdapter]);\n\n // Cleanup function\n const cleanup = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n }\n if (retryTimeoutRef.current !== null) {\n clearTimeout(retryTimeoutRef.current);\n retryTimeoutRef.current = null;\n }\n }, []);\n\n // Main fetch function\n const fetchNameData = useCallback(async () => {\n cleanup();\n\n // Exit conditions\n if (!walletAddress || !foundAdapter || !adapterCapabilities.hasNameResolver) {\n setEnsName(null);\n setEnsAvatar(null);\n setIsLoading(false);\n setError(null);\n return;\n }\n\n // Create new abort controller for this request\n abortControllerRef.current = new AbortController();\n const { signal } = abortControllerRef.current;\n\n // Start loading\n setIsLoading(true);\n setError(null);\n setEnsName(null);\n setEnsAvatar(null);\n\n try {\n // Check if request was aborted\n if (signal.aborted) return;\n\n // Attempt to resolve the name\n const name = await foundAdapter.getName?.(walletAddress);\n\n if (signal.aborted) return;\n\n if (name) {\n setEnsName(name);\n\n // If avatar resolution is supported, fetch the avatar\n if (adapterCapabilities.hasAvatarResolver) {\n try {\n const avatar = await foundAdapter.getAvatar?.(name);\n if (!signal.aborted) {\n // Handle undefined case by converting to null\n setEnsAvatar(avatar ?? null);\n }\n } catch (avatarError) {\n // Avatar fetch failed, but name succeeded - not critical\n console.warn('Failed to fetch avatar:', avatarError);\n if (!signal.aborted) {\n setEnsAvatar(null);\n }\n }\n }\n }\n } catch (error) {\n if (signal.aborted) return;\n\n const errorMessage = error instanceof Error ? error.message : 'Failed to fetch name service data';\n console.error('Failed to fetch name service data:', error);\n\n setError(errorMessage);\n setEnsName(null);\n setEnsAvatar(null);\n\n // Auto retry if enabled\n if (autoRetry) {\n retryTimeoutRef.current = setTimeout(() => {\n fetchNameData();\n }, retryDelay) as unknown as number;\n }\n } finally {\n if (!signal.aborted) {\n setIsLoading(false);\n }\n }\n }, [walletAddress, foundAdapter, adapterCapabilities, autoRetry, retryDelay, cleanup]);\n\n // Manual retry function\n const retry = useCallback(() => {\n setError(null);\n fetchNameData();\n }, [fetchNameData]);\n\n // Effect to fetch data when dependencies change\n useEffect(() => {\n fetchNameData();\n return cleanup;\n }, [fetchNameData, cleanup]);\n\n // Cleanup on unmount\n useEffect(() => {\n return cleanup;\n }, [cleanup]);\n\n // Memoized abbreviated name computation\n const ensNameAbbreviated = useMemo(() => {\n if (ensName) {\n return ensName.length > maxNameLength\n ? textCenterEllipsis(ensName, abbreviateSymbols, abbreviateSymbols)\n : ensName;\n }\n\n return walletAddress ? textCenterEllipsis(walletAddress, abbreviateSymbols, abbreviateSymbols) : undefined;\n }, [ensName, walletAddress, maxNameLength, abbreviateSymbols]);\n\n return {\n ensName,\n ensAvatar,\n isLoading,\n ensNameAbbreviated,\n error,\n retry,\n };\n}\n","import { getAdapterFromWalletType } from '@tuwaio/orbit-core';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport { NovaConnectProviderProps } from './useNovaConnect';\n\n/**\n * @interface NativeBalanceResult\n * Represents the native token balance returned by the adapter.\n * The value is already formatted for human readability.\n * @property {string} value The native token balance formatted to standard decimals (e.g., \"1.5\").\n * @property {string} symbol The symbol of the native token (e.g., \"ETH\").\n */\nexport interface NativeBalanceResult {\n value: string;\n symbol: string;\n}\n\n// Type for the balance state within the hook (the fetched data or null).\ntype NativeBalanceState = NativeBalanceResult | null;\n\n// Type for the local cache: \"walletAddress-chainId\" -> { value, symbol }.\ntype BalanceCache = Record<string, NativeBalanceResult>;\n\n/**\n * @interface NativeBalanceData\n * The object returned by the useWalletNativeBalance hook.\n * @property {NativeBalanceState} balance The native token balance and symbol, or null.\n * @property {boolean} isLoading True while the balance is being fetched for the current wallet/chain combination.\n * @property {() => void} refetch Function to manually trigger a balance refresh.\n */\ninterface NativeBalanceData {\n balance: NativeBalanceState;\n isLoading: boolean;\n refetch: () => void;\n}\n\n/**\n * Custom hook to fetch the native token balance for the currently connected wallet\n * on the active chain. It includes a local cache layer to prevent redundant network calls\n * when switching between components or on re-renders for the same wallet/chain.\n *\n * @returns {NativeBalanceData} An object containing the balance data and loading state.\n *\n * @example\n * ```typescript\n * import { useWalletNativeBalance } from './useWalletNativeBalance';\n *\n * function NativeTokenDisplay() {\n * const { balance, isLoading, refetch } = useWalletNativeBalance();\n *\n * if (isLoading) {\n * return <p>Loading balance...</p>;\n * }\n *\n * // Display the formatted balance and symbol\n * return (\n * <div>\n * <p>Balance: {balance ? `${balance.value} ${balance.symbol}` : '0.00'}</p>\n * <button onClick={refetch}>Refresh</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useWalletNativeBalance({ store }: Pick<NovaConnectProviderProps, 'store'>): NativeBalanceData {\n // --- 1. STATE & CACHE SETUP ---\n\n // Local cache storage. Keys combine wallet address and chain ID.\n const [balanceCache, setBalanceCache] = useState<BalanceCache>({});\n\n // Local loading state, managed alongside the cache check.\n const [isLoading, setIsLoading] = useState<boolean>(false);\n\n // Track the current fetch operation to prevent race conditions\n const fetchOperationRef = useRef<string | null>(null);\n\n // Store state selectors - memoized for performance\n const wallet = store.getState().activeWallet;\n const getAdapter = store.getState().getAdapter;\n\n // --- 2. COMPUTED INPUTS ---\n\n const walletAddress = wallet?.address;\n const currentChainId = wallet?.chainId;\n\n // Create the unique key for cache lookups: \"address-chainId\".\n const cacheKey = useMemo(() => {\n return walletAddress && currentChainId ? `${walletAddress}-${currentChainId}` : null;\n }, [walletAddress, currentChainId]);\n\n // Find the actual adapter object from the adapter map.\n const foundAdapter = useMemo(() => {\n if (!wallet?.walletType) return null;\n return getAdapter(getAdapterFromWalletType(wallet.walletType));\n }, [getAdapter, wallet?.walletType]);\n\n // Check if the adapter has balance functionality\n const hasBalanceResolver = useMemo(() => {\n return foundAdapter && 'getBalance' in foundAdapter && typeof foundAdapter.getBalance === 'function';\n }, [foundAdapter]);\n\n // --- 3. BALANCE FETCHING LOGIC ---\n\n const fetchBalance = useCallback(\n async (forceRefresh = false) => {\n // Exit early if essential data is missing (not connected).\n if (!walletAddress || !foundAdapter || !currentChainId || !cacheKey || !hasBalanceResolver) {\n setIsLoading(false);\n return;\n }\n\n // Set the current operation ID to prevent race conditions\n const operationId = `${cacheKey}-${Date.now()}`;\n fetchOperationRef.current = operationId;\n\n // Check cache unless forcing a refresh\n if (!forceRefresh) {\n const cachedBalance = balanceCache[cacheKey];\n if (cachedBalance) {\n setIsLoading(false);\n return;\n }\n }\n\n setIsLoading(true);\n\n try {\n // Call the adapter's getBalance method\n const balanceResult: NativeBalanceResult = await foundAdapter.getBalance(walletAddress, currentChainId);\n\n // Only update if this operation is still the latest one\n if (fetchOperationRef.current === operationId) {\n setBalanceCache((prevCache) => ({\n ...prevCache,\n [cacheKey]: balanceResult,\n }));\n }\n } catch (error) {\n console.error(`Failed to fetch native balance for ${cacheKey}:`, error);\n\n // Optionally clear cache entry on error (if you want to retry on next call)\n if (forceRefresh && fetchOperationRef.current === operationId) {\n setBalanceCache((prevCache) => {\n const newCache = { ...prevCache };\n delete newCache[cacheKey];\n return newCache;\n });\n }\n } finally {\n // Only update loading state if this operation is still current\n if (fetchOperationRef.current === operationId) {\n setIsLoading(false);\n }\n }\n },\n [walletAddress, foundAdapter, currentChainId, cacheKey, hasBalanceResolver, balanceCache],\n );\n\n // Memoized refetch function that forces a refresh\n const refetch = useCallback(() => {\n fetchBalance(true);\n }, [fetchBalance]);\n\n // --- 4. EFFECT FOR INITIAL FETCH ---\n\n useEffect(() => {\n // Only fetch if we have all required data and no cached result\n if (cacheKey && hasBalanceResolver && !balanceCache[cacheKey]) {\n fetchBalance(false);\n } else if (!cacheKey || !hasBalanceResolver) {\n // Reset loading state if we can't fetch\n setIsLoading(false);\n }\n }, [cacheKey, hasBalanceResolver, balanceCache, fetchBalance]);\n\n // --- 5. CLEANUP EFFECT ---\n\n useEffect(() => {\n return () => {\n // Cancel any ongoing operations when component unmounts\n fetchOperationRef.current = null;\n };\n }, []);\n\n // --- 6. RETURNED DATA ---\n\n // The definitive balance is always derived from the cache based on the current key.\n const balance: NativeBalanceState = useMemo(() => {\n return cacheKey ? balanceCache[cacheKey] || null : null;\n }, [cacheKey, balanceCache]);\n\n // Return the fetched balance data and the loading status.\n return {\n balance, // { value: \"1.5\", symbol: \"ETH\" } or null\n isLoading,\n refetch,\n };\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {textCenterEllipsis}from'@tuwaio/nova-core';import {getAdapterFromWalletType,OrbitAdapter}from'@tuwaio/orbit-core';import {useMemo,useState,useRef,useCallback,useEffect}from'react';function z(w){let{abbreviateSymbols:r=12,maxNameLength:y=30,autoRetry:C=false,retryDelay:u=3e3,store:f}=w,n=f.getState().activeWallet,N=f.getState().getAdapter,a=useMemo(()=>n?.address,[n?.address]),l=useMemo(()=>n?.walletType,[n?.walletType]),e=useMemo(()=>l?N(getAdapterFromWalletType(l??`${OrbitAdapter.EVM}:not-connected`)):null,[N,l]),[t,o]=useState(null),[p,m]=useState(null),[W,g]=useState(false),[b,s]=useState(null),c=useRef(null),v=useRef(null),x=useMemo(()=>{if(!e)return {hasNameResolver:false,hasAvatarResolver:false};let d="getName"in e&&typeof e.getName=="function",i="getAvatar"in e&&typeof e.getAvatar=="function";return {hasNameResolver:d,hasAvatarResolver:i}},[e]),A=useCallback(()=>{c.current&&(c.current.abort(),c.current=null),v.current!==null&&(clearTimeout(v.current),v.current=null);},[]),h=useCallback(async()=>{if(A(),!a||!e||!x.hasNameResolver){o(null),m(null),g(false),s(null);return}c.current=new AbortController;let{signal:d}=c.current;g(true),s(null),o(null),m(null);try{if(d.aborted)return;let i=await e.getName?.(a);if(d.aborted)return;if(i&&(o(i),x.hasAvatarResolver))try{let B=await e.getAvatar?.(i);d.aborted||m(B??null);}catch(B){console.warn("Failed to fetch avatar:",B),d.aborted||m(null);}}catch(i){if(d.aborted)return;let B=i instanceof Error?i.message:"Failed to fetch name service data";console.error("Failed to fetch name service data:",i),s(B),o(null),m(null),C&&(v.current=setTimeout(()=>{h();},u));}finally{d.aborted||g(false);}},[a,e,x,C,u,A]),I=useCallback(()=>{s(null),h();},[h]);useEffect(()=>(h(),A),[h,A]),useEffect(()=>A,[A]);let M=useMemo(()=>t?t.length>y?textCenterEllipsis(t,r,r):t:a?textCenterEllipsis(a,r,r):void 0,[t,a,y,r]);return {ensName:t,ensAvatar:p,isLoading:W,ensNameAbbreviated:M,error:b,retry:I}}function X({store:w}){let[r,y]=useState({}),[C,u]=useState(false),f=useRef(null),n=w.getState().activeWallet,N=w.getState().getAdapter,a=n?.address,l=n?.chainId,e=useMemo(()=>a&&l?`${a}-${l}`:null,[a,l]),t=useMemo(()=>n?.walletType?N(getAdapterFromWalletType(n.walletType)):null,[N,n?.walletType]),o=useMemo(()=>t&&"getBalance"in t&&typeof t.getBalance=="function",[t]),p=useCallback(async(g=false)=>{if(!a||!t||!l||!e||!o){u(false);return}let b=`${e}-${Date.now()}`;if(f.current=b,!g&&r[e]){u(false);return}u(true);try{let s=await t.getBalance(a,l);f.current===b&&y(c=>({...c,[e]:s}));}catch(s){console.error(`Failed to fetch native balance for ${e}:`,s),g&&f.current===b&&y(c=>{let v={...c};return delete v[e],v});}finally{f.current===b&&u(false);}},[a,t,l,e,o,r]),m=useCallback(()=>{p(true);},[p]);return useEffect(()=>{e&&o&&!r[e]?p(false):(!e||!o)&&u(false);},[e,o,r,p]),useEffect(()=>()=>{f.current=null;},[]),{balance:useMemo(()=>e&&r[e]||null,[e,r]),isLoading:C,refetch:m}}export{z as useGetWalletNameAndAvatar,X as useWalletNativeBalance};//# sourceMappingURL=index.js.map
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/hooks/useGetWalletNameAndAvatar.ts","../../src/hooks/useWalletNativeBalance.ts"],"names":["useGetWalletNameAndAvatar","options","abbreviateSymbols","maxNameLength","autoRetry","retryDelay","store","wallet","getAdapter","walletAddress","useMemo","walletType","foundAdapter","getAdapterFromWalletType","OrbitAdapter","ensName","setEnsName","useState","ensAvatar","setEnsAvatar","isLoading","setIsLoading","error","setError","abortControllerRef","useRef","retryTimeoutRef","adapterCapabilities","hasNameResolver","hasAvatarResolver","cleanup","useCallback","fetchNameData","signal","name","avatar","avatarError","errorMessage","retry","useEffect","ensNameAbbreviated","textCenterEllipsis","useWalletNativeBalance","balanceCache","setBalanceCache","fetchOperationRef","currentChainId","cacheKey","hasBalanceResolver","fetchBalance","forceRefresh","operationId","balanceResult","prevCache","newCache","refetch"],"mappings":"4LAsEO,SAASA,CAAAA,CAA0BC,EAAoE,CAC5G,GAAM,CAAE,iBAAA,CAAAC,CAAAA,CAAoB,GAAI,aAAA,CAAAC,CAAAA,CAAgB,GAAI,SAAA,CAAAC,CAAAA,CAAY,MAAO,UAAA,CAAAC,CAAAA,CAAa,IAAM,KAAA,CAAAC,CAAM,EAAIL,CAAAA,CAG9FM,CAAAA,CAASD,CAAAA,CAAM,QAAA,GAAW,YAAA,CAC1BE,CAAAA,CAAaF,EAAM,QAAA,EAAS,CAAE,WAG9BG,CAAAA,CAAgBC,OAAAA,CAAQ,IAAMH,CAAAA,EAAQ,OAAA,CAAS,CAACA,CAAAA,EAAQ,OAAO,CAAC,CAAA,CAChEI,CAAAA,CAAaD,QAAQ,IAAMH,CAAAA,EAAQ,UAAA,CAAY,CAACA,GAAQ,UAAU,CAAC,EAEnEK,CAAAA,CAAeF,OAAAA,CAAQ,IACtBC,CAAAA,CACEH,CAAAA,CAAWK,yBAAyBF,CAAAA,EAAc,CAAA,EAAGG,aAAa,GAAG,CAAA,cAAA,CAAgB,CAAC,CAAA,CADrE,IAAA,CAEvB,CAACN,CAAAA,CAAYG,CAAU,CAAC,CAAA,CAGrB,CAACI,CAAAA,CAASC,CAAU,EAAIC,QAAAA,CAAwB,IAAI,EACpD,CAACC,CAAAA,CAAWC,CAAY,CAAA,CAAIF,QAAAA,CAAwB,IAAI,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IAAMC,CAAAA,CAAW,CAAE,GAAGD,CAAU,EAChC,OAAA,OAAOC,CAAAA,CAASP,CAAQ,CAAA,CACjBO,CACT,CAAC,EAEL,QAAE,CAEIT,CAAAA,CAAkB,UAAYM,CAAAA,EAChC9B,CAAAA,CAAa,KAAK,EAEtB,CACF,EACA,CAACZ,CAAAA,CAAeG,EAAckC,CAAAA,CAAgBC,CAAAA,CAAUC,EAAoBL,CAAY,CAC1F,EAGMY,CAAAA,CAAUxB,WAAAA,CAAY,IAAM,CAChCkB,EAAa,IAAI,EACnB,EAAG,CAACA,CAAY,CAAC,CAAA,CAIjB,OAAAV,UAAU,IAAM,CAEVQ,GAAYC,CAAAA,EAAsB,CAACL,EAAaI,CAAQ,CAAA,CAC1DE,EAAa,KAAK,CAAA,CAAA,CACT,CAACF,CAAAA,EAAY,CAACC,CAAAA,GAEvB3B,CAAAA,CAAa,KAAK,EAEtB,CAAA,CAAG,CAAC0B,CAAAA,CAAUC,CAAAA,CAAoBL,EAAcM,CAAY,CAAC,EAI7DV,SAAAA,CAAU,IACD,IAAM,CAEXM,CAAAA,CAAkB,QAAU,KAC9B,CAAA,CACC,EAAE,EAUE,CACL,OAAA,CANkCnC,QAAQ,IACnCqC,CAAAA,EAAWJ,EAAaI,CAAQ,CAAA,EAAK,KAC3C,CAACA,CAAAA,CAAUJ,CAAY,CAAC,CAAA,CAKzB,UAAAvB,CAAAA,CACA,OAAA,CAAAmC,CACF,CACF","file":"index.js","sourcesContent":["import { textCenterEllipsis } from '@tuwaio/nova-core';\nimport { getAdapterFromWalletType, OrbitAdapter } from '@tuwaio/orbit-core';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport { NovaConnectProviderProps } from './useNovaConnect';\n\nexport interface WalletNameAndAvatarData {\n /** The resolved name from the Name Service (e.g., ENS, like \"alice.eth\"), or null if not found. */\n ensName: string | null;\n /** The URL of the avatar associated with the name, or null if not found. */\n ensAvatar: string | null;\n /** True while the name service data is being fetched. */\n isLoading: boolean;\n /** A truncated version of the name for display, or the abbreviated address if no name. */\n ensNameAbbreviated: string | undefined;\n /** Error message if the name resolution failed. */\n error: string | null;\n /** Function to retry the name resolution manually. */\n retry: () => void;\n}\n\ninterface UseGetWalletNameAndAvatarOptions extends Pick<NovaConnectProviderProps, 'store'> {\n /** Number of characters to show on each side when abbreviating (default: 12) */\n abbreviateSymbols?: number;\n /** Maximum length before abbreviation is applied (default: 30) */\n maxNameLength?: number;\n /** Whether to automatically retry on failure (default: false) */\n autoRetry?: boolean;\n /** Retry delay in milliseconds (default: 3000) */\n retryDelay?: number;\n}\n\n/**\n * A custom hook to fetch the Name Service (e.g., ENS) name and avatar\n * for the currently active wallet.\n *\n * This hook automatically detects the active wallet and its corresponding\n * adapter via the `useSatelliteConnectStore` and attempts to resolve the\n * wallet address to a human-readable name and avatar.\n *\n * @param options Configuration options for the hook\n * @returns An object containing the resolved name, avatar, loading state, and utility functions\n *\n * @example\n * ```typescript\n * import { useGetWalletNameAndAvatar } from './useGetWalletNameAndAvatar';\n *\n * function DisplayWalletInfo() {\n * const { ensName, ensAvatar, isLoading, ensNameAbbreviated, error, retry } = useGetWalletNameAndAvatar({\n * abbreviateSymbols: 8,\n * maxNameLength: 25\n * });\n *\n * if (isLoading) {\n * return <div>Resolving name...</div>;\n * }\n *\n * if (error) {\n * return <div>Error: {error} <button onClick={retry}>Retry</button></div>;\n * }\n *\n * return (\n * <div className=\"wallet-info\">\n * {ensAvatar && <img src={ensAvatar} alt=\"Wallet Avatar\" />}\n * <p title={ensName || ''}>{ensNameAbbreviated || 'No Name Found'}</p>\n * </div>\n * );\n * }\n * ```\n */\nexport function useGetWalletNameAndAvatar(options: UseGetWalletNameAndAvatarOptions): WalletNameAndAvatarData {\n const { abbreviateSymbols = 12, maxNameLength = 30, autoRetry = false, retryDelay = 3000, store } = options;\n\n // Store state selectors - memoized for performance\n const wallet = store.getState().activeWallet;\n const getAdapter = store.getState().getAdapter;\n\n // Memoize wallet address and adapter for dependency tracking\n const walletAddress = useMemo(() => wallet?.address, [wallet?.address]);\n const walletType = useMemo(() => wallet?.walletType, [wallet?.walletType]);\n\n const foundAdapter = useMemo(() => {\n if (!walletType) return null;\n return getAdapter(getAdapterFromWalletType(walletType ?? `${OrbitAdapter.EVM}:not-connected`));\n }, [getAdapter, walletType]);\n\n // State variables\n const [ensName, setEnsName] = useState<string | null>(null);\n const [ensAvatar, setEnsAvatar] = useState<string | null>(null);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n // Refs for cleanup and retry functionality\n const abortControllerRef = useRef<AbortController | null>(null);\n const retryTimeoutRef = useRef<number | null>(null);\n\n // Memoize adapter capabilities\n const adapterCapabilities = useMemo(() => {\n if (!foundAdapter) {\n return { hasNameResolver: false, hasAvatarResolver: false };\n }\n\n const hasNameResolver = 'getName' in foundAdapter && typeof foundAdapter.getName === 'function';\n const hasAvatarResolver = 'getAvatar' in foundAdapter && typeof foundAdapter.getAvatar === 'function';\n\n return { hasNameResolver, hasAvatarResolver };\n }, [foundAdapter]);\n\n // Cleanup function\n const cleanup = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n }\n if (retryTimeoutRef.current !== null) {\n clearTimeout(retryTimeoutRef.current);\n retryTimeoutRef.current = null;\n }\n }, []);\n\n // Main fetch function\n const fetchNameData = useCallback(async () => {\n cleanup();\n\n // Exit conditions\n if (!walletAddress || !foundAdapter || !adapterCapabilities.hasNameResolver) {\n setEnsName(null);\n setEnsAvatar(null);\n setIsLoading(false);\n setError(null);\n return;\n }\n\n // Create new abort controller for this request\n abortControllerRef.current = new AbortController();\n const { signal } = abortControllerRef.current;\n\n // Start loading\n setIsLoading(true);\n setError(null);\n setEnsName(null);\n setEnsAvatar(null);\n\n try {\n // Check if request was aborted\n if (signal.aborted) return;\n\n // Attempt to resolve the name\n const name = await foundAdapter.getName?.(walletAddress);\n\n if (signal.aborted) return;\n\n if (name) {\n setEnsName(name);\n\n // If avatar resolution is supported, fetch the avatar\n if (adapterCapabilities.hasAvatarResolver) {\n try {\n const avatar = await foundAdapter.getAvatar?.(name);\n if (!signal.aborted) {\n // Handle undefined case by converting to null\n setEnsAvatar(avatar ?? null);\n }\n } catch (avatarError) {\n // Avatar fetch failed, but name succeeded - not critical\n console.warn('Failed to fetch avatar:', avatarError);\n if (!signal.aborted) {\n setEnsAvatar(null);\n }\n }\n }\n }\n } catch (error) {\n if (signal.aborted) return;\n\n const errorMessage = error instanceof Error ? error.message : 'Failed to fetch name service data';\n console.error('Failed to fetch name service data:', error);\n\n setError(errorMessage);\n setEnsName(null);\n setEnsAvatar(null);\n\n // Auto retry if enabled\n if (autoRetry) {\n retryTimeoutRef.current = setTimeout(() => {\n fetchNameData();\n }, retryDelay) as unknown as number;\n }\n } finally {\n if (!signal.aborted) {\n setIsLoading(false);\n }\n }\n }, [walletAddress, foundAdapter, adapterCapabilities, autoRetry, retryDelay, cleanup]);\n\n // Manual retry function\n const retry = useCallback(() => {\n setError(null);\n fetchNameData();\n }, [fetchNameData]);\n\n // Effect to fetch data when dependencies change\n useEffect(() => {\n fetchNameData();\n return cleanup;\n }, [fetchNameData, cleanup]);\n\n // Cleanup on unmount\n useEffect(() => {\n return cleanup;\n }, [cleanup]);\n\n // Memoized abbreviated name computation\n const ensNameAbbreviated = useMemo(() => {\n if (ensName) {\n return ensName.length > maxNameLength\n ? textCenterEllipsis(ensName, abbreviateSymbols, abbreviateSymbols)\n : ensName;\n }\n\n return walletAddress ? textCenterEllipsis(walletAddress, abbreviateSymbols, abbreviateSymbols) : undefined;\n }, [ensName, walletAddress, maxNameLength, abbreviateSymbols]);\n\n return {\n ensName,\n ensAvatar,\n isLoading,\n ensNameAbbreviated,\n error,\n retry,\n };\n}\n","import { getAdapterFromWalletType } from '@tuwaio/orbit-core';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport { NovaConnectProviderProps } from './useNovaConnect';\n\n/**\n * @interface NativeBalanceResult\n * Represents the native token balance returned by the adapter.\n * The value is already formatted for human readability.\n * @property {string} value The native token balance formatted to standard decimals (e.g., \"1.5\").\n * @property {string} symbol The symbol of the native token (e.g., \"ETH\").\n */\nexport interface NativeBalanceResult {\n value: string;\n symbol: string;\n}\n\n// Type for the balance state within the hook (the fetched data or null).\ntype NativeBalanceState = NativeBalanceResult | null;\n\n// Type for the local cache: \"walletAddress-chainId\" -> { value, symbol }.\ntype BalanceCache = Record<string, NativeBalanceResult>;\n\n/**\n * @interface NativeBalanceData\n * The object returned by the useWalletNativeBalance hook.\n * @property {NativeBalanceState} balance The native token balance and symbol, or null.\n * @property {boolean} isLoading True while the balance is being fetched for the current wallet/chain combination.\n * @property {() => void} refetch Function to manually trigger a balance refresh.\n */\ninterface NativeBalanceData {\n balance: NativeBalanceState;\n isLoading: boolean;\n refetch: () => void;\n}\n\n/**\n * Custom hook to fetch the native token balance for the currently connected wallet\n * on the active chain. It includes a local cache layer to prevent redundant network calls\n * when switching between components or on re-renders for the same wallet/chain.\n *\n * @returns {NativeBalanceData} An object containing the balance data and loading state.\n *\n * @example\n * ```typescript\n * import { useWalletNativeBalance } from './useWalletNativeBalance';\n *\n * function NativeTokenDisplay() {\n * const { balance, isLoading, refetch } = useWalletNativeBalance();\n *\n * if (isLoading) {\n * return <p>Loading balance...</p>;\n * }\n *\n * // Display the formatted balance and symbol\n * return (\n * <div>\n * <p>Balance: {balance ? `${balance.value} ${balance.symbol}` : '0.00'}</p>\n * <button onClick={refetch}>Refresh</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useWalletNativeBalance({ store }: Pick<NovaConnectProviderProps, 'store'>): NativeBalanceData {\n // --- 1. STATE & CACHE SETUP ---\n\n // Local cache storage. Keys combine wallet address and chain ID.\n const [balanceCache, setBalanceCache] = useState<BalanceCache>({});\n\n // Local loading state, managed alongside the cache check.\n const [isLoading, setIsLoading] = useState<boolean>(false);\n\n // Track the current fetch operation to prevent race conditions\n const fetchOperationRef = useRef<string | null>(null);\n\n // Store state selectors - memoized for performance\n const wallet = store.getState().activeWallet;\n const getAdapter = store.getState().getAdapter;\n\n // --- 2. COMPUTED INPUTS ---\n\n const walletAddress = wallet?.address;\n const currentChainId = wallet?.chainId;\n\n // Create the unique key for cache lookups: \"address-chainId\".\n const cacheKey = useMemo(() => {\n return walletAddress && currentChainId ? `${walletAddress}-${currentChainId}` : null;\n }, [walletAddress, currentChainId]);\n\n // Find the actual adapter object from the adapter map.\n const foundAdapter = useMemo(() => {\n if (!wallet?.walletType) return null;\n return getAdapter(getAdapterFromWalletType(wallet.walletType));\n }, [getAdapter, wallet?.walletType]);\n\n // Check if the adapter has balance functionality\n const hasBalanceResolver = useMemo(() => {\n return foundAdapter && 'getBalance' in foundAdapter && typeof foundAdapter.getBalance === 'function';\n }, [foundAdapter]);\n\n // --- 3. BALANCE FETCHING LOGIC ---\n\n const fetchBalance = useCallback(\n async (forceRefresh = false) => {\n // Exit early if essential data is missing (not connected).\n if (!walletAddress || !foundAdapter || !currentChainId || !cacheKey || !hasBalanceResolver) {\n setIsLoading(false);\n return;\n }\n\n // Set the current operation ID to prevent race conditions\n const operationId = `${cacheKey}-${Date.now()}`;\n fetchOperationRef.current = operationId;\n\n // Check cache unless forcing a refresh\n if (!forceRefresh) {\n const cachedBalance = balanceCache[cacheKey];\n if (cachedBalance) {\n setIsLoading(false);\n return;\n }\n }\n\n setIsLoading(true);\n\n try {\n // Call the adapter's getBalance method\n const balanceResult: NativeBalanceResult = await foundAdapter.getBalance(walletAddress, currentChainId);\n\n // Only update if this operation is still the latest one\n if (fetchOperationRef.current === operationId) {\n setBalanceCache((prevCache) => ({\n ...prevCache,\n [cacheKey]: balanceResult,\n }));\n }\n } catch (error) {\n console.error(`Failed to fetch native balance for ${cacheKey}:`, error);\n\n // Optionally clear cache entry on error (if you want to retry on next call)\n if (forceRefresh && fetchOperationRef.current === operationId) {\n setBalanceCache((prevCache) => {\n const newCache = { ...prevCache };\n delete newCache[cacheKey];\n return newCache;\n });\n }\n } finally {\n // Only update loading state if this operation is still current\n if (fetchOperationRef.current === operationId) {\n setIsLoading(false);\n }\n }\n },\n [walletAddress, foundAdapter, currentChainId, cacheKey, hasBalanceResolver, balanceCache],\n );\n\n // Memoized refetch function that forces a refresh\n const refetch = useCallback(() => {\n fetchBalance(true);\n }, [fetchBalance]);\n\n // --- 4. EFFECT FOR INITIAL FETCH ---\n\n useEffect(() => {\n // Only fetch if we have all required data and no cached result\n if (cacheKey && hasBalanceResolver && !balanceCache[cacheKey]) {\n fetchBalance(false);\n } else if (!cacheKey || !hasBalanceResolver) {\n // Reset loading state if we can't fetch\n setIsLoading(false);\n }\n }, [cacheKey, hasBalanceResolver, balanceCache, fetchBalance]);\n\n // --- 5. CLEANUP EFFECT ---\n\n useEffect(() => {\n return () => {\n // Cancel any ongoing operations when component unmounts\n fetchOperationRef.current = null;\n };\n }, []);\n\n // --- 6. RETURNED DATA ---\n\n // The definitive balance is always derived from the cache based on the current key.\n const balance: NativeBalanceState = useMemo(() => {\n return cacheKey ? balanceCache[cacheKey] || null : null;\n }, [cacheKey, balanceCache]);\n\n // Return the fetched balance data and the loading status.\n return {\n balance, // { value: \"1.5\", symbol: \"ETH\" } or null\n isLoading,\n refetch,\n };\n}\n"]}
|