Instantiating a Smart Contract
The getContract
function is your gateway to creating and interacting with contract instances on OP_NET. By utilizing this function, you ensure that your contract instance is correctly typed and capable of interacting seamlessly with its ABI-defined methods.
Method
getContract<T extends BaseContractProperties>(
address: string | Address,
abi: BitcoinInterface | BitcoinInterfaceAbi,
provider: AbstractRpcProvider,
network: Network,
sender?: Address
): BaseContract<T> & Omit<T, keyof BaseContract<T>>;
-
Parameters:
address: string | Address
: The address of the contract to instantiate.abi: BitcoinInterface | BitcoinInterfaceAbi
: The ABI of the contract.provider: AbstractRpcProvider
: The provider instance connected to OP_NET.network: Network
: The target network for the contract.sender?: Address
: (Optional) The sender address for contract interactions.
-
Returns:
BaseContract<T>
: The contract instance with all methods, events, and properties defined in the ABI.Omit<T, keyof BaseContract<T>>
: The contract interface without the methods and events inherited from the base contract.
Example of Instantiating a Contract
Instantiating with a String Address
import { getContract, IOP_20Contract, OP_20_ABI } from "opnet";
import { networks } from "@btc-vision/bitcoin";
const op20Contract = getContract<IOP_20Contract>(
"bcrt1qexampleaddress", // Contract address as a string
OP_20_ABI, // OP_20 token contract ABI
provider, // JSONRpcProvider connected to OP_NET
networks.regtest // Target network
// Optional: Add the sender's address
// Address.fromString("your-public-key")
);
Instantiating with an Address
Object
const op20Contract = getContract<IOP_20Contract>(
contractAddressObject, // Address object resolved via getPublicKeyInfo or other methods
OP_20_ABI,
provider,
networks.regtest
// Optional: Add the sender's address
// Address.fromString("your-public-key")
);
In both cases, the returned instance allows you to interact with the OP_20 token contract, using methods defined in its ABI (e.g., balanceOf
, transfer
).
Best Practices
- Specify the expected contract interface (e.g.,
IOP_20Contract
) to enable full IntelliSense support and reduce runtime errors. - Create and reuse a single instance of your
JSONRpcProvider
for consistent connectivity and improved performance. - Set the
sender
parameter explicitly if your contract interactions require it, otherwise, leave it unset for general use.
What’s Next?
Now that you understand the basics, explore the following topics to dive deeper into contract interactions: