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 whenonlyBytecode
isfalse
.Buffer
: Raw bytecode whenonlyBytecode
istrue
.
Object Definitions
ContractData
ObjectField | Description |
---|---|
contractAddress | The contract's main address. |
virtualAddress | Virtual address of the contract for internal operations. |
p2trAddress | P2TR address of the contract. |
bytecode | The raw bytecode of the contract. |
wasCompressed | Indicates if the bytecode was compressed during deployment. |
deployedTransactionId | The transaction ID of the contract's deployment. |
deployedTransactionHash | The hash of the transaction that deployed the contract. |
deployerPubKey | The public key of the deployer. |
contractSeed | The seed used during contract deployment. |
contractSaltHash | The salt hash associated with the contract. |
contractDeployer | The 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.