Wallet state with useWallet()
The useWallet()
hook provides a simple interface for managing a wallet instance in your React application. It exposes the current wallet, allows you to initialize one from multiple sources, and cleanly separates logic using React context.
Quick setup
Wrap your app (or a subtree) with the <WalletContext>
provider:
import { WalletContext } from 'chaingate'
function App() {
return (
<WalletContext>
<YourComponent />
</WalletContext>
)
}
Then use the hook in any child component:
import { useWallet } from 'chaingate'
const { wallet, initializeWallet, closeWallet } = useWallet()
What it gives you
wallet
: the currently loaded wallet (ornull
if none)initializeWallet
: a set of methods to load or create a walletcloseWallet()
: removes the current wallet from context
initializeWallet methods
All methods are async and automatically store the resulting wallet in context:
-
create({ phrase?, seed?, privateKey?, ... })
— Generates a new mnemonic phrase and wallet. Supports encryption and optional customization of language and word count. -
fromPrivateKey({ privateKey })
— Loads a wallet directly from a private key string or buffer. Useful for importing low-level credentials or legacy keys. -
fromSeed({ seed })
— Restores a wallet from a raw seed buffer or hex string. Recommended for advanced deterministic workflows. -
fromPhrase({ phrase })
— Restores a wallet from a word phrase. Also supports optional encryption or warnings for unencrypted usage. -
fromKeystore({ keystoreJson, password })
— Decrypts a Web3 or legacy keystore file and loads the appropriate wallet type (private key or phrase). -
deserialize({ data })
— Reconstructs a wallet from serialized JSON previously saved with.serialize()
. Prompts for password if encrypted.
Validation helpers
These methods are also available to check user input before initializing:
checkPhrase(phrase)
checkSeed(seed)
checkPrivateKey(privateKey)
checkKeystore(keystore)
checkSerialized(serializedData)
Error handling
If you use useWallet()
outside of a <WalletContext>
, it will throw an error.
Error: useWallet must be used within <WalletContext>
Make sure your component is inside the provider tree.
Key points
- No need to pass wallet instances manually
- One global wallet per context
- Easy to reset with
closeWallet()
- Compatible with all wallet types (seed, phrase, key, keystore, serialized)