Class Contract

    Contract class with dynamic methods

    The Contract class provides two types of interactions:

    1. Query (Readonly): Functions marked as 'readonly' in the ABI

      • No transaction created
      • No gas fees
      • Returns data immediately
      • Accessed via dynamically generated methods or call()
    2. Invoke (Mutable): Functions that modify contract state

      • Creates and signs a transaction
      • Requires gas fees
      • Returns transaction result with wait() method
      • Accessed via dynamically generated methods or invoke()
    • Interface for ABI parsing and encoding
    • ABIEncoder for parameter encoding
    • ABIDecoder for result decoding

    Indexable

    • [key: string]: unknown
    Index

    Constructors

    Properties

    address: KleverAddress
    interface: Interface
    populateTransaction: {
        [key: string]: (...args: unknown[]) => Promise<Transaction>;
    }
    provider?: Provider
    signer?: Signer

    Methods

    • Attach contract to a different address

      Creates a new Contract instance with the same ABI but pointing to a different contract address. This is useful when you have multiple instances of the same contract deployed at different addresses.

      Parameters

      Returns Contract

      New Contract instance with the same ABI but different address

      const tokenABI = [...] // ERC20-like token ABI
      const token1 = new Contract('klv1token1...', tokenABI, wallet)

      // Create a new instance pointing to a different token
      const token2 = token1.attach('klv1token2...')

      // Both use the same ABI but interact with different contracts
      const balance1 = await token1.balanceOf(address)
      const balance2 = await token2.balanceOf(address)
    • Call a contract function dynamically Useful when function name is determined at runtime

      Supports passing CallOptions as the last argument for transaction customization (value, nonce, fees, chainId, permissionId, data, etc.)

      Type Parameters

      • T = unknown

      Parameters

      • functionName: string

        The name of the function to call

      • ...args: unknown[]

        Arguments to pass to the function (last arg can be CallOptions)

      Returns Promise<T>

      // Basic call
      const result = await contract.call('transfer', toAddress, amount)

      // With CallOptions
      const result = await contract.call('transfer', toAddress, amount, {
      value: parseKLV('1'),
      nonce: 123,
      fees: { kAppFee: 100 }
      })
    • Query a contract function and return raw result (unparsed)

      This method is useful when you need access to the raw returnData from a contract query, including metadata like returnCode, returnMessage, and gas information.

      Parameters

      • functionName: string

        The name of the readonly function to query

      • ...args: unknown[]

        Arguments to pass to the function

      Returns Promise<IContractQueryResult>

      Raw query result with returnData, returnCode, returnMessage, and gas info

      Error if the function is not readonly

      Error if the provider is not available

      Error if the contract query fails

      // Query a contract and get raw results
      const result = await contract.callRaw('getBalance', address)

      console.log(result.data?.returnData) // ['AQ==', 'BQ==']
      console.log(result.data?.returnCode) // 'ok'
      console.log(result.data?.gasRemaining) // 500000n
      console.log(result.data?.returnMessage) // 'Success'
      • call for automatically decoded results
      • invoke for state-changing transactions
    • Connect contract to a different signer or provider

      Creates a new Contract instance with the same ABI and address but connected to a different signer or provider. This is useful when you want to interact with the same contract using different accounts.

      Parameters

      • signerOrProvider: Signer | Provider

        The signer or provider to connect to

      Returns Contract

      New Contract instance with the same ABI and address

      const contract = new Contract(address, abi, wallet1)

      // Switch to a different wallet
      const contract2 = contract.connect(wallet2)

      // Now transactions will be signed by wallet2
      await contract2.transfer(toAddress, amount)
    • Get unique event identifiers from transaction logs

      Parameters

      • Optionallogs: TransactionLog

        Transaction logs

      Returns string[]

      Array of unique event identifiers

    • Get all available function names

      Returns an array of all function names defined in the contract's ABI, including both readonly (query) and mutable (transaction) functions.

      Returns string[]

      Array of function names

      const functions = contract.getFunctions()
      console.log(functions) // ['transfer', 'balanceOf', 'approve', ...]

      // Iterate over all functions
      for (const funcName of contract.getFunctions()) {
      console.log(`Function: ${funcName}`)
      }
    • Check if contract has a function

      Verifies whether the contract's ABI includes a function with the specified name.

      Parameters

      • functionName: string

        The name of the function to check

      Returns boolean

      True if the function exists in the contract's ABI, false otherwise

      if (contract.hasFunction('transfer')) {
      await contract.transfer(toAddress, amount)
      }
    • Invoke a mutable contract function (state-changing transaction) This method explicitly requires the function to be mutable.

      Supports passing CallOptions as the last argument for transaction customization (value, nonce, fees, chainId, permissionId, data, etc.)

      Parameters

      • functionName: string

        The name of the mutable function to invoke

      • ...args: unknown[]

        Arguments to pass to the function (last arg can be CallOptions)

      Returns Promise<TransactionSubmitResult>

      Transaction submit result with hash and wait() method

      // Basic invocation with individual args
      const result = await contract.invoke('bet', betType, betValue)
      await result.wait() // Wait for confirmation

      // With array of args (will be spread automatically)
      const params = [betType, betValue]
      const result = await contract.invoke('bet', ...params)

      // With CallOptions (value, nonce, fees, etc.)
      const result = await contract.invoke('bet', betType, betValue, {
      value: parseKLV('10'), // Send 10 KLV with call
      nonce: 123,
      fees: { kAppFee: 100 }
      })

      // With array of args AND CallOptions
      const result = await contract.invoke('bet', ...params, {
      value: parseKLV('10')
      })
    • Parse events from transaction logs

      Parameters

      • Optionallogs: TransactionLog

        Transaction logs from a transaction response

      • Optionalfilter: ContractEventFilter

        Optional filter to apply (identifier, address, topics)

      Returns ContractEvent[]

      Array of parsed events

      // Parse all events from a transaction
      const tx = await provider.getTransaction(hash)
      const events = contract.parseEvents(tx.logs)

      // Filter events by identifier
      const betEvents = contract.parseEvents(tx.logs, {
      identifier: 'BetPlaced'
      })

      // Filter events from this contract only
      const contractEvents = contract.parseEvents(tx.logs, {
      address: contract.address
      })