Mastering Smart Contracts with Web3.js

·

Live Code Editor: Deploying and Interacting with Smart Contracts

Explore a hands-on approach to deploying and interacting with smart contracts using Web3.js. Below is a breakdown of the components available in the live code editor:

Key Components in the Editor:


The Contract Class in Web3.js

The Contract class, exported by web3-eth-contract, enables seamless interaction with Ethereum smart contracts. It’s also accessible via the main web3 package.

Importing the Contract Class

You can import Contract directly or through a Web3 instance:

// Option 1: From web3-eth-contract
import { Contract } from 'web3-eth-contract';
const contract = new Contract(abi, address, { provider: 'http://127.0.0.1:8545' });

// Option 2: From web3 package
import { Web3 } from 'web3';
const web3 = new Web3('http://127.0.0.1:8545');
const contract = new web3.eth.Contract(abi, address);

Key Differences: Contract vs web3.eth.Contract

👉 Explore Web3.js Contract Documentation


Constructor Parameters

When initializing a Contract, provide:

  1. ABI: Defines how to interact with the contract.
  2. Address (optional): The deployed contract’s Ethereum address.
  3. Options (optional): Configure gas, gasPrice, etc.
const myContract = new Contract(abi, address, {
  defaultGasPrice: '20000000000', // 20 Gwei
  defaultGas: 5000000,
});

Contract Properties and Methods

Core Properties:

Essential Methods:


ABI and Bytecode Essentials

Understanding ABI

The ABI defines a contract’s interface. For example:

contract MyContract {
  uint256 public myNumber;
  function setMyNumber(uint256 _myNumber) public { ... }
}

Yields this ABI:

[
  {
    "inputs": [{ "internalType": "uint256", "name": "_myNumber", "type": "uint256" }],
    "name": "setMyNumber",
    "type": "function"
  }
]

Bytecode Explained

Bytecode is compiled Solidity code (hexadecimal), e.g.:

0x608060405234801561001057600080fd5b506...

When Do You Need Bytecode?

👉 Learn More About Smart Contract Deployment


FAQ Section

1. How do I estimate gas for contract deployment?

Use contractDeployer.estimateGas() before sending the transaction.

2. Can I change a contract’s ABI after deployment?

No. The ABI is immutable once deployed.

3. What’s the difference between call() and send()?

4. How do I filter contract events?

Use the filter option in events:

myContract.events.MyEvent({ filter: { myNumber: [12, 13] } });

5. Is the ABI mandatory?

Yes, for method interaction and TypeScript support.