@terrawallet/react 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,15 @@
1
+ Terra Wallet SDK
2
+ Copyright 2026 Terra Wallet (https://terrawallet.us)
3
+
4
+ This product includes software developed by Terra Wallet.
5
+ Official source: https://github.com/theterrawallet/terra-sdk
6
+ Developers: https://developers.terrawallet.us
7
+
8
+ "Terra Wallet", "Terra Pay", "Terra Connect", "Terra Escrow" and the Terra Wallet
9
+ logo are trademarks of Terra Wallet. The Apache License 2.0 grants no permission
10
+ to use them (section 6), except as needed to describe the origin of the software.
11
+ A modified copy must not be presented as the official Terra Wallet SDK.
12
+
13
+ Third-party software: the optional WalletConnect add-on (terra-walletconnect.*)
14
+ bundles @walletconnect/sign-client and its dependencies, which are distributed
15
+ under their own licenses, not under this one. See each bundle's sbom.cdx.json.
package/README.md CHANGED
@@ -1,5 +1,51 @@
1
1
  # @terrawallet/react
2
2
 
3
- This package name is **reserved by Terra Wallet**. Nothing is released under it yet, and this version contains no working code.
3
+ Terra Wallet for React 18 and 19: a provider, a connect button, a modal, hooks, and a wagmi connector.
4
4
 
5
- Official SDKs and tools will be announced at https://developers.terrawallet.us. Only install Terra packages linked from that site.
5
+ ```tsx
6
+ "use client";
7
+ import { TerraProvider, ConnectButton, useAccount, useSendTransaction } from "@terrawallet/react";
8
+
9
+ export function App() {
10
+ return (
11
+ <TerraProvider appName="My dApp" chains={[8453, 1]} walletConnectProjectId="<reown project id>"
12
+ theme={{ mode: "auto", accent: "#0A5BFF", radius: 14 }}>
13
+ <ConnectButton />
14
+ <Pay />
15
+ </TerraProvider>
16
+ );
17
+ }
18
+
19
+ function Pay() {
20
+ const { address, chain, isConnected } = useAccount();
21
+ const { sendTransaction, data: hash, isPending, error } = useSendTransaction();
22
+ if (!isConnected) return null;
23
+ return <button disabled={isPending} onClick={() => sendTransaction({ to: "0x...", value: 10n ** 15n })}>Send on {chain?.name}</button>;
24
+ }
25
+ ```
26
+
27
+ - `<ConnectButton/>` and `<WalletModal open onOpenChange/>` render Terra's Web Components (closed Shadow DOM), so
28
+ app CSS cannot break or restyle them. Theme with props (`theme`, `accent`, `radius`, `size`, `block`) or the
29
+ provider's `theme`.
30
+ - Hooks: `useAccount`, `useChainId`, `useConnect` (opens the modal by default; `{ modal: false }` for headless),
31
+ `useDisconnect`, `useSwitchChain`, `useSignMessage`, `useSignTypedData`, `useSendTransaction`, `useTerraModal`,
32
+ `useTerraClient`, `useTerraState`. Action hooks return `x()` (errors kept in state) and `xAsync()` (rejects).
33
+ - Server rendering is safe (Next.js App Router: the entry is marked `"use client"`).
34
+ - A secret key passed as `publishableKey` throws.
35
+
36
+ ## wagmi
37
+
38
+ ```ts
39
+ import { createConfig, http } from "wagmi";
40
+ import { base, mainnet } from "wagmi/chains";
41
+ import { terraWallet } from "@terrawallet/react/wagmi";
42
+
43
+ export const config = createConfig({
44
+ chains: [base, mainnet],
45
+ connectors: [terraWallet({ walletConnectProjectId: "<reown project id>" })],
46
+ transports: { [base.id]: http(), [mainnet.id]: http() },
47
+ });
48
+ ```
49
+
50
+ Tested against `@wagmi/core` 3.6.9 and viem 2.57 (connect, sign, switch chain, disconnect, reconnect, 4001 on
51
+ rejection). `terraWallet({ modal: false })` connects without the modal. No runtime dependency on wagmi.
@@ -0,0 +1,47 @@
1
+ /**
2
+ * <ConnectButton/> and <WalletModal/>. Both render Terra's audited Web Components (closed Shadow DOM), so the
3
+ * button and the security prompts look and behave exactly as on any other site, and app CSS cannot restyle or hide
4
+ * them. Theme them through props or <TerraProvider theme>.
5
+ */
6
+ import { type CSSProperties } from "react";
7
+ import type { ConnectResult, TerraConnect } from "@terrawallet/connect";
8
+ import { type ThemeMode } from "@terrawallet/elements";
9
+ export interface ConnectButtonProps {
10
+ /** Text when disconnected. Default "Connect Terra Wallet". */
11
+ label?: string;
12
+ theme?: ThemeMode;
13
+ /** #rgb, #rrggbb or rgb(). Text colour is picked automatically for AA contrast. */
14
+ accent?: string;
15
+ /** px (0 to 24) or "none" | "sm" | "md" | "lg". */
16
+ radius?: number | "none" | "sm" | "md" | "lg";
17
+ size?: "sm" | "md" | "lg";
18
+ /** Full width. */
19
+ block?: boolean;
20
+ className?: string;
21
+ style?: CSSProperties;
22
+ onConnect?(result: ConnectResult): void;
23
+ onDisconnect?(): void;
24
+ }
25
+ type ButtonElement = HTMLElement & {
26
+ client: TerraConnect | null;
27
+ };
28
+ export declare function ConnectButton(props: ConnectButtonProps): import("react").ReactElement<{
29
+ ref: import("react").RefObject<ButtonElement | null>;
30
+ theme: ThemeMode | undefined;
31
+ accent: string | undefined;
32
+ radius: string | undefined;
33
+ font: string | undefined;
34
+ size: "sm" | "md" | "lg" | undefined;
35
+ label: string | undefined;
36
+ block: string | undefined;
37
+ className: string | undefined;
38
+ style: CSSProperties | undefined;
39
+ suppressHydrationWarning: boolean;
40
+ }, string | import("react").JSXElementConstructor<any>>;
41
+ export interface WalletModalProps {
42
+ open: boolean;
43
+ onOpenChange?(open: boolean): void;
44
+ }
45
+ /** Controlled Terra Wallet modal. Renders nothing in place: the dialog lives in the browser's top layer. */
46
+ export declare function WalletModal({ open, onOpenChange }: WalletModalProps): null;
47
+ export {};
@@ -0,0 +1,100 @@
1
+ import { type ConnectOptions, type ConnectResult, type Hex, type SignableMessage, type TerraChain, type TerraError, type TerraState, type TransactionRequest } from "@terrawallet/connect";
2
+ /** The raw connection state. */
3
+ export declare function useTerraState(): TerraState;
4
+ export interface UseAccountResult {
5
+ address: Hex | undefined;
6
+ addresses: readonly Hex[];
7
+ chainId: number | undefined;
8
+ chain: TerraChain | undefined;
9
+ status: TerraState["status"];
10
+ connector: TerraState["connector"] | undefined;
11
+ solanaAddress: string | undefined;
12
+ isConnected: boolean;
13
+ isConnecting: boolean;
14
+ isReconnecting: boolean;
15
+ isDisconnected: boolean;
16
+ }
17
+ export declare function useAccount(): UseAccountResult;
18
+ export declare function useChainId(): number | undefined;
19
+ export interface UseConnectOptions {
20
+ /**
21
+ * true (default): open the Terra Wallet modal (extension, QR code, app deep link, install links).
22
+ * false: connect headlessly (the extension when present, else WalletConnect).
23
+ */
24
+ modal?: boolean;
25
+ }
26
+ export declare function useConnect(opts?: UseConnectOptions): {
27
+ data: ConnectResult | undefined;
28
+ error: TerraError | null;
29
+ isPending: boolean;
30
+ isSuccess: boolean;
31
+ isError: boolean;
32
+ connect: (o?: ConnectOptions | undefined) => undefined;
33
+ connectAsync: (o?: ConnectOptions | undefined) => Promise<ConnectResult>;
34
+ reset: () => void;
35
+ };
36
+ export declare function useDisconnect(): {
37
+ data: void | undefined;
38
+ error: TerraError | null;
39
+ isPending: boolean;
40
+ isSuccess: boolean;
41
+ isError: boolean;
42
+ disconnect: () => undefined;
43
+ disconnectAsync: () => Promise<void>;
44
+ reset: () => void;
45
+ };
46
+ export declare function useSwitchChain(): {
47
+ data: number | undefined;
48
+ error: TerraError | null;
49
+ isPending: boolean;
50
+ isSuccess: boolean;
51
+ isError: boolean;
52
+ switchChain: (p: {
53
+ chainId: number;
54
+ }) => undefined;
55
+ switchChainAsync: (p: {
56
+ chainId: number;
57
+ }) => Promise<number>;
58
+ chains: readonly TerraChain[];
59
+ reset: () => void;
60
+ };
61
+ export declare function useSignMessage(): {
62
+ data: `0x${string}` | undefined;
63
+ error: TerraError | null;
64
+ isPending: boolean;
65
+ isSuccess: boolean;
66
+ isError: boolean;
67
+ signMessage: (p: {
68
+ message: SignableMessage;
69
+ }) => undefined;
70
+ signMessageAsync: (p: {
71
+ message: SignableMessage;
72
+ }) => Promise<`0x${string}`>;
73
+ reset: () => void;
74
+ };
75
+ export declare function useSignTypedData(): {
76
+ data: `0x${string}` | undefined;
77
+ error: TerraError | null;
78
+ isPending: boolean;
79
+ isSuccess: boolean;
80
+ isError: boolean;
81
+ signTypedData: (typedData: object) => undefined;
82
+ signTypedDataAsync: (typedData: object) => Promise<`0x${string}`>;
83
+ reset: () => void;
84
+ };
85
+ /** `data` is the transaction hash once the wallet has sent it. */
86
+ export declare function useSendTransaction(): {
87
+ data: `0x${string}` | undefined;
88
+ error: TerraError | null;
89
+ isPending: boolean;
90
+ isSuccess: boolean;
91
+ isError: boolean;
92
+ sendTransaction: (tx: TransactionRequest) => undefined;
93
+ sendTransactionAsync: (tx: TransactionRequest) => Promise<`0x${string}`>;
94
+ reset: () => void;
95
+ };
96
+ /** Opens or closes the Terra Wallet modal (connect when disconnected, account view when connected). */
97
+ export declare function useTerraModal(): {
98
+ open: () => void;
99
+ close: () => void;
100
+ };
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @terrawallet/react: Terra Wallet for React.
3
+ *
4
+ * <TerraProvider appName="My dApp" walletConnectProjectId="...">
5
+ * <ConnectButton />
6
+ * </TerraProvider>
7
+ *
8
+ * The wagmi connector lives at "@terrawallet/react/wagmi".
9
+ */
10
+ export { TerraProvider, useTerraClient, useTerraContext, type TerraProviderProps, type TerraContextValue } from "./provider.js";
11
+ export { useAccount, useChainId, useConnect, useDisconnect, useSendTransaction, useSignMessage, useSignTypedData, useSwitchChain, useTerraModal, useTerraState, type UseAccountResult, type UseConnectOptions, } from "./hooks.js";
12
+ export { ConnectButton, WalletModal, type ConnectButtonProps, type WalletModalProps } from "./components.js";
13
+ export { TerraError, isTerraError, type TerraChain, type TerraConnect, type TerraConnectOptions, type TerraState, type Hex } from "@terrawallet/connect";
package/dist/index.js ADDED
@@ -0,0 +1,215 @@
1
+ "use client";
2
+
3
+ // src/provider.ts
4
+ import { createContext, createElement, useContext, useEffect, useMemo, useState } from "react";
5
+ import { createTerraConnect } from "@terrawallet/connect";
6
+ import { defineTerraElements, setDefaultClient } from "@terrawallet/elements";
7
+ var TerraContext = createContext(null);
8
+ function TerraProvider({ client: given, theme, children, ...options }) {
9
+ const [client] = useState(() => given ?? createTerraConnect({ deepLink: "manual", ...options }));
10
+ useEffect(() => {
11
+ setDefaultClient(client);
12
+ defineTerraElements();
13
+ }, [client]);
14
+ const value = useMemo(() => ({ client, theme }), [client, theme]);
15
+ return createElement(TerraContext.Provider, { value }, children);
16
+ }
17
+ function useTerraContext() {
18
+ const ctx = useContext(TerraContext);
19
+ if (!ctx) throw new Error("Terra hooks and components must be used inside <TerraProvider>.");
20
+ return ctx;
21
+ }
22
+ function useTerraClient() {
23
+ return useTerraContext().client;
24
+ }
25
+
26
+ // src/hooks.ts
27
+ import { useCallback, useEffect as useEffect2, useMemo as useMemo2, useRef, useState as useState2, useSyncExternalStore } from "react";
28
+ import {
29
+ INITIAL_STATE,
30
+ getChain,
31
+ toTerraError
32
+ } from "@terrawallet/connect";
33
+ import { closeWalletModal, connectWithModal, openWalletModal } from "@terrawallet/elements";
34
+ var serverSnapshot = () => INITIAL_STATE;
35
+ function useTerraState() {
36
+ const { client } = useTerraContext();
37
+ return useSyncExternalStore(client.subscribe, client.getState, serverSnapshot);
38
+ }
39
+ function useAccount() {
40
+ const { client } = useTerraContext();
41
+ const s = useTerraState();
42
+ return useMemo2(
43
+ () => ({
44
+ address: s.address ?? void 0,
45
+ addresses: s.accounts,
46
+ chainId: s.chainId ?? void 0,
47
+ chain: s.chainId ? getChain(s.chainId, client.chains) : void 0,
48
+ status: s.status,
49
+ connector: s.connector ?? void 0,
50
+ solanaAddress: s.solanaAddress ?? void 0,
51
+ isConnected: s.status === "connected",
52
+ isConnecting: s.status === "connecting",
53
+ isReconnecting: s.status === "reconnecting",
54
+ isDisconnected: s.status === "disconnected"
55
+ }),
56
+ [s, client]
57
+ );
58
+ }
59
+ function useChainId() {
60
+ return useTerraState().chainId ?? void 0;
61
+ }
62
+ function useAction(fn) {
63
+ const [st, setSt] = useState2({ data: void 0, error: null, isPending: false });
64
+ const mounted = useRef(true);
65
+ const fnRef = useRef(fn);
66
+ fnRef.current = fn;
67
+ useEffect2(() => {
68
+ mounted.current = true;
69
+ return () => {
70
+ mounted.current = false;
71
+ };
72
+ }, []);
73
+ const runAsync = useCallback(async (...args) => {
74
+ setSt((p) => ({ ...p, isPending: true, error: null }));
75
+ try {
76
+ const data = await fnRef.current(...args);
77
+ if (mounted.current) setSt({ data, error: null, isPending: false });
78
+ return data;
79
+ } catch (e) {
80
+ const error = toTerraError(e);
81
+ if (mounted.current) setSt({ data: void 0, error, isPending: false });
82
+ throw error;
83
+ }
84
+ }, []);
85
+ const run = useCallback((...args) => void runAsync(...args).catch(() => {
86
+ }), [runAsync]);
87
+ const reset = useCallback(() => setSt({ data: void 0, error: null, isPending: false }), []);
88
+ const state = { ...st, isSuccess: st.data !== void 0 && !st.error, isError: !!st.error };
89
+ return { state, run, runAsync, reset };
90
+ }
91
+ function useConnect(opts = {}) {
92
+ const { client, theme } = useTerraContext();
93
+ const useModal = opts.modal !== false;
94
+ const { state, run, runAsync, reset } = useAction(
95
+ (o) => useModal && typeof window !== "undefined" && !o?.method ? connectWithModal(client, { theme }) : client.connect(o)
96
+ );
97
+ return { connect: run, connectAsync: runAsync, reset, ...state };
98
+ }
99
+ function useDisconnect() {
100
+ const { client } = useTerraContext();
101
+ const { state, run, runAsync, reset } = useAction(() => client.disconnect());
102
+ return { disconnect: run, disconnectAsync: runAsync, reset, ...state };
103
+ }
104
+ function useSwitchChain() {
105
+ const { client } = useTerraContext();
106
+ const { state, run, runAsync, reset } = useAction((p) => client.switchChain(p.chainId));
107
+ return { switchChain: run, switchChainAsync: runAsync, chains: client.chains, reset, ...state };
108
+ }
109
+ function useSignMessage() {
110
+ const { client } = useTerraContext();
111
+ const { state, run, runAsync, reset } = useAction((p) => client.signMessage(p.message));
112
+ return { signMessage: run, signMessageAsync: runAsync, reset, ...state };
113
+ }
114
+ function useSignTypedData() {
115
+ const { client } = useTerraContext();
116
+ const { state, run, runAsync, reset } = useAction((typedData) => client.signTypedData(typedData));
117
+ return { signTypedData: run, signTypedDataAsync: runAsync, reset, ...state };
118
+ }
119
+ function useSendTransaction() {
120
+ const { client } = useTerraContext();
121
+ const { state, run, runAsync, reset } = useAction((tx) => client.sendTransaction(tx));
122
+ return { sendTransaction: run, sendTransactionAsync: runAsync, reset, ...state };
123
+ }
124
+ function useTerraModal() {
125
+ const { client, theme } = useTerraContext();
126
+ return useMemo2(
127
+ () => ({
128
+ open: () => {
129
+ openWalletModal(client, { theme });
130
+ },
131
+ close: () => closeWalletModal()
132
+ }),
133
+ [client, theme]
134
+ );
135
+ }
136
+
137
+ // src/components.ts
138
+ import { createElement as createElement2, useEffect as useEffect3, useRef as useRef2 } from "react";
139
+ import { defineTerraElements as defineTerraElements2, openWalletModal as openWalletModal2 } from "@terrawallet/elements";
140
+ function ConnectButton(props) {
141
+ const { client, theme } = useTerraContext();
142
+ const ref = useRef2(null);
143
+ const handlers = useRef2(props);
144
+ handlers.current = props;
145
+ useEffect3(() => {
146
+ const el = ref.current;
147
+ if (!el) return;
148
+ el.client = client;
149
+ defineTerraElements2();
150
+ const onConnect = (e) => handlers.current.onConnect?.(e.detail);
151
+ const onDisconnect = () => handlers.current.onDisconnect?.();
152
+ el.addEventListener("terra-connect", onConnect);
153
+ el.addEventListener("terra-disconnect", onDisconnect);
154
+ return () => {
155
+ el.removeEventListener("terra-connect", onConnect);
156
+ el.removeEventListener("terra-disconnect", onDisconnect);
157
+ };
158
+ }, [client]);
159
+ const mode = props.theme ?? theme?.mode;
160
+ const accent = props.accent ?? theme?.accent;
161
+ const radius = props.radius ?? theme?.radius;
162
+ return createElement2("terra-connect-button", {
163
+ ref,
164
+ theme: mode,
165
+ accent,
166
+ radius: radius === void 0 ? void 0 : String(radius),
167
+ font: theme?.font,
168
+ size: props.size,
169
+ label: props.label,
170
+ block: props.block ? "" : void 0,
171
+ className: props.className,
172
+ style: props.style,
173
+ suppressHydrationWarning: true
174
+ });
175
+ }
176
+ function WalletModal({ open, onOpenChange }) {
177
+ const { client, theme } = useTerraContext();
178
+ const onChange = useRef2(onOpenChange);
179
+ onChange.current = onOpenChange;
180
+ useEffect3(() => {
181
+ if (!open) return;
182
+ let active = true;
183
+ const handle = openWalletModal2(client, { theme });
184
+ void handle.closed.then(() => {
185
+ if (active) onChange.current?.(false);
186
+ });
187
+ return () => {
188
+ active = false;
189
+ handle.close();
190
+ };
191
+ }, [open, client, theme]);
192
+ return null;
193
+ }
194
+
195
+ // src/index.ts
196
+ import { TerraError, isTerraError } from "@terrawallet/connect";
197
+ export {
198
+ ConnectButton,
199
+ TerraError,
200
+ TerraProvider,
201
+ WalletModal,
202
+ isTerraError,
203
+ useAccount,
204
+ useChainId,
205
+ useConnect,
206
+ useDisconnect,
207
+ useSendTransaction,
208
+ useSignMessage,
209
+ useSignTypedData,
210
+ useSwitchChain,
211
+ useTerraClient,
212
+ useTerraContext,
213
+ useTerraModal,
214
+ useTerraState
215
+ };
@@ -0,0 +1,23 @@
1
+ import { type ReactNode } from "react";
2
+ import { type TerraConnect, type TerraConnectOptions } from "@terrawallet/connect";
3
+ import { type ThemeOptions } from "@terrawallet/elements";
4
+ export interface TerraContextValue {
5
+ client: TerraConnect;
6
+ theme: ThemeOptions | undefined;
7
+ }
8
+ export interface TerraProviderProps extends TerraConnectOptions {
9
+ /** Bring your own client (for example one shared with a wagmi connector). Read once, on mount. */
10
+ client?: TerraConnect;
11
+ /** Theme for <ConnectButton/>, <WalletModal/> and the modal opened by hooks: mode, accent, radius, font. */
12
+ theme?: ThemeOptions;
13
+ children?: ReactNode;
14
+ }
15
+ /**
16
+ * Provides one Terra Connect client to the tree. The client is created once on mount (options are read then), is
17
+ * safe during server rendering, and silently restores the previous connection in the browser. Passing a secret
18
+ * key as `publishableKey` throws.
19
+ */
20
+ export declare function TerraProvider({ client: given, theme, children, ...options }: TerraProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<TerraContextValue | null>>;
21
+ export declare function useTerraContext(): TerraContextValue;
22
+ /** The underlying Terra Connect client (for anything the hooks do not cover). */
23
+ export declare function useTerraClient(): TerraConnect;