LocalWalletNode
Generate Local Wallets in Node.js backends, CLIs and scripts.
This is very useful for situations where you need a wallet for your backend services, scripts or CLI.
After generating wallets this way, you can persist it in different ways. For example, you can save it to a file, or store it in a database.
import { ThirdwebSDK } from "@thirdweb-dev/sdk";import { LocalWalletNode } from "@thirdweb-dev/wallets/evm/wallets/local-wallet-node"; // wallet data will be saved in 'wallet.json' by default// you can also pass a different file path by specifying 'storageJsonFile' in the constructorconst wallet = new LocalWalletNode(); // generate a random walletawait wallet.generate(); // connect walletawait wallet.connect(); // at any point, you can save the wallet to persistent storageawait wallet.save(config);// and load it back upawait wallet.load(config); // you can also export the wallet out to send somewhere elseconst exportedWallet = await wallet.export(config);// and import it back inawait wallet.import(exportedWallet, config); // You can then use this wallet to perform transactions via the SDKconst sdk = await ThirdwebSDK.fromWallet(wallet, "goerli");
Local Wallet Backup
Local wallets can be persisted in a file, database, or backed up to another cloud provider. Currently 3 formats are supported:
encryptedJSON
- a standard format for encrypted wallets, this requires a password to encrypt/decrypt the wallet. Recommended for safe backups.privateKey
- the raw private key. This can be stored encrypted or un-encrypted. If not encrypted, make sure you store it somewhere safe.mnemonic
- the raw seed phrase. This can be stored encrypted or un-encrypted. If not encrypted, make sure you store it somewhere safe.
We provide encryption capabilities out of the box, but you can customize the type of encryption, and also turn it off completely.
The type of storage can also be overridden, allowing you to store wallets anywhere you want, including remote locations.
By default, the local wallet will be saved in a wallet.json
file at the root of your project. The path to the file can be customized by passing a storageJsonFile
option to the constructor.
Customizing where the wallet data is persisted only requires implementing a simple interface. Here's an example of a Local Wallet with custom storage:
class MyStorage implements AsyncStorage { getItem(key: string): Promise<string | null> { ... } setItem(key: string, value: string): Promise<void> { ... } removeItem(key: string): Promise<void> { ... }} const wallet = new LocalWalletNode({ storage: new MyStorage(),})
You can implement this any way you like, file persistance, remote cloud storage, etc.
Encryption examples
Here's some examples of different encryption configurations:
Save an encrypted privateKey with default encryption a password as the encryption key:
localWallet.save({ strategy: "privateKey", encryption: { password: "your-encryption-password", // uses default encryption },});
Import a raw private key or mnemonic (seed phrase) with no encryption:
// privateKeylocalWallet.import({ privateKey: "your-raw-privateKey", encryption: false, // no encryption}); // mnemoniclocalWallet.import({ mnemonic: "your-raw-mnemonic", encryption: false, // no encryption});
Save an encrypted mnemonic with a custom encryption:
// privateKeylocalWallet.save({ strategy: "mnemonic", encryption: { encrypt: (message: string, password: string) => { return yourCustomEncryption(message, password); }, password: "your-encryption-password", },});
function constructor( options?: { analytics?: "enabled" | "disabled"; chains?: Array<Chain>; clientId?: string; walletId?: string;
Wallet options to initialize the LocalWalletNode
let options: { analytics?: "enabled" | "disabled"; chains?: Array<Chain>; clientId?: string; walletId?: string;
LocalWallet.addListener
function addListener( event: T, fn: ( ) => void, context?: any,): this;
let fn: () => void;
LocalWallet.autoConnect
auto-connect the wallet if possible
function autoConnect(connectOptions?: { chainId?: number;}): Promise<string>;
LocalWallet.connect
Connect wallet
function connect(connectOptions?: { chainId?: number;}): Promise<string>;
LocalWallet.deleteSaved
Delete the saved wallet from storage. This action is irreversible, use with caution.
await wallet.deleteSaved();
function deleteSaved(): Promise<void>;
LocalWallet.disconnect
Disconnect the wallet
function disconnect(): Promise<void>;
LocalWallet.emit
Calls each of the listeners registered for a given event.
function emit( event: T,): boolean;
LocalWallet.eventNames
Return an array listing the events for which the emitter has registered listeners.
LocalWallet.export
Encrypts the wallet with a password in various formats and return it.
const data = await wallet.export({ strategy: "encryptedJson", password: "password",});
The options
object must be of type LocalWalletExportOptions
. It takes a strategy
and other properties depending on the strategy.
strategy - "encryptedJson"
Export wallet in encryptedJson format. The options
object takes the following properties:
strategy
- must be "encryptedJson"password
- the password to encrypt the wallet data
strategy - "privateKey"
Encrypt the private key of the wallet. The options
object takes the following properties:
strategy
- must be "privateKey"encryption
- encryption object of typeEncryptOptions
to encrypt the private key. It takes apassword
property to encrypt the private key and an optionalencrypt
function to encrypt the private key. Ifencrypt
function is not provided, it uses the default encryption.
strategy - "mnemonic"
Encrypt the mnemonic (seed phrase) of the wallet. The options
object takes the following properties:
strategy
- must be "mnemonic"encryption
- encryption object of typeEncryptOptions
to encrypt the mnemonic. It takes apassword
property to encrypt the mnemonic and an optionalencrypt
function to encrypt the mnemonic. Ifencrypt
function is not provided, it uses the default encryption.
LocalWallet.generate
Creates a new random wallet and returns the wallet address.
const address = await wallet.generate();
function generate(): Promise<string>;
LocalWallet.getAddress
Returns the account address of the connected wallet
function getAddress(): Promise<string>;
LocalWallet.getBalance
Returns the balance of the connected wallet for the specified token address. If no token address is specified, it returns the balance of the native token
function getBalance( tokenAddress: string,): Promise<{ decimals: number; displayValue: string; name: string; symbol: string; value: BigNumber;}>;
LocalWallet.getChainId
Returns the chain id of the network that the wallet is connected to
function getChainId(): Promise<number>;
LocalWallet.getPersonalWallet
If the wallet uses another "personal wallet" under the hood, return it
This is only useful for wallets like Safe or Smart Wallet uses a "personal wallet" under the hood to sign transactions. This method returns that wallet
LocalWallet.getSavedData
Get the saved wallet data from storage
const someStorage = { getItem: (key) => { // Implement your own storage logic here }, removeItem: (key) => { // Implement your own storage logic here }, setItem: (key, value) => { // Implement your own storage logic here },}; wallet.getSaved(someStorage);
function getSavedData(
Promise
which resolves to a WalletData
object containing the wallet data. It returns null
if no wallet data is found in storage.
{ address: string; strategy: "mnemonic" | "privateKey" | "encryptedJson"; data: string; isEncrypted: boolean;}
LocalWallet.getSigner
Get ethers Signer object of the connected wallet
function getSigner(): Promise<Signer>;
LocalWallet.import
Create local wallet by importing a private key, mnemonic or encrypted JSON.
const address = await localWallet.import({ privateKey: "...", encryption: false,});
The options
object must be of type LocalWalletImportOptions
which can have either privateKey
, mnemonic
or encryptedJson
as a property.
They all can be encrypted or un-encrypted. If encrypted, the encryption
property must be provided with password
property to decrypt the data.
privateKey
The Private Key of the wallet.
mnemonic
The mnemonic (seed phrase) of the wallet.
encryptedJson
The encrypted JSON of the wallet.
encryption
This is only required if the given privateKey
, mnemonic
or encryptedJson
is encrypted.
The encryption
object of type DecryptOptions
can be provided to decrypt the data. It is an object with the following properties:
password
The password to decrypt the data.
decrypt
A custom decrypt function that takes the encrypted data and password as arguments and returns the decrypted data.
LocalWallet.isSaved
Check if the wallet data is saved in storage.
function isSaved(): Promise<boolean>;
LocalWallet.listenerCount
Return the number of listeners listening to a given event.
LocalWallet.listeners
Return the listeners registered for a given event.
function listeners( event: T,): Array< ( ) => void>;
let returnType: Array< ( ) => void>;
LocalWallet.load
Initialize the wallet from saved data on storage
await wallet.load({ strategy: "encryptedJson", password: "your-password",});
The options
object must be of type LocalWalletLoadOptions
which contains a strategy
property and other properties depending on the strategy.
strategy "encryptedJson"
Initialize the wallet from encrypted JSON. The options
object takes the following properties:
strategy
- must be "encryptedJson"password
- the password to decrypt the encrypted JSONstorage
- optional storage to get the wallet data from. Must be of typeAsyncStorage
strategy "privateKey"
Initialize the wallet from a private key. The options
object takes the following properties:
strategy
- must be "privateKey"encryption
- optional encryption object of typeDecryptOptions
to decrypt the private key. This is only required if the private key is encrypted.storage
- optional storage to get the wallet data from. Must be of typeAsyncStorage
strategy "mnemonic"
Initialize the wallet from a mnemonic (seed phrase). The options
object takes the following properties:
strategy
- must be "mnemonic"encryption
- optional encryption object of typeDecryptOptions
to decrypt the mnemonic. This is only required if the mnemonic is encrypted.storage
- optional storage to get the wallet data from. Must be of typeAsyncStorage
LocalWallet.loadOrCreate
Load the saved wallet data from storage, if it exists, or generate a new one and save it.
wallet.loadOrCreate({ strategy: "encryptedJson", password: password,});
function loadOrCreate(): Promise<void>;
The options
object must be of type LocalWalletLoadOrCreateOptions
. It takes a strategy
property and other properties depending on the strategy.
strategy "encryptedJson"
Load the wallet from encrypted JSON. The options
object takes the following properties:
strategy
- must be "encryptedJson"password
- the password to decrypt the encrypted JSONstorage
- optional storage to get the wallet data from. Must be of typeAsyncStorage
strategy "privateKey"
Load the wallet from a private key. The options
object takes the following properties:
strategy
- must be "privateKey"encryption
- optional encryption object of typeDecryptOptions
to decrypt the private key. This is only required if the saved private key is encrypted.
LocalWallet.off
function off( event: T, fn?: ( ) => void, context?: any, once?: boolean,): this;
let fn: () => void;
LocalWallet.on
Add a listener for a given event.
function on( event: T, fn: ( ) => void, context?: any,): this;
let fn: () => void;
LocalWallet.once
Add a one-time listener for a given event.
function once( event: T, fn: ( ) => void, context?: any,): this;
let fn: () => void;
LocalWallet.removeListener
Remove the listeners of a given event.
function removeListener( event: T, fn?: ( ) => void, context?: any, once?: boolean,): this;
let fn: () => void;
LocalWallet.save
Save the wallet data to storage
wallet.save({ strategy: "encryptedJson", password: "password",});
The options
object must be of type LocalWalletSaveOptions
. It takes a strategy
property and other properties depending on the strategy.
strategy "encryptedJson"
Save the wallet data as encrypted JSON. The options
object takes the following properties:
strategy
- must be "encryptedJson"password
- the password to encrypt the wallet datastorage
- optional storage to save the wallet data to. Must be of typeAsyncStorage
strategy "privateKey"
Save the wallet data as a private key. The options
object takes the following properties:
strategy
- must be "privateKey"encryption
- optional encryption object of typeEncryptOptions
to encrypt the private key. This is only required if you want to encrypt the private key.storage
- optional storage to save the wallet data to. Must be of typeAsyncStorage
strategy "mnemonic"
Save the wallet data as a mnemonic (seed phrase). The options
object takes the following properties:
strategy
- must be "mnemonic"encryption
- optional encryption object of typeEncryptOptions
to encrypt the mnemonic. This is only required if you want to encrypt the mnemonic.storage
- optional storage to save the wallet data to. Must be of typeAsyncStorage
LocalWallet.signMessage
Sign a message with the connected wallet and return the signature
function signMessage(message: string | Bytes): Promise<string>;
LocalWallet.switchChain
Switch to different Network/Blockchain in the connected wallet
function switchChain(chainId: number): Promise<void>;
LocalWallet.transfer
Transfers some amount of tokens to the specified address
function transfer( to: string, amount: string | number, currencyAddress: string,): Promise<Omit<TransactionResultWithMetadata<unknown>, "data">>;
LocalWallet.updateChains
Update the chains supported by the wallet. This is useful if wallet was initialized with some chains and this needs to be updated without re-initializing the wallet
function updateChains(chains: Array<Chain>): Promise<void>;
LocalWallet.verifySignature
Verify the signature of a message. It returns true
if the signature is valid, false
otherwise
function verifySignature( message: string, signature: string, address: string, _chainId?: number,): Promise<boolean>;
let walletId: string;
let prefixed: string | boolean;