Web3.js Cheat Sheet

Last modified: 2023-10-02

Blockchain Ethereum Web3

Blocks

// Get block
web3.eth.getBlock('latest')

Converting

// Wei to Ether
web3.utils.fromWei('1000000000000000000', 'ether')
// "1"

// Ether to Wei
web3.utils.toWei('0.001')
// "1000000000000000"

Contract

// Initialize a contract
const tokenAbi = [...]; // JSON interface
const tokenAddress = '0x1234...';
const contract = new web3.eth.Contract(tokenAbi, tokenAddress);

Send Ether to Contract

// Send ether to the contract with interacting ABI
contract.example({value: web3.utils.toWei('0.001')})

// Send ether to the contract from outside
contract.sendTransaction({value: toWei('0.0001')})

// Send ether to the contract from outside using `call` function to invoke fallback
(bool success,) = payable(_victim_contract_address).call{value: '1.0'}("");

// Send etehr to the contract from outside by invoking specific function
contract.exampleFunc{value: msg.value}(address(this))

Get Storage of Contract

// the second arguement is the index of the storage.
web3.eth.getStorageAt(contract.address, 0)
web3.eth.getStorageAt(contract.address, 1)

Function Signature

We can retrieve a function signature with encodeFunctionSignature. We can also use it to invoke the contract function via sendTransaction.

const example = web3.eth.abi.encodeFunctionSignature("example()")

// We can invoke the function using this signature
await web3.eth.sendTransaction({from: userAddress, to: contractAddress, data: example})

Function Call

const myAddress = "0x123...";
const functionSignature = {
  name: 'exampleFunc',
  type: 'function',
  inputs: [{type: 'address', name: '_address'}]
}
const params = [myAddress]

const funcData = web3.eth.abi.encodeFunctionCall(functionSignature, params)

// Execute the function
await web3.eth.sendTransaction({from: myAddress, to: contract.address, funcData})

Send Ether to Contract

// Set a gas value
contract.exampleFunc{gas: 100000}()