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

    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
      })
    • 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<null | ITransactionResponse>

      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<null | IReceipt[]>

      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...
    • Unsubscribe from provider events

      TODO: Implementation pending - event unsubscription not yet supported

      Parameters

      • _event: ProviderEvent

        The event type to unsubscribe from

      • _listener: (...args: unknown[]) => void

        The callback function to remove

      Returns void

      // Future usage (not yet implemented)
      const listener = (block) => console.log('Block:', block.nonce)
      provider.on('block', listener)
      // Later...
      provider.off('block', listener)
    • Subscribe to provider events

      TODO: Implementation pending - event subscription not yet supported

      This method will allow subscribing to blockchain events like:

      • New blocks
      • Pending transactions
      • Account balance changes
      • Contract events

      Parameters

      • _event: ProviderEvent

        The event type to subscribe to

      • _listener: (...args: unknown[]) => void

        Callback function to handle the event

      Returns void

      // Future usage (not yet implemented)
      provider.on('block', (block) => {
      console.log('New block:', block.nonce)
      })

      provider.on('transaction', (tx) => {
      console.log('New transaction:', tx.hash)
      })
    • 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)
      }
    • 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<null | ITransactionResponse>

      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}`)
      }
      })