Class KleverProvider

    Klever blockchain provider with built-in caching and retry capabilities

    // Default mainnet
    const provider = new KleverProvider()

    // Named network (simple)
    const provider = new KleverProvider('testnet')
    const provider = new KleverProvider('mainnet')

    // Named network (config object)
    const provider = new KleverProvider({ network: 'testnet' })

    // Custom network (shorthand)
    const provider = new KleverProvider({
    url: 'https://custom-node.com',
    chainId: '100'
    })

    // Custom network (full)
    const provider = new KleverProvider({
    network: createCustomNetwork({
    api: 'https://api.custom.com',
    node: 'https://node.custom.com',
    chainId: '100'
    })
    })

    // Advanced usage with caching and retry
    const provider = new KleverProvider({
    network: 'mainnet',
    cache: { ttl: 15000, maxSize: 100 },
    retry: { maxRetries: 3, backoff: 'exponential' },
    debug: true
    })
    Implements
    Index

    Constructors

    Properties

    apiClient: HttpClient
    cache?: SimpleCache<unknown>
    debug: boolean
    network: Network
    nodeClient: HttpClient

    Methods

    • Execute multiple requests in parallel Useful for batching multiple API calls for better performance

      Type Parameters

      • T

      Parameters

      • requests: (() => Promise<T>)[]

        Array of request functions to execute

      Returns Promise<T[]>

      Array of results in the same order as requests

      const [account1, account2, balance] = await provider.batch([
      () => provider.getAccount('klv1...'),
      () => provider.getAccount('klv1xxx...'),
      () => provider.getBalance('klv1...')
      ])
    • Broadcasts a single signed transaction to the network

      Parameters

      • tx: unknown

        The signed transaction data

      Returns Promise<IBroadcastResult>

      Broadcast result with transaction hash

      const result = await provider.broadcastTransaction(signedTx)
      console.log(result.hash) // Transaction hash
    • Broadcasts multiple signed transactions to the network in a single batch

      Parameters

      • txs: unknown[]

        Array of signed transaction data

      Returns Promise<IBulkBroadcastResult>

      Broadcast result with array of transaction hashes

      const result = await provider.broadcastTransactions([tx1, tx2, tx3])
      console.log(result.hashes) // ['hash1', 'hash2', 'hash3']
    • Build transaction using node endpoint Node will handle nonce fetching (if missing), fee calculation, and proto encoding

      This method provides server-side transaction building where the node does the heavy lifting:

      • Fetches nonce if not provided
      • Calculates kAppFee and bandwidthFee
      • Encodes transaction to proto format
      • Returns proto transaction object and transaction hash

      Parameters

      Returns Promise<BuildTransactionResponse>

      Proto transaction object and transaction hash

      const request = {
      sender: 'klv1...',
      contracts: [{
      type: TXType.Transfer,
      parameter: { receiver: 'klv1...', amount: 1000000n, kda: 'KLV' }
      }]
      }
      const tx = await provider.buildTransaction(request)
      // tx.result contains proto transaction object (ITransaction)
      // tx.txHash contains the transaction hash
    • Calls a contract method (generic API call)

      TODO: Implementation pending - generic contract calls not yet supported

      This is a low-level method for making arbitrary contract API calls. For standard contract queries, use queryContract() instead.

      Type Parameters

      • T = unknown

      Parameters

      • _endpoint: string

        The API endpoint for the contract call

      • Optional_params: Record<string, unknown>

        The parameters for the contract call

      Returns Promise<T>

      The result of the contract call

      // Future usage (not yet implemented)
      const result = await provider.call<ContractData>('/contract/endpoint', {
      param1: 'value1',
      param2: 123
      })
    • Subscribe to provider events

      Opens a WebSocket connection to the network's ws URL. If WebSocket is unavailable in the current runtime, or if the network has no ws URL configured, the provider automatically falls back to polling the REST API for new blocks every 3 seconds.

      Safe to call multiple times — subsequent calls while already connected are no-ops. To reconnect, call disconnect() first.

      Returns void

      const provider = new KleverProvider('mainnet')
      provider.on('block', ({ blockNumber }) => console.log('New block:', blockNumber))
      provider.connect()
    • Stop real-time event subscription and release all associated resources (WebSocket, polling timers).

      After calling disconnect() you can call connect() again to re-establish the connection.

      Returns void

      provider.disconnect()
      
    • Estimates the fee for a transaction

      TODO: Implementation pending - currently returns zero fees

      This method will calculate the expected fees for a transaction including:

      • kAppFee: Application-specific fee
      • bandwidthFee: Network bandwidth cost
      • gasEstimated: Estimated gas for smart contract execution

      Parameters

      • _tx: unknown

        The transaction request to estimate fees for

      Returns Promise<IFeesResponse>

      The estimated fee breakdown

      // Future usage (not yet implemented)
      const fees = await provider.estimateFee({
      sender: 'klv1...',
      contracts: [{
      type: TXType.Transfer,
      parameter: { receiver: 'klv1...', amount: 1000000n }
      }]
      })
      console.log('Estimated kAppFee:', fees.kAppFee)
      console.log('Estimated bandwidthFee:', fees.bandwidthFee)
    • Retrieves account information from the blockchain

      Parameters

      • address: KleverAddress

        The Klever address to query

      • Optionaloptions: { skipCache?: boolean }

        Additional options

      Returns Promise<IAccount>

      Account information including balance and assets

      If the address is invalid

      const account = await provider.getAccount('klv1...')
      console.log('Balance:', account.balance)
      console.log('Assets:', account.assets)
    • Get balance for a specific token

      Parameters

      • address: KleverAddress

        Klever address

      • token: string = 'KLV'

        Token identifier (e.g., 'KLV', 'KDA-ABC123')

      Returns Promise<bigint>

      Balance as bigint

      const balance = await provider.getBalance('klv1...', 'KLV')
      console.log(`Balance: ${balance}`)
    • Retrieves transaction information by hash

      Parameters

      • hash: string | TransactionHash

        The transaction hash (as TransactionHash branded type or string)

      Returns Promise<ITransactionResponse | null>

      Transaction details including receipts, or null if not found

      If there's a network error

      const tx = await provider.getTransaction('0x123...')
      if (tx) {
      console.log('Status:', tx.status)
      console.log('Block:', tx.blockNum)
      console.log('From:', tx.sender)
      console.log('Receipts:', tx.receipts)
      }
    • Retrieves transaction receipt(s) by hash

      Receipts contain detailed information about what happened during transaction execution, including transfers, freezes, claims, and other operations.

      Parameters

      • hash: string | TransactionHash

        The transaction hash (as TransactionHash branded type or string)

      Returns Promise<IReceipt[] | null>

      Array of receipts or null if transaction not found

      // Get receipts after transaction is mined
      const receipts = await provider.getTransactionReceipt(txHash)
      if (receipts) {
      console.log(`Transaction has ${receipts.length} receipt(s)`)
      receipts.forEach(receipt => {
      console.log(`Type: ${receipt.typeString}, Asset: ${receipt.assetId}`)
      })
      }

      // Parse receipts with type-safe parsers
      import { parseReceipt } from '@klever/connect-provider'
      const tx = await provider.getTransaction(txHash)
      if (tx) {
      const freezeData = parseReceipt.freeze(tx)
      console.log(`Bucket ID: ${freezeData.bucketId}`)
      }
    • Get the full URL for viewing a transaction in the explorer

      Parameters

      • txHash: string | TransactionHash

        The transaction hash (as TransactionHash branded type or string)

      Returns string

      The full URL to view the transaction

      const txUrl = provider.getTransactionUrl('0x123...')
      console.log(txUrl) // https://kleverscan.org/transaction/0x123...
    • Remove a previously registered listener.

      Passing a listener reference that was never registered is a no-op.

      Type Parameters

      • K extends keyof ProviderEventMap

      Parameters

      • event: K

        The event name

      • listener: (data: ProviderEventMap[K]) => void

        The exact callback reference that was passed to on/once

      Returns void

      const handler = ({ blockNumber }: BlockEventData) => console.log(blockNumber)
      provider.on('block', handler)
      // ... later
      provider.off('block', handler)
    • Register a persistent listener for a provider event.

      The provider emits the following typed events:

      • 'block'BlockEventData — new block produced
      • 'pending'PendingEventData — pending transaction in mempool
      • 'error'ProviderError — connection or polling error
      • 'debug'DebugEvent — internal diagnostic message
      • 'network'NetworkChangeEvent — active network changed
      • 'connect'undefined — WebSocket/polling connection established
      • 'disconnect'undefined — WebSocket/polling connection closed

      Note: You must call connect() to start receiving 'block', 'pending', 'connect', and 'disconnect' events. 'error' and 'network' events can fire without an active connection.

      Type Parameters

      • K extends keyof ProviderEventMap

      Parameters

      • event: K

        The event name (key of ProviderEventMap)

      • listener: (data: ProviderEventMap[K]) => void

        Callback receiving the typed payload

      Returns void

      provider.on('block', ({ blockNumber, hash }) => {
      console.log(`New block #${blockNumber}: ${hash}`)
      })

      provider.on('error', ({ code, message }) => {
      console.error(`Provider error [${code}]: ${message}`)
      })

      provider.connect()
    • Register a one-time listener that is automatically removed after its first invocation.

      Type Parameters

      • K extends keyof ProviderEventMap

      Parameters

      • event: K

        The event name

      • listener: (data: ProviderEventMap[K]) => void

        Callback receiving the typed payload

      Returns void

      // Wait for the first block after connecting
      provider.once('block', ({ blockNumber }) => {
      console.log('First block received:', blockNumber)
      })
      provider.connect()
    • Queries a smart contract (read-only, no gas cost)

      Contract queries are free and don't require signing or broadcasting. Use this to read contract state or call view functions.

      Parameters

      • params: IContractQueryParams

        Contract query parameters

      Returns Promise<IContractQueryResult>

      Query result with return data and status

      // Query contract balance
      const result = await provider.queryContract({
      scAddress: 'klv1contract...',
      funcName: 'getBalance',
      args: ['klv1user...']
      })

      if (result.error) {
      console.error('Query failed:', result.error)
      } else {
      console.log('Return data:', result.data?.returnData)
      console.log('Gas remaining:', result.data?.gasRemaining)
      }
    • Remove all listeners for a specific event, or every listener across all events when called without arguments.

      Type Parameters

      • K extends keyof ProviderEventMap

      Parameters

      • Optionalevent: K

        Optional event name. Omit to clear all events.

      Returns void

      // Remove all 'block' listeners
      provider.removeAllListeners('block')

      // Remove every listener on the provider
      provider.removeAllListeners()
    • Requests test KLV from faucet (testnet/devnet only)

      Parameters

      • address: KleverAddress

        The address to send test KLV to

      • Optionalamount: bigint

        Optional amount to request (in smallest unit)

      Returns Promise<IFaucetResult>

      Faucet result with transaction hash and status

      If address is invalid or network is mainnet

      // Request test KLV on testnet
      const provider = new KleverProvider('testnet')
      const result = await provider.requestTestKLV('klv1...')
      console.log('Faucet TX:', result.txHash)
      console.log('Status:', result.status)

      // Wait for confirmation
      await provider.waitForTransaction(result.txHash)
      const balance = await provider.getBalance('klv1...')
      console.log('New balance:', balance)
    • Sends a single raw transaction to the network

      Parameters

      • signedTx: unknown

        Signed transaction data (hex string, JSON string, Uint8Array, or Transaction object)

      Returns Promise<TransactionHash>

      The transaction hash

      If the transaction data is invalid, broadcast fails, or no hash is returned

      try {
      const hash = await provider.sendRawTransaction(signedTxHex)
      console.log(hash) // '0x123...'
      } catch (error) {
      console.error('Broadcast failed:', error.message)
      }
    • Sends multiple raw transactions to the network in a single batch

      Parameters

      • signedTxs: unknown[]

        Array of signed transaction data (hex strings, JSON strings, Uint8Arrays, or Transaction objects)

      Returns Promise<TransactionHash[]>

      Array of transaction hashes

      If any transaction data is invalid, broadcast fails, or no hashes are returned

      try {
      const hashes = await provider.sendRawTransactions([tx1Hex, tx2Hex, tx3Hex])
      console.log(hashes) // ['0x123...', '0x456...', '0x789...']
      } catch (error) {
      console.error('Broadcast failed:', error.message)
      }
    • Waits for a transaction to be mined and confirmed

      Parameters

      • hash: string | TransactionHash

        The transaction hash (as TransactionHash branded type or string)

      • Optionalconfirmations: number

        Number of confirmations to wait for (default: 1)

      • OptionalonProgress: (
            status: "pending" | "failed" | "confirming" | "timeout",
            data: {
                attempts: number;
                confirmations?: number;
                maxAttempts: number;
                required?: number;
                transaction?: ITransactionResponse;
            },
        ) => void

        Optional callback for progress updates

      Returns Promise<ITransactionResponse | null>

      The transaction or null if not found/timeout

      // Basic usage
      const tx = await provider.waitForTransaction(hash)

      // With progress callback for UI updates
      const tx = await provider.waitForTransaction(hash, 3, (status, data) => {
      if (status === 'pending') {
      console.log(`Attempt ${data.attempts}/${data.maxAttempts}`)
      } else if (status === 'confirming') {
      console.log(`Confirmations: ${data.confirmations}/${data.required}`)
      }
      })