Developer Fundamentals

5. States and Views

Load smart contracts using ABI and call view functions for state data, including historical revisions.

Prerequisites

Peering into Contracts

Contracts hold secrets! 🔮 Smart contracts expose public variables and view functions—no gas needed to read them.
First, grab the ABI (interface) from the block explorer, from your hardhat project or from b32 repo. Think of ABI as a menu telling you what functions are available.

javascriptimport { ThorClient } from '@vechain/sdk-network';
const thor = ThorClient.at('https://mainnet.vechain.org');
const abiResponse = await fetch('https://raw.githubusercontent.com/vechain/b32/master/ABIs/energy.json');
const energyAbi = await abiResponse.json();
const vtho = thor.contracts.load('0x0000000000000000000000000000456e65726779', energyAbi);
const name = await vtho.read.name();
console.log('Name', name);  // "VeThor"
javascriptimport { ThorClient } from '@vechain/sdk-network';
const thor = ThorClient.at('https://mainnet.vechain.org');
const abiResponse = await fetch('https://raw.githubusercontent.com/vechain/b32/master/ABIs/energy.json');
const energyAbi = await abiResponse.json();
const vtho = thor.contracts.load('0x0000000000000000000000000000456e65726779', energyAbi);
const name = await vtho.read.name();
console.log('Name', name);  // "VeThor"
javascriptimport { ThorClient } from '@vechain/sdk-network';
const thor = ThorClient.at('https://mainnet.vechain.org');
const abiResponse = await fetch('https://raw.githubusercontent.com/vechain/b32/master/ABIs/energy.json');
const energyAbi = await abiResponse.json();
const vtho = thor.contracts.load('0x0000000000000000000000000000456e65726779', energyAbi);
const name = await vtho.read.name();
console.log('Name', name);  // "VeThor"

You're reading!

But, how can you make sure it's a contract?

Good question, check hasCode first (true = contract)

One step forward, for sensitive operations can be to check bytecode correspondence.
Fetch bytecode with thor.accounts.getBytecode(addr).

Want past data? Set revision:

vtho.setContractReadOptions({ revision: 12345678 });
vtho.setContractReadOptions({ revision: 12345678 });
vtho.setContractReadOptions({ revision: 12345678 });

Simulate state-changing calls to test:

vtho.read.transfer(addr, '1')
vtho.read.transfer(addr, '1')
vtho.read.transfer(addr, '1')

throws on failure.

Boss level unlocked!​

Pitfalls: b32 only exist for VeChain! Always import full JSON ABI (no fragments); handle simulation errors with try/catch.