Skip to main content

Interacting with Smart Contracts Using call

The call method allows you to interact with deployed smart contracts without broadcasting a transaction. This method is useful for reading contract state or simulating transactions.


Method

call(
to: string | Address,
data: Buffer | string,
from?: Address,
height?: BigNumberish
): Promise<CallResult | ICallRequestError>;
  • Parameters:

    • to: string | Address: The address of the contract to call.
    • data: Buffer | string: The calldata to send to the contract.
    • from?: Address: (Optional) The address making the call.
    • height?: BigNumberish: (Optional) The blockchain height at which to perform the call.
  • Returns:

    • Promise<CallResult>: Contains the execution result, including any returned data or events.
    • Promise<ICallRequestError>: Contains error details if the call fails.

Object Definitions

CallResult Object
Property/MethodTypeDescription
resultBinaryReaderThe raw result of the call.
accessListIAccessListAccessed storage and contract addresses.
revertstring | undefinedThe reason for revert, if the call fails.
calldataBuffer | undefinedThe calldata used for the call.
estimatedGasbigint | undefinedEstimated gas for the call.
eventsOPNetEvent[]Events emitted during the call.
sendTransaction()FunctionSends a transaction with the current parameters.

Example Usage (Get Balance of a Public Key)

import { networks } from "@btc-vision/bitcoin";
import { getContract, IOP_20Contract, OP_20_ABI } from "opnet";

// Get the contract
const contractAddress = "bcrt1p..."; // Replace with actual contract address
const contract = getContract<IOP_20Contract>(
contractAddress,
OP_20_ABI,
provider,
networks.regtest
// Optional: Add the sender's address
// Address.fromString("your-public-key")
);

const pubKey = await provider.getPublicKeyInfo("bcrt1p..."); // Replace with the address

// Call the contract
const calldata = contract.encodeCalldata("balanceOf", [pubKey]);

try {
const callResult = await provider.call(contractAddress, calldata);

if ("error" in callResult) {
throw new Error(callResult.error);
}

console.log("Call Result:", callResult.result.toString());
console.log("Estimated Gas:", callResult.estimatedGas);
console.log("Events:", callResult.events);
} catch (error) {
console.error("Call Error:", error.error);
}

Best Practices

  • Ensure the contract address and calldata are correct before making a call.
  • Use the height parameter to simulate the call at a specific block height, if needed.
  • Handle errors gracefully using the ICallRequestError interface.

What’s Next?

After interacting with contracts using call, you can explore: