Class NodeWallet

    Wallet implementation for Node.js environments

    NodeWallet provides secure wallet operations in server-side Node.js applications. It uses private key-based signing and is designed for backend services, CLI tools, and automated systems.

    Security Considerations:

    • Private keys are stored in memory and should be handled with care
    • Use environment variables or secure key management systems for production
    • Never expose private keys in logs, error messages, or client-side code
    • Consider using the disconnect(true) option to clear keys from memory when done

    Environment:

    • Node.js only - will throw error if used in browser environments
    • Use BrowserWallet for browser/dApp applications
    import { KleverProvider } from '@klever/connect-provider'
    import { NodeWallet } from '@klever/connect-wallet'

    // Create wallet with private key
    const provider = new KleverProvider({ network: 'mainnet' })
    const wallet = new NodeWallet(provider, process.env.PRIVATE_KEY)

    // Connect and use
    await wallet.connect()
    console.log('Address:', wallet.address)

    // Send a transaction
    const result = await wallet.transfer({
    receiver: 'klv1...',
    amount: 1000000, // 1 KLV (6 decimals)
    })
    console.log('Transaction hash:', result.hash)

    // Disconnect and clear private key from memory (recommended for security)
    await wallet.disconnect(true)
    // Generate a new random wallet
    const newWallet = await NodeWallet.generate(provider)
    await newWallet.connect()
    console.log('New address:', newWallet.address)
    Hierarchy

    Constructors

    Properties

    _address: string = ''
    _connected: boolean = false
    _events: Map<WalletEvent, Set<WalletEventHandler>> = ...
    _provider: IProvider
    _publicKey: string = ''

    Accessors

    Methods

    • Connect the wallet

      Derives the public key and address from the private key and marks the wallet as connected. This operation is performed locally without any network calls.

      Returns Promise<void>

      If no private key was provided during construction or via setPrivateKey()

      If the generated address is invalid

      connect - Emits when successfully connected with { address: string }

      const wallet = new NodeWallet(provider, privateKey)
      await wallet.connect()
      console.log('Connected:', wallet.address)
    • Disconnect from the wallet

      Clears the connection state and optionally removes the private key from memory.

      Security Note:

      • By default (clearPrivateKey=false), the private key remains in memory for quick reconnection
      • For enhanced security, set clearPrivateKey=true to completely remove the key from memory
      • After clearing the private key, you must create a new wallet instance to reconnect

      Parameters

      • clearPrivateKey: boolean = false

        Whether to clear the private key from memory (default: false) - false: Keep key in memory, can reconnect with connect() - true: Remove key from memory, requires new wallet instance

      Returns Promise<void>

      disconnect - Emits when disconnected

      // Disconnect but keep key for reconnection
      await wallet.disconnect()
      await wallet.connect() // Works - key still in memory

      // Disconnect and clear key (recommended for security)
      await wallet.disconnect(true)
      await wallet.connect() // Throws error - key cleared
    • Register an event handler

      Parameters

      • event: WalletEvent

        Event name ('connect', 'disconnect', 'accountChanged')

      • handler: WalletEventHandler

        Event handler function

      Returns void

    • Send a transaction with any contract type Builds, signs, and broadcasts the transaction Can be overridden by child classes (e.g., BrowserWallet uses extension)

      Parameters

      • contract: ContractRequestData

      Returns Promise<TransactionSubmitResult>

    • Set or change the private key

      Security Note: Can only be called when wallet is disconnected to prevent accidental key changes during active operations.

      Parameters

      • privateKey: string

        Private key as hex string

      Returns void

      If wallet is currently connected

      If private key format is invalid

      const wallet = new NodeWallet(provider) // No key yet
      wallet.setPrivateKey(process.env.PRIVATE_KEY)
      await wallet.connect()
    • Sign a message with the wallet's private key

      SECURITY WARNING:

      • Only sign messages from trusted sources
      • Signing malicious messages can lead to phishing attacks
      • Never sign messages that look like transactions or authorization requests
      • Verify the message content before signing

      The message is signed using the Ed25519 signature scheme. The resulting signature can be verified using the wallet's public key.

      Parameters

      • message: string | Uint8Array<ArrayBufferLike>

        Message to sign (string or raw bytes)

      Returns Promise<Signature>

      Signature object with .toHex() and .toBase64() methods

      If wallet is not connected or private key not available

      const message = "Hello, Klever!"
      const signature = await wallet.signMessage(message)

      // Get signature in different formats
      console.log('Hex:', signature.toHex())
      console.log('Base64:', signature.toBase64())

      // Verify the signature
      const isValid = await wallet.verifyMessage(message, signature)
      console.log('Valid:', isValid) // true
      // Sign raw bytes
      const data = new Uint8Array([1, 2, 3, 4])
      const signature = await wallet.signMessage(data)
    • Sign a transaction with the wallet's private key

      SECURITY WARNING:

      • Always verify transaction details before signing
      • Check recipient address, amount, and contract type
      • Signing a transaction authorizes it to be broadcasted to the blockchain
      • Signed transactions cannot be reversed once broadcasted

      The transaction is signed in-place, modifying the original transaction object with the signature. The same transaction object is returned for convenience.

      Parameters

      Returns Promise<Transaction>

      The same transaction object, now signed

      If wallet is not connected or private key not available

      import { TransactionBuilder } from '@klever/connect-transactions'

      // Build a transaction
      const builder = new TransactionBuilder(provider)
      const unsignedTx = await builder
      .transfer({ receiver: 'klv1...', amount: 1000000 })
      .sender(wallet.address)
      .build()

      // Sign it
      const signedTx = await wallet.signTransaction(unsignedTx)

      // Broadcast
      const hash = await wallet.broadcastTransaction(signedTx)
      console.log('Transaction hash:', hash)
    • Verify a message signature

      Parameters

      • message: string | Uint8Array<ArrayBufferLike>

        The message that was signed (string or bytes)

      • signature: string | Signature

        The signature to verify (Signature object, hex string, or base64 string)

      Returns Promise<boolean>

      true if signature is valid, false otherwise

      const message = "Hello, Klever!"
      const signature = await wallet.signMessage(message)

      // Verify with Signature object
      const isValid = await wallet.verifyMessage(message, signature)

      // Or verify with hex string
      const isValidHex = await wallet.verifyMessage(message, signature.toHex())

      // Or verify with base64 string
      const isValidBase64 = await wallet.verifyMessage(message, signature.toBase64())
      console.log('Signature valid:', isValid)
    • Generate a new wallet with a random private key

      Creates a new wallet instance with a cryptographically secure random private key. The wallet is ready to connect and use immediately.

      Important:

      • Save the private key securely - it cannot be recovered if lost
      • Never share the private key with anyone
      • Use environment variables or secure key management in production

      Parameters

      • provider: IProvider

        Provider instance for blockchain communication

      Returns Promise<NodeWallet>

      New NodeWallet instance with generated key pair

      import { KleverProvider } from '@klever/connect-provider'
      import { NodeWallet } from '@klever/connect-wallet'

      const provider = new KleverProvider({ network: 'testnet' })
      const wallet = await NodeWallet.generate(provider)

      await wallet.connect()
      console.log('New wallet address:', wallet.address)

      // IMPORTANT: Save the private key securely!
      // You can extract it before connecting if needed for backup
      // Generate multiple wallets for testing
      const wallets = await Promise.all([
      NodeWallet.generate(provider),
      NodeWallet.generate(provider),
      NodeWallet.generate(provider),
      ])

      for (const wallet of wallets) {
      await wallet.connect()
      console.log('Generated address:', wallet.address)
      }