Read Data from a Contract¶
Learn how to query smart contract state and read data from contracts on the Koinos blockchain.
Overview¶
Reading contract data is a fundamental operation when building applications on Koinos. Unlike transactions that modify state, reading data is free and doesn't require mana.
Prerequisites¶
- Basic understanding of Quick Start
- Node.js and Koilib installed
Reading Contract State¶
Basic Contract Read¶
export async function getHeadInfo(fetchImpl = fetch) {
return getJson("/v1/chain/head_info", fetchImpl);
}
View complete file · Run example
This first read verifies the connection by retrieving the current mainnet head. It is read-only and requires no account.
Working Without a Local ABI¶
Fetching ABI from the Blockchain¶
If you don't have the ABI locally, query the contract metadata service through the provider and parse the returned JSON:
export async function getContractAbi() {
const provider = new Provider(API_BASE);
const response = await provider.call(
"contract_meta_store.get_contract_meta",
{ contract_id: NICKNAMES_CONTRACT_ID }
);
if (!response.meta?.abi) throw new Error("Contract ABI is unavailable");
return JSON.parse(response.meta.abi);
}
View complete file · Run example
ABI Fetching Explained¶
The fetchAbi() function:
- Retrieves the ABI directly from the blockchain where it's stored
- Links it to the contract interface so you can call functions
- Works with any contract as long as you have the contract address and the ABI was deployed by the creator
When to Use Each Approach¶
Local ABI (Recommended):
- Better performance (no network call)
- Works offline during development
- More predictable for production applications
Dynamic ABI Fetching:
- When you don't have the ABI available locally
- For exploring unknown contracts
- When building tools that work with arbitrary contracts
Common Read Operations¶
Token Balance¶
The public REST layer exposes contract-backed token reads in a convenient form:
export async function getKoinBalance(address, fetchImpl = fetch) {
const account = encodeURIComponent(address);
return getJson(
`/v1/account/${account}/balance/${KOIN_CONTRACT_ID}`,
fetchImpl
);
}
View complete file · Run example
Contract Metadata¶
The same API can read the KOIN token's name, symbol, decimals, and supply:
export async function getKoinMetadata(fetchImpl = fetch) {
return getJson(`/v1/token/${KOIN_CONTRACT_ID}/info`, fetchImpl);
}
View complete file · Run example
All four examples are read-only. A live run needs network access to the public mainnet API but no key or wallet.
Best Practices¶
- Cache results when appropriate to reduce API calls
- Handle errors gracefully for network issues
- Use appropriate data types for contract parameters
- Validate results before using in your application