Skip to main content

Fetching the Code of a Contract

The getCode method allows you to retrieve the bytecode and metadata of a deployed contract on the OP_NET network. You can fetch the contract code by providing its address and specify whether you want only the raw bytecode or detailed contract metadata.


Method

getCode(address: string | Address, onlyBytecode?: boolean): Promise<ContractData | Buffer>;
  • Parameters:

    • address: string | Address: The address of the contract whose code you want to fetch.
    • onlyBytecode?: boolean (Optional):
      • true: Returns only the raw bytecode.
      • false or omitted: Returns comprehensive contract metadata (ContractData).
  • Returns:

    • Promise<ContractData | Buffer>:
      • ContractData: Detailed contract metadata when onlyBytecode is false.
      • Buffer: Raw bytecode when onlyBytecode is true.

Object Definitions

ContractData Object
FieldDescription
contractAddressThe contract's main address.
virtualAddressVirtual address of the contract for internal operations.
p2trAddressP2TR address of the contract.
bytecodeThe raw bytecode of the contract.
wasCompressedIndicates if the bytecode was compressed during deployment.
deployedTransactionIdThe transaction ID of the contract's deployment.
deployedTransactionHashThe hash of the transaction that deployed the contract.
deployerPubKeyThe public key of the deployer.
contractSeedThe seed used during contract deployment.
contractSaltHashThe salt hash associated with the contract.
contractDeployerThe address of the contract deployer.

Example Usage

Fetching Full Contract Metadata

import { ContractData } from "opnet";

const contractAddress = "bcrt1qexamplecontract...";
const contractData = (await provider.getCode(contractAddress)) as ContractData;

console.log("Contract Address:", contractData.contractAddress.toString());
console.log("Bytecode (Hex):", contractData.bytecode.toString("hex"));
console.log(
"Deployer Public Key:",
contractData.deployerPubKey.toString("hex")
);
console.log("Deployment Transaction ID:", contractData.deployedTransactionId);

Fetching Only the Raw Bytecode

const bytecode = (await provider.getCode(contractAddress, true)) as Buffer;

console.log("Contract Bytecode (Hex):", bytecode.toString("hex"));

Best Practices

  • Ensure the provided address corresponds to a valid deployed contract.
  • If the contract does not exist at the specified address, the method may return null or throw an error.
  • The ContractData object provides critical information for contract verification, auditing, and interaction.