0
0
Blockchain / Solidityprogramming~5 mins

Reading contract state in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Reading contract state lets you see the current data stored in a blockchain contract. It helps you check values without changing anything.

You want to check a user's token balance in a wallet.
You need to see the current price stored in a smart contract.
You want to verify if a contract feature is enabled or disabled.
You want to display contract data on a website without sending a transaction.
Syntax
Blockchain / Solidity
contractInstance.methods.methodName().call()
Use .call() to read data without spending gas or changing the blockchain.
Replace methodName with the contract's read-only function name.
Examples
Reads the token balance of a user from the contract.
Blockchain / Solidity
const balance = await contractInstance.methods.balanceOf(userAddress).call();
Gets the current price stored in the contract.
Blockchain / Solidity
const price = await contractInstance.methods.getPrice().call();
Sample Program

This program connects to the Ethereum mainnet, reads the token balance of a user from a contract, and prints it.

Blockchain / Solidity
import Web3 from 'web3';

async function readContractState() {
  const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');
  const contractAddress = '0xYourContractAddress';
  const abi = [
    {
      "constant": true,
      "inputs": [{"name": "", "type": "address"}],
      "name": "balanceOf",
      "outputs": [{"name": "", "type": "uint256"}],
      "type": "function"
    }
  ];

  const contract = new web3.eth.Contract(abi, contractAddress);
  const userAddress = '0xUserAddress';

  const balance = await contract.methods.balanceOf(userAddress).call();
  console.log(`Balance of user: ${balance}`);
}

readContractState();
OutputSuccess
Important Notes

Reading state with .call() does not cost gas because it does not change the blockchain.

Make sure the contract ABI includes the method you want to call.

Summary

Use .call() to read contract data without sending a transaction.

Reading contract state helps you get current values like balances or settings.