Lesson 2 of 5 Interacting with Contracts Using web3.js

Accounts, Units and Transactions

This lesson covers the everyday tasks of a web3.js application: converting between wei and ether, handling BigInt values, creating accounts and signing messages, and building, signing, sending and confirming transactions.

Learning outcomes

After completing this lesson, you will be able to:

  • Convert between wei, gwei and ether.
  • Explain how web3.js v4 uses BigInt.
  • Distinguish node-managed accounts from local accounts.
  • Explain how messages are signed and verified.
  • Describe how transactions are signed, sent and confirmed.

Units and BigInt

Nodes and contracts work only in wei. web3.js converts for display and input.

web3.utils.toWei("1.5", "gwei");      // "1500000000"
web3.utils.toWei("0.1", "ether");     // "100000000000000000"
const balance = await web3.eth.getBalance(account);   // 9999999639454077451720n
web3.utils.fromWei(balance, "ether");   // "9999.99963945407745172"

web3.js v4 returns balances, gas, block numbers and chain IDs as BigInt. BigInt values cannot be mixed with ordinary numbers in arithmetic (10n + 1 throws), and they compare with BigInt literals (chainId === 31337n). Pass amounts as strings or BigInt, never as JavaScript numbers with decimals: 0.1 * 1e18 is not exactly 1017, and amounts above 253 wei (about 0.009 ether) lose precision as numbers. Code written for web3.js v1 received decimal strings instead of BigInt, which explains differences between older and newer examples.

Scenario questions

Working with BigInt

Exam skills 1.2.1

Handle the BigInt values that web3.js v4 returns.

Log in to try this activity Interactive activities are free with an account.

Accounts and message signing

The following terms describe the account functions of web3.js.

web3.eth.getAccounts()
Asks the node or wallet which accounts it manages, such as a development node's unlocked accounts or the connected wallet account.
web3.eth.accounts.create()
Generates a new random key pair locally and returns an account object.
privateKeyToAccount(key)
Builds an account object from an existing private key.
web3.eth.accounts.wallet.add(key)
Adds a key to web3.js's in-memory wallet so that contract send() calls can sign with it.
encrypt / decrypt
Convert a private key to and from a password-protected keystore JSON file.
const acct = web3.eth.accounts.privateKeyToAccount(process.env.PRIVATE_KEY);
const sig = web3.eth.accounts.sign("Sign in to Example: nonce 8812", acct.privateKey);
web3.eth.accounts.recover("Sign in to Example: nonce 8812", sig.signature);
// returns acct.address

sign prefixes the message with "\x19Ethereum Signed Message:\n" and its length (EIP-191), so a signed message can never be a valid transaction. Servers use this for sign-in: they issue a unique challenge, the user signs it, and the server recovers and checks the address. Smart contracts can verify the same signatures with ecrecover or OpenZeppelin's ECDSA, and structured data is signed with EIP-712 typed signatures.

The following diagram shows a sign-in with a signed message.

Signing in with a signed message. The server issues a unique challenge with a random nonce. The user's wallet signs it; sign prefixes the message with the EIP-191 prefix and its length, so a signed message can never be a valid transaction. The server recovers the signer's address from the signature and checks that it matches and that the nonce is unused. Contracts can verify the same signatures with ecrecover, and structured data uses EIP-712 typed signatures.
The signature proves control of the address without a transaction.
True or false

Signing messages

Exam skills 1.2.2

Check how web3.js signs and verifies messages.

Log in to try this activity Interactive activities are free with an account.

Building, signing and sending transactions

With a node-managed account, web3.eth.sendTransaction({ from, to, value }) asks the node or wallet to sign. With a local key, the application signs and submits the raw transaction itself.

const tx = {
  from: acct.address,
  to: recipient,
  value: web3.utils.toWei("0.1", "ether"),
  gas: 21000n,
  maxFeePerGas: web3.utils.toWei("30", "gwei"),
  maxPriorityFeePerGas: web3.utils.toWei("1", "gwei"),
};
const signed = await acct.signTransaction(tx);
const receipt = await web3.eth.sendSignedTransaction(signed.rawTransaction);
console.log(receipt.status, receipt.gasUsed, receipt.type);   // 1n 21000n 2n

web3.js fills missing fields, such as the nonce, chain ID and fees, by querying the node. The returned promise resolves to the receipt once the transaction is included, and it also emits events: sending, sent, transactionHash, receipt and confirmation, which applications use to show progress.

Put in order

Sending with a local key

Exam skills 1.2.3

Arrange the steps of sending a transaction signed with a local private key in web3.js.

Log in to try this activity Interactive activities are free with an account.

Reading the receipt

The following table describes the receipt fields applications use most.

FieldMeaning
status1n for success, 0n for a reverted transaction
transactionHash, blockNumberWhere the transaction was included
gasUsedGas consumed
effectiveGasPricePrice paid per gas, in wei
contractAddressThe new contract's address, for deployments
logsRaw event logs; contract send() receipts also include decoded events
Fill in the number

Reading a receipt

Exam skills 1.2.3 · 5.1.2

Calculate values from receipt fields.

Log in to try this activity Interactive activities are free with an account.
Worked example

A balance check that fails

A script contains if (balance > 1e18) { ... } where balance comes from web3.eth.getBalance. Another line, const total = balance + 100;, throws "Cannot mix BigInt and other types". How should the code be written?

Work in BigInt throughout: if (balance > 10n ** 18n) and const total = balance + 100n;, or convert amounts with BigInt(web3.utils.toWei("1", "ether")). Comparison between a BigInt and a number happens to work, but arithmetic does not, and floating-point literals such as 1e18 invite precision errors in other calculations.

Worked example

Sign in with a signature

A server wants to confirm that a visitor controls address A without charging gas. How can web3.js support this, and how is replay prevented?

The server sends a unique message containing a random nonce and an expiry. The visitor's wallet signs it (personal_sign, which applies the EIP-191 prefix). The server calls web3.eth.accounts.recover(message, signature) and accepts the visitor if the result equals A and the nonce is unused and unexpired. The unique nonce stops an intercepted signature from being reused.

Check yourself

What does web3.utils.toWei("2", "gwei") return?

Show answer

"2000000000": two times 10^9 wei. Gas prices are usually expressed in gwei and must be converted to wei for transactions.

Exam Tips

Remember for the exam

  • toWei and fromWei convert units; nodes always use wei.
  • web3.js v4 returns BigInt; never mix BigInt with numbers in arithmetic.
  • getAccounts() lists node or wallet accounts; accounts.create() makes a local key.
  • sign and recover prove control of an address without a transaction.
  • signTransaction + sendSignedTransaction submits locally signed transactions; check receipt.status.