diff --git a/README.md b/README.md
index adf5ec07574..3284ef04f23 100644
--- a/README.md
+++ b/README.md
@@ -43,7 +43,7 @@ yarn add web3
## Migration Guide
-- [Migration Guide from Web3.js 1.x to 4.x](https://docs.web3js.org/guides/web3_upgrade_guide/x/)
+- [Migration Guide from Web3.js 1.x to 4.x](https://docs.web3js.org/guides/web3_upgrade_guide/index)
Breaking changes are listed in migration guide and its first step for migrating from Web3.js 1.x to 4.x. If there is any question or discussion feel free to ask in [Discord](https://discord.gg/yjyvFRP), and in case of any bug or new feature request [open issue](https://github.com/web3/web3.js/issues/new) or create a pull request for [contributions](https://github.com/web3/web3.js/blob/4.x/.github/CONTRIBUTING.md).
## Useful links
@@ -76,18 +76,18 @@ yarn add web3
## Package.json Scripts
-| Script | Description |
-| ---------------- |--------------------------------------------------------------------|
-| clean | Uses `rimraf` to remove `dist/` |
-| build | Uses `tsc` to build all packages |
-| lint | Uses `eslint` to lint all packages |
-| lint:fix | Uses `eslint` to check and fix any warnings |
-| format | Uses `prettier` to format the code |
-| test | Uses `jest` to run unit tests in each package |
-| test:integration | Uses `jest` to run tests under `/test/integration` in each package |
-| test:unit | Uses `jest` to run tests under `/test/unit` in each package |
-| test:manual:long-connection-ws | Runs manual tests for keeping a long WebSocket connection |
-| test:manual | Runs manual tests under `test/manual` in the web3 package |
+| Script | Description |
+| ------------------------------ | ------------------------------------------------------------------ |
+| clean | Uses `rimraf` to remove `dist/` |
+| build | Uses `tsc` to build all packages |
+| lint | Uses `eslint` to lint all packages |
+| lint:fix | Uses `eslint` to check and fix any warnings |
+| format | Uses `prettier` to format the code |
+| test | Uses `jest` to run unit tests in each package |
+| test:integration | Uses `jest` to run tests under `/test/integration` in each package |
+| test:unit | Uses `jest` to run tests under `/test/unit` in each package |
+| test:manual:long-connection-ws | Runs manual tests for keeping a long WebSocket connection |
+| test:manual | Runs manual tests under `test/manual` in the web3 package |
[npm-url]: https://npmjs.org/package/web3
[downloads-image]: https://img.shields.io/npm/dm/web3?label=npm%20downloads
diff --git a/docs/docs/glossary/index.md b/docs/docs/glossary/index.md
index 1af9691a85e..7af367af75b 100644
--- a/docs/docs/glossary/index.md
+++ b/docs/docs/glossary/index.md
@@ -4,7 +4,6 @@ sidebar_label: '📖 Glossary'
title: Glossary
---
-
## Provider
In web3.js, a `provider` is an object responsible for enabling connectivity with the Ethereum network in various ways. Providers facilitate the connection of your web application to an Ethereum node, different provider types are available in web3.js(HTTP, WebSocket and IPC), each with its own features and use cases. **It's important to note that a provider itself only provides read-only access to the blockchain.** It does not use any private keys or accounts for interaction. This read-only functionality is particularly useful for querying data and making calls to the blockchain without the need for private key authorization.
@@ -13,12 +12,10 @@ In web3.js, a `provider` is an object responsible for enabling connectivity with
In web3.js, an `account` allows you to perform operations on the blockchain, such as sending transactions, signing data, and interacting with contracts. It serves as the key component for **using a private key** directly to execute various blockchain operations. In other libraries, this concept is often referred to as a `signer`. This versatility in terminology doesn't change its fundamental purpose, providing a secure and straightforward means to manage Ethereum-related operations.
-
## Wallet
A `wallet` in web3.js can store multiple `accounts`. This feature allows you to manage various private keys for different operations. When using methods such as `web3.eth.sendTransaction()` or `web3.eth.contract.methods.doSomething().send({})`, the web3.js library handles these transactions using the wallet accounts under the hood. Essentially, the wallet makes it easier to coordinate multiple accounts for smoother Ethereum operations.
-
## Contract
The `Contract` class is an important class in the `web3-eth-contract` package, also available in the `web3` package. It serves as an abstraction representing a connection to a specific contract on the Ethereum Network, enabling applications to interact with it as a typical JavaScript object. Through the `Contract` class, you can execute functions and listen to events associated with the smart contract (e.g, `contract.methods.doSomething().call()`)
@@ -82,30 +79,39 @@ contract Test {
```json title='Resulting JSON ABI'
[
- {
- "type": "constructor",
- "stateMutability": "nonpayable",
- "inputs": [{"internalType":"uint256","name":"testInt","type":"uint256"}],
- },
- {
- "type": "event",
- "name": "Event",
- "inputs": [{"indexed":true,"internalType":"uint256","name":"b","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"c","type":"bytes32"}],
- "anonymous": false,
- },
- {
- "type": "event",
- "name": "Event2",
- "inputs": [{"indexed":true,"internalType":"uint256","name":"b","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"c","type":"bytes32"}],
- "anonymous": false,
- },
- {
- "type": "function",
- "name": "foo",
- "stateMutability": "nonpayable",
- "inputs": [{"internalType":"uint256","name":"b","type":"uint256"},{"internalType":"bytes32","name":"c","type":"bytes32"}],
- "outputs": [{"internalType":"address","name":"","type":"address"}],
- }
+ {
+ "type": "constructor",
+ "stateMutability": "nonpayable",
+ "inputs": [{ "internalType": "uint256", "name": "testInt", "type": "uint256" }]
+ },
+ {
+ "type": "event",
+ "name": "Event",
+ "inputs": [
+ { "indexed": true, "internalType": "uint256", "name": "b", "type": "uint256" },
+ { "indexed": false, "internalType": "bytes32", "name": "c", "type": "bytes32" }
+ ],
+ "anonymous": false
+ },
+ {
+ "type": "event",
+ "name": "Event2",
+ "inputs": [
+ { "indexed": true, "internalType": "uint256", "name": "b", "type": "uint256" },
+ { "indexed": false, "internalType": "bytes32", "name": "c", "type": "bytes32" }
+ ],
+ "anonymous": false
+ },
+ {
+ "type": "function",
+ "name": "foo",
+ "stateMutability": "nonpayable",
+ "inputs": [
+ { "internalType": "uint256", "name": "b", "type": "uint256" },
+ { "internalType": "bytes32", "name": "c", "type": "bytes32" }
+ ],
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }]
+ }
]
```
@@ -123,6 +129,7 @@ const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
```
## WebSocketProvider
+
[WebSocketProvider](https://docs.web3js.org/guides/web3_providers_guide/#websocket-provider) in Web3.js connects your application to an Ethereum node via WebSocket, enabling real-time and asynchronous communication. This provider is ideal for applications needing real-time updates, such as new blocks or smart contract events. It offers better performance for high-throughput applications compared to `HttpProvider`. Ensure secure connections with `wss://` for exposed endpoints. Handle reconnections gracefully for reliable operation.
```javascript title='WebSocketProvider example'
@@ -138,13 +145,14 @@ The `Events` class in Web3.js is a crucial part of the library that enables deve
```solidity title='Event in solidity'
contract MyContract {
- event Transfer(address indexed from, address indexed to, uint value);
+ event Transfer(address indexed from, address indexed to, uint256 value);
- function transfer(address recipient, uint amount) public {
- // ... transfer logic ...
- emit Transfer(msg.sender, recipient, amount);
- }
+ function transfer(address recipient, uint256 amount) public {
+ // ... transfer logic ...
+ emit Transfer(msg.sender, recipient, amount);
+ }
}
+
```
```javascript title='Event in web3.js'
@@ -158,9 +166,9 @@ const myContract = new web3.eth.Contract(MyContract.abi, contractAddress);
const transferEvent = myContract.events.Transfer(); // Access the Transfer event
-transferEvent.on('data', (event) => {
- console.log('Transfer Event:', event);
- // Process the event data (from, to, value)
+transferEvent.on('data', event => {
+ console.log('Transfer Event:', event);
+ // Process the event data (from, to, value)
});
```
@@ -190,4 +198,5 @@ web3.eth.getPastLogs(options)
.catch((error) => {
console.error('Error retrieving logs:', error);
});
-`
\ No newline at end of file
+`
+```
diff --git a/docs/docs/guides/getting_started/_category_.yml b/docs/docs/guides/01_getting_started/_category_.yml
similarity index 100%
rename from docs/docs/guides/getting_started/_category_.yml
rename to docs/docs/guides/01_getting_started/_category_.yml
diff --git a/docs/docs/guides/01_getting_started/introduction.md b/docs/docs/guides/01_getting_started/introduction.md
new file mode 100644
index 00000000000..b1fc2a8469a
--- /dev/null
+++ b/docs/docs/guides/01_getting_started/introduction.md
@@ -0,0 +1,92 @@
+---
+slug: /
+sidebar_position: 1
+sidebar_label: Introduction
+---
+
+# Introduction
+
+Web3.js is a robust and flexible collection of **TypeScript and JavaScript** libraries that allows developers to interact with local or remote [Ethereum](https://ethereum.org/en/) nodes (or **any EVM-compatible blockchain**) over **HTTP, IPC or WebSocket** connections. It is a powerful and efficient toolkit for crafting applications within the Ethereum ecosystem and beyond.
+
+This documentation is the entrypoint to Web3.js for developers. It covers [basic](/guides/getting_started/quickstart) and [advanced](/guides/smart_contracts/mastering_smart_contracts) usage with examples, and includes comprehensive [API documentation](/api) as well as guides for common tasks, like [upgrading](/guides/web3_upgrade_guide) from older versions.
+
+## Features of Web3.js v4
+
+- Flexible
+ - ECMAScript (ESM) and CommonJS (CJS) builds
+ - [Plugins](/guides/web3_plugin_guide/) for extending functionality
+- Efficient
+ - Modular, [package](/#packages)-based design reduces unneeded dependencies
+ - [Tree shakable with ESM](/guides/advanced/tree_shaking)
+ - Use of native [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) (instead of large [BigNumber](https://mikemcl.github.io/bignumber.js/) libraries)
+ - Efficient ABI [encoding](/api/web3-eth-abi/function/encodeFunctionCall) & [decoding](/api/web3-eth-abi/function/decodeParameter)
+- Developer-Friendly
+ - [Dynamic contract types](/guides/smart_contracts/infer_contract_types/) & full API in TypeScript
+ - Custom output [formatters](https://docs.web3js.org/api/web3-utils/function/format)
+ - In compliance with the [Ethereum JSON-RPC Specification](https://ethereum.github.io/execution-apis/api-documentation/)
+
+## Using These Docs
+
+There is a lot to learn about Web3.js! Here are some tips for developers of different skill levels. Remember, you can always [reach out directly](/guides/feedback/#urgent-questions-or-concerns) with Discord or Twitter if you're feeling stuck.
+
+### For Beginner Web3.js Developers
+
+New Web3.js developers should proceed to the [Quickstart](/guides/getting_started/quickstart) section to learn how to get started with Web3.js. Once you understand the basics, you may want to consider learning more about [providers](/guides/web3_providers_guide/), [wallets and accounts](/guides/wallet), [smart contracts](/guides/smart_contracts/smart_contracts_guide), and how to [use Web3.js with the Hardhat development environment](/guides/hardhat_tutorial).
+
+### For Intermediate & Advanced Web3.js Developers
+
+If you're already familiar with Ethereum and Web3.js development, you may want to review the Web3.js [package structure](#packages--plugins) and proceed directly to the [package-level documentation](/libdocs/ABI) and [API documentation](/api). Application developers may wish to review the [Web3.js configuration guide](/guides/web3_config) or learn how to use Web3.js with tools like the [MetaMask](/guides/dapps/metamask-react) wallet or the [WalletConnect](/guides/dapps/web3_modal_guide) wallet selection modal. Don't forget to review the [list of available plugins](https://web3js.org/plugins) or even [learn how to build your own Web3.js plugin](/guides/web3_plugin_guide/plugin_authors)!
+
+## Packages & Plugins
+
+Web3.js is a modular collection of packages, each of which serves a specific needs. This means developers don't need to install the entire Web3 library for most use cases. Instead, necessary packages are selectively installed for a more efficient development experience. Here is an overview of a selection of available packages:
+
+- [**Web3Eth:**](/libdocs/Web3Eth) The `web3-eth` package is the entrypoint to Web3.js - it's the control center for managing interactions with Ethereum and other EVM-compatible networks.
+
+- [**Net:**](/libdocs/Net) The `web3-net` package provides discovery and interactions for an **Ethereum node's network properties.**
+
+- [**Accounts:**](/libdocs/Accounts) The `web3-eth-accounts` package has tools for creating Ethereum accounts and the **secure signing** of transactions and data.
+
+- [**Personal:**](/libdocs/Personal) Use `web3-eth-personal` for **direct communication about your accounts with the Ethereum node**, which streamlines account management during development.
+
+ **NOTE:** _For enhanced security in production and when interacting with public nodes, consider using `web3-eth-accounts` for local signing operations, which keeps your private keys and sensitive information secure on your local machine_
+
+- [**Utils:**](/libdocs/Utils) The `web3-utils` package provides helpers to perform a range of essential Ethereum development tasks, including **converting data formats, checking addresses, encoding and decoding data, hashing, handling numbers, and much more.**.
+
+- [**Contract:**](/libdocs/Contract) The `web3-eth-contract` package makes it easy to **interact with smart contracts through JavaScript or TypeScript,** which streamlines the development process and makes it less error-prone.
+
+- [**ABI:**](/libdocs/ABI) The `web3-eth-abi` package simplifies decoding logs and parameters, encoding function calls and signatures, and inferring types for efficient Ethereum **smart contract interactions.**
+
+- [**ENS:**](/libdocs/ENS) The `web3-eth-ens` package makes it easy for developers to communicate with the **Ethereum Name Service (ENS).**
+
+- [**Iban:**](/libdocs/Iban) The `web3-eth-iban` package allows you to switch between **Ethereum addresses and special banking-like addresses** (IBAN or BBAN) and simplifies conversion between the types.
+
+### Additional Supporting Packages
+
+- [**Web3 Core:**](/api/web3-core) subscriptions, request management, and configuration used by other Web3 packages
+
+- [**Web3 Types:**](/api/web3-types) data structures, objects, interfaces and types used by Web3
+
+- [**Web3 Validator:**](/api/web3-validator) runtime type validation against predefined types or custom schemas
+
+- [**Web3 Errors:**](/api/web3-errors) error codes and common error classes that are used by other Web3 packages
+
+- [**Web3 RPC Methods:**](/api/web3/namespace/rpcMethods) functions for making RPC requests to Ethereum using a given provider
+
+### Plugins
+
+Web3.js supports [plugins](/guides/web3_plugin_guide/), which are another way to encapsulate capabilities that support a specific need. There are plugins that exist to support native features, like those described by [EIPs](https://eips.ethereum.org/) as well as plugins that are designed to support specific smart contracts, middleware, or even other Ethereum-compatible networks. Visit the [Web3.js plugins homepage](https://web3js.org/plugins) to view a list of the most important Web3.js plugins, which includes:
+
+- [EIP-4337 (Account Abstraction) Plugin](https://www.npmjs.com/package/@chainsafe/web3-plugin-eip4337)
+
+- [EIP-4844 (Blob Transactions) Plugin](https://www.npmjs.com/package/web3-plugin-blob-tx)
+
+- [zkSync Plugin](https://www.npmjs.com/package/web3-plugin-zksync)
+
+## Advantages Over Other Libraries
+
+- **Extensive Documentation and Community**: Web3.js is one of the most established Ethereum libraries, which means it benefits from extensive documentation and a large, active community. Web3.js is widely adopted and has been thoroughly tested in various production environments, and is compatible with a broad range of other tools and services in the Ethereum ecosystem.
+
+- **Modular Design**: Web3.js is designed to be modular, which allows developers to use specific packages according to their needs. This leads to smaller bundle sizes and faster load times for web applications.
+
+- **Active Development and Support**: Web3.js sees regular updates and active development. This support is crucial for developers needing assurance that the library they're using will keep pace with the evolving Ethereum landscape.
diff --git a/docs/docs/guides/getting_started/quickstart.md b/docs/docs/guides/01_getting_started/quickstart.md
similarity index 87%
rename from docs/docs/guides/getting_started/quickstart.md
rename to docs/docs/guides/01_getting_started/quickstart.md
index 80551ad735b..fb0a70c851f 100644
--- a/docs/docs/guides/getting_started/quickstart.md
+++ b/docs/docs/guides/01_getting_started/quickstart.md
@@ -9,11 +9,11 @@ Use the live code editor to try Web3.js in your browser now! Keep reading to lea
## Live Code Editor
-
+
## Installation
-If NPM is being used as package manager, install Web3.js with the following command:
+If NPM is being used as package manager, install Web3.js with the following command:
```
npm i web3
@@ -25,19 +25,19 @@ For projects using Yarn as a package manager, use:
yarn add web3
```
-Note: Installing Web3.js in this way will bring in all Web3.js sub-[packages](/#packages). If you only need specific packages, it is recommended to install them individually (e.g, if you want the [Contract](/libdocs/Contract) package, use `npm i web3-eth-contract` instead)
+Note: Installing Web3.js in this way will bring in all Web3.js sub-[packages](/#packages). If you only need specific packages, it is recommended to install them individually (e.g, if you want the [Contract](/libdocs/Contract) package, use `npm i web3-eth-contract` instead)
## Importing Web3.js
Web3.js v4 supports both CommonJS (CJS) and native ECMAScript module (ESM) imports. For importing the main Web3 class in CJS, use:
-``` js
+```js
const { Web3 } = require('web3');
```
For ESM-style imports, use:
-``` ts
+```ts
import { Web3 } from 'web3';
```
@@ -47,18 +47,19 @@ import { Web3 } from 'web3';
Web3.js is in compliance with [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193), the Ethereum Provider JavaScript API, so any EIP-1193 provider can be used to initialize the `Web3` object.
-``` ts
+```ts
import { Web3 } from 'web3';
-// private RPC endpoint
-const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_ID');
+// private RPC endpoint
+const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_ID');
// or public RPC endpoint
-// const web3 = new Web3('https://eth.llamarpc.com');
+// const web3 = new Web3('https://eth.llamarpc.com');
web3.eth.getBlockNumber().then(console.log);
// ↳ 18849658n
```
+
## Querying the Blockchain
After instantiating the `Web3` instance with a provider, the [`web3-eth`](/libdocs/Web3Eth) package can be used to fetch data from the Ethereum network:
@@ -97,7 +98,7 @@ Using the `Wallet` to create a random account is a good way to accelerate the de
```ts
// create random wallet with 1 account
-web3.eth.accounts.wallet.create(1)
+web3.eth.accounts.wallet.create(1);
/* ↳
Wallet(1)
[
@@ -129,7 +130,9 @@ Private keys are sensitive data and should be treated as such. Make sure that pr
```ts
// the private key must start with the "0x" prefix
-const account = web3.eth.accounts.wallet.add('0x50d349f5cf627d44858d6fcb6fbf15d27457d35c58ba2d5cfeaf455f25db5bec');
+const account = web3.eth.accounts.wallet.add(
+ '0x50d349f5cf627d44858d6fcb6fbf15d27457d35c58ba2d5cfeaf455f25db5bec',
+);
console.log(account[0].address);
//↳ 0xcE6A5235d6033341972782a15289277E85E5b305
@@ -144,21 +147,22 @@ This is an example of using a private key to add an account to a wallet, and the
```ts
// add an account to a wallet
-const account = web3.eth.accounts.wallet.add('0x50d349f5cf627d44858d6fcb6fbf15d27457d35c58ba2d5cfeaf455f25db5bec');
+const account = web3.eth.accounts.wallet.add(
+ '0x50d349f5cf627d44858d6fcb6fbf15d27457d35c58ba2d5cfeaf455f25db5bec',
+);
// create transaction object to send 1 eth to '0xa32...c94' address from the account[0]
-const tx =
-{
- from: account[0].address,
- to: '0xa3286628134bad128faeef82f44e99aa64085c94',
- value: web3.utils.toWei('1', 'ether')
+const tx = {
+ from: account[0].address,
+ to: '0xa3286628134bad128faeef82f44e99aa64085c94',
+ value: web3.utils.toWei('1', 'ether'),
};
// the "from" address must match the one previously added with wallet.add
// send the transaction
const txReceipt = await web3.eth.sendTransaction(tx);
-console.log('Tx hash:', txReceipt.transactionHash)
+console.log('Tx hash:', txReceipt.transactionHash);
// ↳ Tx hash: 0x03c844b069646e08af1b6f31519a36e3e08452b198ef9f6ce0f0ccafd5e3ae0e
```
@@ -172,22 +176,21 @@ The first step to interacting with a smart contract is to instantiate it, which
```ts
// Uniswap token smart contract address (Mainnet)
-const address = '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984'
+const address = '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984';
// you can find the complete ABI on etherscan.io
// https://etherscan.io/address/0x1f9840a85d5af5bf1d1762f925bdaddc4201f984#code
-const ABI =
-[
- {
- name: 'symbol',
- outputs: [{ type: 'string' }],
- type: 'function',
- },
- {
- name: 'totalSupply',
- outputs: [{ type: 'uint256' }],
- type: 'function',
- },
+const ABI = [
+ {
+ name: 'symbol',
+ outputs: [{ type: 'string' }],
+ type: 'function',
+ },
+ {
+ name: 'totalSupply',
+ outputs: [{ type: 'uint256' }],
+ type: 'function',
+ },
];
// instantiate the smart contract
@@ -202,7 +205,7 @@ Since reading data from a smart contract does not consume any gas, it's not nece
// make the call to the contract
const symbol = await uniswapToken.methods.symbol().call();
-console.log('Uniswap symbol:',symbol);
+console.log('Uniswap symbol:', symbol);
// ↳ Uniswap symbol: UNI
// make the call to the contract
@@ -221,12 +224,12 @@ Writing data to a smart contract consumes gas and requires the use of an account
const to = '0xcf185f2F3Fe19D82bFdcee59E3330FD7ba5f27ce';
// value to transfer (1 with 18 decimals)
-const value = web3.utils.toWei('1','ether');
+const value = web3.utils.toWei('1', 'ether');
// send the transaction => return the Tx receipt
-const txReceipt = await uniswapToken.methods.transfer(to,value).send({from: account[0].address});
+const txReceipt = await uniswapToken.methods.transfer(to, value).send({ from: account[0].address });
-console.log('Tx hash:',txReceipt.transactionHash);
+console.log('Tx hash:', txReceipt.transactionHash);
// ↳ Tx hash: 0x14273c2b5781cc8f1687906c68bfc93482c603026d01b4fd37a04adb6217ad43
```
@@ -261,12 +264,12 @@ import { Web3 } from 'web3';
const web3 = new Web3('wss://ethereum.publicnode.com');
// instantiate contract
-const uniswapToken = new web3.eth.Contract(abi, address)
+const uniswapToken = new web3.eth.Contract(abi, address);
// create the subscription to all the 'Transfer' events
const subscription = uniswapToken.events.Transfer();
// listen to the events
-subscription.on('data',console.log);
+subscription.on('data', console.log);
// ↳ [{...},{...}, ...] live events will be printed in the console
```
diff --git a/docs/docs/guides/01_getting_started/return-formats.md b/docs/docs/guides/01_getting_started/return-formats.md
new file mode 100644
index 00000000000..3afabcb6871
--- /dev/null
+++ b/docs/docs/guides/01_getting_started/return-formats.md
@@ -0,0 +1,121 @@
+---
+sidebar_position: 3
+sidebar_label: Return Formats
+---
+
+# Return Formats
+
+By default, Web3.js formats byte values as hexadecimal strings (e.g. `"0x221`") and number values as [`BigInt`s](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt). The default formats can be configured at the global level by updating the [`defaultReturnFormat` configuration option](/guides/web3_config/#defaultreturnformat). Many Web3.js functions (e.g. [`getBlock`](/api/web3-eth/function/getBlock), [`sendTransaction`](/api/web3-eth/function/sendTransaction)) accept an optional parameter named `returnFormat` of the [type `DataFormat`](/api/web3-types#DataFormat) that can be used to configure the format for data returned by that single function invocation.
+
+The following example demonstrates working with return formats:
+
+```ts
+import { Block, FMT_BYTES, FMT_NUMBER, Numbers, Web3 } from 'web3';
+
+const web3 = new Web3('https://eth.llamarpc.com');
+
+// use the default return format
+web3.eth.getBlock().then((block: Block) => {
+ console.log(`Block #${block.number} Hash: ${block.hash}`);
+});
+// ↳ Block #20735255 Hash: 0xbaea6dbd46fa810a27be4c9eac782602f8efe7512fb30a8455c127b101a23e22
+
+// specify the return format for a single function invocation
+web3.eth
+ .getBlockNumber({
+ bytes: FMT_BYTES.HEX,
+ number: FMT_NUMBER.HEX,
+ })
+ .then((blockNumber: Numbers) => {
+ console.log(`Block #${blockNumber}`);
+ });
+// ↳ Block #0x13c6517
+
+// configure default return format for the web3-eth package
+web3.eth.defaultReturnFormat = {
+ bytes: FMT_BYTES.UINT8ARRAY,
+ number: FMT_NUMBER.HEX,
+};
+
+web3.eth.getBlock().then((block: Block) => {
+ console.log(`Block #${block.number} Hash: [${block.hash}]`);
+});
+// ↳ Block #0x13c6517 Hash: [186,234,109,...,162,62,34]
+```
+
+The supported return formats are:
+
+- Bytes
+ - [`FMT_BYTES.HEX`](/api/web3-types/enum/FMT_BYTES#HEX): hexadecimal [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) (e.g. `"0xdd"`)
+ ```ts
+ web3.eth
+ .getBlock(undefined, undefined, {
+ bytes: FMT_BYTES.HEX,
+ number: FMT_NUMBER.BIGINT,
+ })
+ .then((block: Block) => {
+ console.log(`Block hash: ${block.hash}`);
+ });
+ // ↳ Block hash: 0xbaea6dbd46fa810a27be4c9eac782602f8efe7512fb30a8455c127b101a23e22
+ ```
+ - [`FMT_BYTES.UINT8ARRAY`](/api/web3-types/enum/FMT_BYTES#UINT8ARRAY): [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) (e.g. `[ 2, 33 ]`)
+ ```ts
+ web3.eth
+ .getBlock(undefined, undefined, {
+ bytes: FMT_BYTES.UINT8ARRAY,
+ number: FMT_NUMBER.BIGINT,
+ })
+ .then((block: Block) => {
+ console.log(`Block hash: [${block.hash}]`);
+ });
+ // ↳ Block hash: [186,234,109,...,162,62,34]
+ ```
+- Numbers
+ - [`FMT_NUMBER.BIGINT`](/api/web3-types/enum/FMT_NUMBER#BIGINT): [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) (e.g. `221n`)
+ ```ts
+ web3.eth
+ .getBlockNumber({
+ bytes: FMT_BYTES.HEX,
+ number: FMT_NUMBER.BIGINT,
+ })
+ .then((blockNumber: Numbers) => {
+ console.log(`Block #${blockNumber}`);
+ });
+ // ↳ Block #20735255
+ ```
+ - [`FMT_NUMBER.HEX`](/api/web3-types/enum/FMT_NUMBER#HEX): hexadecimal [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) (e.g. `"0xdd"`)
+ ```ts
+ web3.eth
+ .getBlockNumber({
+ bytes: FMT_BYTES.HEX,
+ number: FMT_NUMBER.HEX,
+ })
+ .then((blockNumber: Numbers) => {
+ console.log(`Block #${blockNumber}`);
+ });
+ // ↳ Block #0x13c6517
+ ```
+ - [`FMT_NUMBER.NUMBER`](/api/web3-types/enum/FMT_NUMBER#NUMBER): [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) (e.g. `221`)
+ ```ts
+ web3.eth
+ .getBlockNumber({
+ bytes: FMT_BYTES.HEX,
+ number: FMT_NUMBER.NUMBER,
+ })
+ .then((blockNumber: Numbers) => {
+ console.log(`Block #${blockNumber}`);
+ });
+ // ↳ Block #20735255
+ ```
+ - [`FMT_NUMBER.STR`](/api/web3-types/enum/FMT_NUMBER#STR): [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) (e.g. `"221"`)
+ ```ts
+ web3.eth
+ .getBlockNumber({
+ bytes: FMT_BYTES.HEX,
+ number: FMT_NUMBER.STR,
+ })
+ .then((blockNumber: Numbers) => {
+ console.log(`Block #${blockNumber}`);
+ });
+ // ↳ Block #20735255
+ ```
diff --git a/docs/docs/guides/web3_providers_guide/_category_.yml b/docs/docs/guides/02_web3_providers_guide/_category_.yml
similarity index 100%
rename from docs/docs/guides/web3_providers_guide/_category_.yml
rename to docs/docs/guides/02_web3_providers_guide/_category_.yml
diff --git a/docs/docs/guides/web3_providers_guide/eip6963.md b/docs/docs/guides/02_web3_providers_guide/eip6963.md
similarity index 66%
rename from docs/docs/guides/web3_providers_guide/eip6963.md
rename to docs/docs/guides/02_web3_providers_guide/eip6963.md
index 0965e440c9b..37577aa54d4 100644
--- a/docs/docs/guides/web3_providers_guide/eip6963.md
+++ b/docs/docs/guides/02_web3_providers_guide/eip6963.md
@@ -9,7 +9,7 @@ sidebar_label: 'EIP-6963: Multi Injected Provider Discovery'
EIP-6963 proposes the "Multi Injected Provider Discovery" standard, which aims to enhance the discoverability and interaction with multiple injected Ethereum providers in a browser environment. Injected providers refer to browser extensions or other injected scripts that provide access to an Ethereum provider within the context of a web application.
-Web3.js library has utility functions for discovery of injected providers using `requestEIP6963Providers()` and `onNewProviderDiscovered(eventDetails)`.
+Web3.js library has utility functions for discovery of injected providers using `requestEIP6963Providers()` and `onNewProviderDiscovered(eventDetails)`.
`onNewProviderDiscovered(eventDetails)` can be used to subscribe to events of provider discovery & providers map update and `requestEIP6963Providers()` returns Promise object that resolves to `Map` object containing list of providers. For updated providers `eip6963:providersMapUpdated` event is emitted and it has updated Map object. This event can be subscribed as mentioned earlier using `onNewProviderDiscovered(eventDetails)`
@@ -17,8 +17,8 @@ Web3.js library has utility functions for discovery of injected providers using
```ts
export interface EIP6963ProviderDetail {
- info: EIP6963ProviderInfo;
- provider: EIP1193Provider;
+ info: EIP6963ProviderInfo;
+ provider: EIP1193Provider;
}
```
@@ -26,42 +26,45 @@ where `info` has details of provider containing UUID, name, Icon and RDNS as def
```ts
export interface EIP6963ProviderInfo {
- uuid: string;
- name: string;
- icon: string;
- rdns: string;
+ uuid: string;
+ name: string;
+ icon: string;
+ rdns: string;
}
```
`provider` in `EIP6963ProviderDetail` is `EIP1193Provider` and it contains actual provider that can be injected in web3 instance.
-Following code snippet demonstrates usage of `requestEIP6963Providers()` function for providers discovery.
+Following code snippet demonstrates usage of `requestEIP6963Providers()` function for providers discovery.
```ts
-//Assuming multiple providers are installed in browser.
+//Assuming multiple providers are installed in browser.
import { Web3 } from 'web3';
// Following will subscribe to event that will be triggered when providers map is updated.
-Web3.onNewProviderDiscovered((provider) => {
- console.log(provider.detail); // This will log the populated providers map object, provider.detail has Map of all providers yet discovered
- // add logic here for updating UI of your DApp
+Web3.onNewProviderDiscovered(provider => {
+ console.log(provider.detail); // This will log the populated providers map object, provider.detail has Map of all providers yet discovered
+ // add logic here for updating UI of your DApp
});
// Call the function and wait for the promise to resolve
let providers = await Web3.requestEIP6963Providers();
for (const [key, value] of providers) {
- console.log(value);
+ console.log(value);
-/* Based on your DApp's logic show use list of providers and get selected provider's UUID from user for injecting its EIP6963ProviderDetail.provider EIP1193 object into web3 object */
+ /* Based on your DApp's logic show use list of providers and get selected provider's UUID from user for injecting its EIP6963ProviderDetail.provider EIP1193 object into web3 object */
- if (value.info.name === 'MetaMask') {
- const web3 = new Web3(value.provider);
+ if (value.info.name === 'MetaMask') {
+ const web3 = new Web3(value.provider);
- // now you can use web3 object with injected provider
- console.log(await web3.eth.getTransaction('0x82512812c11f56aa2474a16d5cc8916b73cd6ed96bf9b8defb3499ec2d9070cb'));
- }
+ // now you can use web3 object with injected provider
+ console.log(
+ await web3.eth.getTransaction(
+ '0x82512812c11f56aa2474a16d5cc8916b73cd6ed96bf9b8defb3499ec2d9070cb',
+ ),
+ );
+ }
}
-
-```
\ No newline at end of file
+```
diff --git a/docs/docs/guides/web3_providers_guide/events_listening.md b/docs/docs/guides/02_web3_providers_guide/events_listening.md
similarity index 97%
rename from docs/docs/guides/web3_providers_guide/events_listening.md
rename to docs/docs/guides/02_web3_providers_guide/events_listening.md
index a8e36a3cd22..ae0b809d4a5 100644
--- a/docs/docs/guides/web3_providers_guide/events_listening.md
+++ b/docs/docs/guides/02_web3_providers_guide/events_listening.md
@@ -26,42 +26,42 @@ import { Web3 } from 'web3';
const web3 = new Web3(/* PROVIDER*/);
web3.provider.on('message', () => {
- // ...
+ // ...
});
web3.provider.on('connect', () => {
- // ...
+ // ...
});
web3.provider.on('disconnect', () => {
- // ...
+ // ...
});
web3.provider.on('accountsChanged', () => {
- // ...
+ // ...
});
web3.provider.on('chainChanged', () => {
- // ...
+ // ...
});
// it is possible to catch errors that could happen in the underlying connection Socket with the `error` event
// and it is also used to catch the error when max reconnection attempts is exceeded
// as in section: /docs/guides/web3_providers_guide/#error-message
web3.provider.on('error', () => {
- // ...
+ // ...
});
// ...
// for every event above `once` can be used to register to the event only once
web3.provider.once('SUPPORTED_EVENT_NAME', () => {
- // ...
+ // ...
});
// And to unregister a listener `removeListener` could be called
web3.provider.removeListener('SUPPORTED_EVENT_NAME', () => {
- // ...
+ // ...
});
```
diff --git a/docs/docs/guides/web3_providers_guide/index.md b/docs/docs/guides/02_web3_providers_guide/index.md
similarity index 74%
rename from docs/docs/guides/web3_providers_guide/index.md
rename to docs/docs/guides/02_web3_providers_guide/index.md
index 726ccd8c229..65e49eb9c00 100644
--- a/docs/docs/guides/web3_providers_guide/index.md
+++ b/docs/docs/guides/02_web3_providers_guide/index.md
@@ -37,14 +37,14 @@ Keep reading to learn more about the different types of providers and how to use
HTTP is a request-response protocol and does not support persistent connection, which means that HTTP providers are not suitable for use cases that require real-time [event subscriptions](/guides/events_subscriptions/).
-``` ts title='Initialize an HTTP Provider'
+```ts title='Initialize an HTTP Provider'
import { Web3, HttpProvider } from 'web3';
// supply an HTTP provider as a URL string
// highlight-next-line
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_ID');
-await web3.eth.getBlockNumber()
+await web3.eth.getBlockNumber();
// ↳ 18849658n
// OR
@@ -53,7 +53,7 @@ await web3.eth.getBlockNumber()
// highlight-next-line
const web3_2 = new Web3(new HttpProvider('https://mainnet.infura.io/v3/YOUR_INFURA_ID'));
-await web3.eth.getBlockNumber()
+await web3.eth.getBlockNumber();
// ↳ 18849658n
```
@@ -65,23 +65,23 @@ HTTP providers can be configured by including an [`HttpProviderOptions`](/api/we
import { Web3, HttpProvider } from 'web3';
const httpOptions = {
- providerOptions: {
- body: undefined,
- cache: 'force-cache',
- credentials: 'same-origin',
- headers: {
- 'Content-Type': 'application/json',
- },
- integrity: undefined,
- keepalive: true,
- method: 'GET',
- mode: 'same-origin',
- redirect: 'error',
- referrer: undefined,
- referrerPolicy: 'same-origin',
- signal: undefined,
- window: undefined,
- } as RequestInit,
+ providerOptions: {
+ body: undefined,
+ cache: 'force-cache',
+ credentials: 'same-origin',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ integrity: undefined,
+ keepalive: true,
+ method: 'GET',
+ mode: 'same-origin',
+ redirect: 'error',
+ referrer: undefined,
+ referrerPolicy: 'same-origin',
+ signal: undefined,
+ window: undefined,
+ } as RequestInit,
};
const web3 = new Web3(new HttpProvider('https://eth.llamarpc.com', httpOptions));
@@ -91,14 +91,14 @@ const web3 = new Web3(new HttpProvider('https://eth.llamarpc.com', httpOptions))
WebSockets support a persistent connection between a client and a server, which means they are suitable for use cases that require real-time [event subscriptions](/guides/events_subscriptions/).
-``` ts title='Initialize WS Provider'
+```ts title='Initialize WS Provider'
import { Web3, WebSocketProvider } from 'web3';
// supply a WebSocket provider as a URL string
// highlight-next-line
const web3 = new Web3('wss://mainnet.infura.io/ws/v3/YOUR_INFURA_ID');
-await web3.eth.getBlockNumber();
+await web3.eth.getBlockNumber();
// ↳ 18849658n
// OR
@@ -118,29 +118,29 @@ The [`WebSocketProvider` constructor](/api/web3-providers-ws/class/WebSocketProv
```ts title='Configuring a WebSocket Provider'
// include both optional parameters
const provider = new WebSocketProvider(
- `ws://localhost:8545`,
- {
- headers: {
- // for node services that require an API key in a header
- 'x-api-key': '',
- },
- },
- {
- delay: 500,
- autoReconnect: true,
- maxAttempts: 10,
- }
+ `ws://localhost:8545`,
+ {
+ headers: {
+ // for node services that require an API key in a header
+ 'x-api-key': '',
+ },
+ },
+ {
+ delay: 500,
+ autoReconnect: true,
+ maxAttempts: 10,
+ },
);
// OR include only ReconnectOptions
const provider = new WebSocketProvider(
- `ws://localhost:8545`,
- {},
- {
- delay: 500,
- autoReconnect: true,
- maxAttempts: 10,
- }
+ `ws://localhost:8545`,
+ {},
+ {
+ delay: 500,
+ autoReconnect: true,
+ maxAttempts: 10,
+ },
);
```
@@ -148,7 +148,7 @@ const provider = new WebSocketProvider(
IPC (inter-process communication) providers offer high-performance local communication and provide a faster alternative to HTTP providers. IPC providers are tailored for efficiency and excel in local environments, and also support real-time [event subscriptions](/guides/events_subscriptions/).
-``` ts title='Initialize IPC Provider'
+```ts title='Initialize IPC Provider'
import { Web3 } from 'web3';
// highlight-next-line
import { IpcProvider } from 'web3-providers-ipc';
@@ -164,37 +164,35 @@ await web3.eth.getBlockNumber();
The [`IpcProvider` constructor](/api/web3-providers-ipc/class/IpcProvider#constructor) accepts two optional parameters that can be used to configure the behavior of the `IpcProvider`: the first parameter must be of type [`SocketConstructorOpts`](https://microsoft.github.io/PowerBI-JavaScript/interfaces/_node_modules__types_node_net_d_._net_.socketconstructoropts.html) and the second parameter must be of type [`ReconnectOptions`](/api/web3/namespace/utils#ReconnectOptions).
-
-
```ts title='Configuring an IPC Provider'
// include both optional parameters
const provider = new IpcProvider(
- '/Users/myuser/Library/Ethereum/geth.ipc',
- {
- writable: false,
- },
- {
- delay: 500,
- autoReconnect: true,
- maxAttempts: 10,
- }
+ '/Users/myuser/Library/Ethereum/geth.ipc',
+ {
+ writable: false,
+ },
+ {
+ delay: 500,
+ autoReconnect: true,
+ maxAttempts: 10,
+ },
);
// OR include only ReconnectOptions
const provider = new IpcProvider(
- '/Users/myuser/Library/Ethereum/geth.ipc',
- {},
- {
- delay: 500,
- autoReconnect: true,
- maxAttempts: 10,
- }
+ '/Users/myuser/Library/Ethereum/geth.ipc',
+ {},
+ {
+ delay: 500,
+ autoReconnect: true,
+ maxAttempts: 10,
+ },
);
```
### Injected Provider
-Injected providers are supplied by an external third-party, most often a wallet or a web browser that is designed to be used with the Ethereum network. In addition to providing network connectivity, injected providers often supply one or more [accounts](/guides/wallet/). Web3.js supports any injected provider that is compliant with [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193). Injected providers support real-time [event subscriptions](/guides/events_subscriptions/). Continue reading for an [example](#injected-provider-1) of using an injected provider.
+Injected providers are supplied by an external third-party, most often a wallet or a web browser that is designed to be used with the Ethereum network. In addition to providing network connectivity, injected providers often supply one or more [accounts](/guides/wallet/index). Web3.js supports any injected provider that is compliant with [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193). Injected providers support real-time [event subscriptions](/guides/events_subscriptions/). Continue reading for an [example](#injected-provider-1) of using an injected provider.
## Provider Origins
@@ -239,36 +237,37 @@ const web3 = new Web3('https://eth-mainnet.alchemyapi.io/v2/your-api-key');
### Injected Provider
-Injected providers are supplied by an external third-party, most often a wallet or a web browser that is designed to be used with the Ethereum network. In addition to providing network connectivity, injected providers often supply one or more [accounts](/guides/wallet/). Web3.js supports any injected provider that is compliant with [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) and has been tested with multiple EIP-1193 providers, including [MetaMask](https://docs.metamask.io/wallet/reference/provider-api/), [Hardhat](https://hardhat.org/hardhat-runner/docs/advanced/hardhat-runtime-environment), and [Incubed (IN3)](https://in3.readthedocs.io/en/develop/index.html).
+Injected providers are supplied by an external third-party, most often a wallet or a web browser that is designed to be used with the Ethereum network. In addition to providing network connectivity, injected providers often supply one or more [accounts](/guides/wallet). Web3.js supports any injected provider that is compliant with [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) and has been tested with multiple EIP-1193 providers, including [MetaMask](https://docs.metamask.io/wallet/reference/provider-api/), [Hardhat](https://hardhat.org/hardhat-runner/docs/advanced/hardhat-runtime-environment), and [Incubed (IN3)](https://in3.readthedocs.io/en/develop/index.html).
:::note
The following example should be run in a browser with the MetaMask extension installed.
:::
```html title='E.g, Metamask'
-
+
```
diff --git a/docs/docs/guides/wallet/index.md b/docs/docs/guides/03_wallet/index.md
similarity index 78%
rename from docs/docs/guides/wallet/index.md
rename to docs/docs/guides/03_wallet/index.md
index ef75a663ec8..d93ba737a50 100644
--- a/docs/docs/guides/wallet/index.md
+++ b/docs/docs/guides/03_wallet/index.md
@@ -1,11 +1,11 @@
---
-sidebar_position: 1
-sidebar_label: 'Introduction to Accounts & Wallets'
+sidebar_position: 3
+sidebar_label: '🔑 Accounts & Wallets'
---
# Introduction to Accounts & Wallets
-The concept of an [account](https://ethereum.org/en/developers/docs/accounts/) is central to Ethereum and it can be used to refer to two types of entities that are native to Ethereum: externally-owned accounts and contract accounts. This document relates _exclusively_ to **externally-owned accounts**. An externally-owned account is associated with a "[key pair](https://ethereum.org/en/developers/docs/accounts/#externally-owned-accounts-and-key-pairs)", which is a general concept that is related to [public-key cryptography](https://en.wikipedia.org/wiki/Public-key_cryptography). The key pair consists of a private key, which must always be kept secret, and a public key, which is used to derive a public identifier (address) for an account. Ethereum accounts have an [ETH](https://ethereum.org/en/developers/docs/intro-to-ethereum/#eth) balance, which can be [transferred](/guides/wallet/transactions) to other accounts or used to pay for interactions with [smart contracts](/guides/smart_contracts/smart_contracts_guide). Anyone with access to an account's private key has the ability to control that account's ETH balance, so it's important that an account's private key is always kept secret. In addition to the general guidelines for [protecting private keys](https://ethereum.org/en/security/#protect-private-keys/), private keys should never be included in client-side code that can be seen by end users and should never be committed to code repositories.
+The concept of an [account](https://ethereum.org/en/developers/docs/accounts/) is central to Ethereum and it can be used to refer to two types of entities that are native to Ethereum: externally-owned accounts and contract accounts. This document relates _exclusively_ to **externally-owned accounts**. An externally-owned account is associated with a "[key pair](https://ethereum.org/en/developers/docs/accounts/#externally-owned-accounts-and-key-pairs)", which is a general concept that is related to [public-key cryptography](https://en.wikipedia.org/wiki/Public-key_cryptography). The key pair consists of a private key, which must always be kept secret, and a public key, which is used to derive a public identifier (address) for an account. Ethereum accounts have an [ETH](https://ethereum.org/en/developers/docs/intro-to-ethereum/#eth) balance, which can be [transferred](/guides/transactions/transactions) to other accounts or used to pay for interactions with [smart contracts](/guides/smart_contracts/smart_contracts_guide). Anyone with access to an account's private key has the ability to control that account's ETH balance, so it's important that an account's private key is always kept secret. In addition to the general guidelines for [protecting private keys](https://ethereum.org/en/security/#protect-private-keys/), private keys should never be included in client-side code that can be seen by end users and should never be committed to code repositories.
In the context of this document, the term "wallet" refers to a collection of accounts and should not be confused with [wallet "applications"](https://ethereum.org/en/wallets/).
@@ -29,7 +29,7 @@ console.log(account);
*/
// use the account to sign a message
-const signature = account.sign("Hello, Web3.js!");
+const signature = account.sign('Hello, Web3.js!');
/* ↳
{
message: 'Hello, Web3.js!',
@@ -48,7 +48,7 @@ In addition to generating new random accounts, the Account package can also be u
```js
// load an existing account from its private key
-const account = web3.eth.accounts.privateKeyToAccount("");
+const account = web3.eth.accounts.privateKeyToAccount('');
console.log(account);
/* ↳
@@ -62,7 +62,7 @@ console.log(account);
*/
// use the account to sign a message
-const signature = account.sign("Hello, Web3.js!");
+const signature = account.sign('Hello, Web3.js!');
/* ↳
{
message: 'Hello, Web3.js!',
@@ -77,30 +77,30 @@ const signature = account.sign("Hello, Web3.js!");
### Account Methods
-The following is a list of [`Accounts`](/libdocs/Accounts) methods in the `web3.eth.accounts` package with descriptions and example usage:
-
-- [create](/libdocs/Accounts#create)
-- [decrypt](/libdocs/Accounts#decrypt)
-- [encrypt](/libdocs/Accounts#encrypt)
-- [hashMessage](/libdocs/Accounts#hashMessage)
-- [parseAndValidatePrivateKey](/libdocs/Accounts#libdocs/Accounts#parseandvalidateprivatekey)
-- [privateKeyToAccount](/libdocs/Accounts#privatekeytoaccount)
-- [privateKeyToAddress](/libdocs/Accounts#privatekeytoaddress)
-- [privateKeyToPublicKey](/libdocs/Accounts#privatekeytopublickey)
-- [recover](/libdocs/Accounts#recover)
-- [recoverTransaction](/libdocs/Accounts#recovertransaction)
-- [sign](/libdocs/Accounts#sign)
-- [signTransaction](/libdocs/Accounts#signtransaction)
+The following is a list of [`Accounts`](/libdocs/Accounts) methods in the `web3.eth.accounts` package with descriptions and example usage:
+
+- [create](/libdocs/Accounts#create)
+- [decrypt](/libdocs/Accounts#decrypt)
+- [encrypt](/libdocs/Accounts#encrypt)
+- [hashMessage](/libdocs/Accounts#hashMessage)
+- [parseAndValidatePrivateKey](/libdocs/Accounts#libdocs/Accounts#parseandvalidateprivatekey)
+- [privateKeyToAccount](/libdocs/Accounts#privatekeytoaccount)
+- [privateKeyToAddress](/libdocs/Accounts#privatekeytoaddress)
+- [privateKeyToPublicKey](/libdocs/Accounts#privatekeytopublickey)
+- [recover](/libdocs/Accounts#recover)
+- [recoverTransaction](/libdocs/Accounts#recovertransaction)
+- [sign](/libdocs/Accounts#sign)
+- [signTransaction](/libdocs/Accounts#signtransaction)
## Wallets
-A Web3.js wallet is a collection of accounts and is represented with the [`Wallet`](/api/web3-eth-accounts/class/Wallet) class. When a wallet is used to track an account, that account is added to an internal context (i.e. [`Web3Context`](/api/web3-core/class/Web3Context/)), which makes it easier to use that account in the future - this is described in more detail in the [transactions tutorial](/guides/wallet/transactions). The following snippet demonstrates creating a wallet with 2 new random accounts and using the second account to sign a message:
+A Web3.js wallet is a collection of accounts and is represented with the [`Wallet`](/api/web3-eth-accounts/class/Wallet) class. When a wallet is used to track an account, that account is added to an internal context (i.e. [`Web3Context`](/api/web3-core/class/Web3Context/)), which makes it easier to use that account in the future - this is described in more detail in the [transactions tutorial](/guides/transactions/transactions). The following snippet demonstrates creating a wallet with 2 new random accounts and using the second account to sign a message:
```js
// create a wallet with 2 new random accounts
const wallet = web3.eth.accounts.wallet.create(2);
-console.log(wallet)
+console.log(wallet);
/* ↳
Wallet(2) [
{
@@ -131,7 +131,7 @@ Wallet(2) [
*/
// use the second account in the wallet to sign a message
-const signature = wallet[1].sign("Hello, Web3.js!");
+const signature = wallet[1].sign('Hello, Web3.js!');
// wallet accounts can also be accessed with the "at" and "get" methods
// wallet.at(1).sign("Hello, Web3.js!")
// wallet.get(1).sign("Hello, Web3.js!")
@@ -154,7 +154,7 @@ In addition to generating new random accounts, a wallet can also be used to load
```js
// create a wallet with a single existing account
-const wallet = web3.eth.accounts.wallet.add("");
+const wallet = web3.eth.accounts.wallet.add('');
console.log(wallet);
/* ↳
@@ -281,23 +281,23 @@ Wallet(3) [
### Wallet Methods
-The following is a list of [`Wallet`](/libdocs/Wallet) methods in the `web3.eth.accounts.wallet` package with description and example usage:
+The following is a list of [`Wallet`](/libdocs/Wallet) methods in the `web3.eth.accounts.wallet` package with description and example usage:
-- [add](/libdocs/Wallet#add)
-- [clear](/libdocs/Wallet#clear)
-- [create](/libdocs/Wallet#create)
-- [decrypt](/libdocs/Wallet#decrypt)
-- [encrypt](/libdocs/Wallet#encrypt)
-- [get](/libdocs/Wallet#get)
-- [load](/libdocs/Wallet#load)
-- [remove](/libdocs/Wallet#remove)
-- [save](/libdocs/Wallet#save)
-- [getStorage](/libdocs/Wallet#getStorage)
+- [add](/libdocs/Wallet#add)
+- [clear](/libdocs/Wallet#clear)
+- [create](/libdocs/Wallet#create)
+- [decrypt](/libdocs/Wallet#decrypt)
+- [encrypt](/libdocs/Wallet#encrypt)
+- [get](/libdocs/Wallet#get)
+- [load](/libdocs/Wallet#load)
+- [remove](/libdocs/Wallet#remove)
+- [save](/libdocs/Wallet#save)
+- [getStorage](/libdocs/Wallet#getStorage)
## Next Steps
This document is just an introduction to Web3.js accounts and wallets. Here are some suggestions for what to review next:
-- Learn how to [transfer ETH](/guides/wallet/transactions) from one account to another.
-- Build a front-end application that uses [injected accounts](/guides/wallet/metamask-vanilla) from the MetaMask wallet.
-- Use an account to [deploy and interact with a smart contract](/guides/smart_contracts/smart_contracts_guide).
+- Learn how to [transfer ETH](/guides/transactions/transactions) from one account to another.
+- Build a front-end application that uses [injected accounts](/guides/dapps/metamask-vanilla) from the MetaMask wallet.
+- Use an account to [deploy and interact with a smart contract](/guides/smart_contracts/smart_contracts_guide).
diff --git a/docs/docs/guides/web3_upgrade_guide/1.x/_category_.yml b/docs/docs/guides/04_transactions/_category_.yml
similarity index 53%
rename from docs/docs/guides/web3_upgrade_guide/1.x/_category_.yml
rename to docs/docs/guides/04_transactions/_category_.yml
index 7723475cb40..99d68c8c3bc 100644
--- a/docs/docs/guides/web3_upgrade_guide/1.x/_category_.yml
+++ b/docs/docs/guides/04_transactions/_category_.yml
@@ -1,5 +1,5 @@
-label: 'Upgrade from 1.x'
+label: '🔄 Transactions'
collapsible: true
collapsed: true
link: null
-position: 1
\ No newline at end of file
+position: 4
diff --git a/docs/docs/guides/wallet/transactions.md b/docs/docs/guides/04_transactions/transactions.md
similarity index 81%
rename from docs/docs/guides/wallet/transactions.md
rename to docs/docs/guides/04_transactions/transactions.md
index dfc92765844..8b830554593 100644
--- a/docs/docs/guides/wallet/transactions.md
+++ b/docs/docs/guides/04_transactions/transactions.md
@@ -1,11 +1,11 @@
---
-sidebar_position: 2
+sidebar_position: 1
sidebar_label: 'Tutorial: Sending Transactions'
---
# Sending Transactions
-This tutorial will walk through the process of using accounts to send transactions on a [development network](https://ethereum.org/en/developers/docs/development-networks/), including how to subscribe to the events associated with a transaction. The topics covered in this tutorial include basic concepts of [Ethereum](https://ethereum.org/), such as [accounts](/guides/wallet/), [denominations of ether](https://ethereum.org/en/developers/docs/intro-to-ether/#denominations), [transactions](https://ethereum.org/en/developers/docs/transactions/), and [gas fees](https://ethereum.org/en/developers/docs/gas/), as well as the basics of the [Hardhat](https://hardhat.org/) development environment.
+This tutorial will walk through the process of using accounts to send transactions on a [development network](https://ethereum.org/en/developers/docs/development-networks/), including how to subscribe to the events associated with a transaction. The topics covered in this tutorial include basic concepts of [Ethereum](https://ethereum.org/), such as [accounts](/guides/wallet), [denominations of ether](https://ethereum.org/en/developers/docs/intro-to-ether/#denominations), [transactions](https://ethereum.org/en/developers/docs/transactions/), and [gas fees](https://ethereum.org/en/developers/docs/gas/), as well as the basics of the [Hardhat](https://hardhat.org/) development environment.
## Overview
@@ -19,7 +19,7 @@ Here is a high-level overview of the steps we will be taking in this tutorial:
6. Send a raw transaction
:::tip
-If you encounter any issues while following this guide or have any questions, don't hesitate to seek assistance. Our friendly community is ready to help you out! Join our [Discord](https://discord.gg/F4NUfaCC) server and head to the **#web3js-general** channel to connect with other developers and get the support you need.
+If you encounter any issues while following this guide or have any questions, don't hesitate to seek assistance. Our friendly community is ready to help you out! Join our [Discord](https://discord.gg/F4NUfaCC) server and head to the **#web3js-general** channel to connect with other developers and get the support you need.
:::
## Step 1: Prerequisites
@@ -105,19 +105,19 @@ The Hardhat development network needs to remain running in the terminal that was
Next, create a new file called `index.js` in your project directory and add the following code to it:
```js
-const { Web3 } = require("web3");
+const { Web3 } = require('web3');
-const web3 = new Web3("http://127.0.0.1:8545/");
+const web3 = new Web3('http://127.0.0.1:8545/');
// Log the chain ID to the console
web3.eth
- .getChainId()
- .then((result) => {
- console.log("Chain ID: " + result);
- })
- .catch((error) => {
- console.error(error);
- });
+ .getChainId()
+ .then(result => {
+ console.log('Chain ID: ' + result);
+ })
+ .catch(error => {
+ console.error(error);
+ });
```
This code sets up a Web3.js connection to the Hardhat development network and logs the chain ID to the console.
@@ -147,51 +147,45 @@ Replace the value of the `privateKey` variable with one of the private keys of t
:::
```js
-const { Web3 } = require("web3");
+const { Web3 } = require('web3');
async function main() {
- const web3 = new Web3("http://127.0.0.1:8545/");
-
- // create a new Web3.js account object with the private key of a Hardhat test account
- const privateKey = "";
- // the account is created with a wallet, which makes it easier to use
- const sender = web3.eth.accounts.wallet.add(privateKey)[0];
-
- // generate a new random Web3.js account object to receive the transaction
- const receiver = web3.eth.accounts.create();
-
- // log initial balances
- console.log(
- "Initial sender balance:",
- // account balance in wei
- await web3.eth.getBalance(sender.address)
- );
- console.log(
- "Initial receiver balance:",
- // account balance in wei
- await web3.eth.getBalance(receiver.address)
- );
-
- // sign and send the transaction
- const receipt = await web3.eth.sendTransaction({
- from: sender.address,
- to: receiver.address,
- // amount in wei
- value: 100,
- });
-
- // log transaction receipt
- console.log(receipt);
-
- // log final balances
- console.log(
- "Final sender balance:",
- await web3.eth.getBalance(sender.address)
- );
- console.log(
- "Final receiver balance:",
- await web3.eth.getBalance(receiver.address)
- );
+ const web3 = new Web3('http://127.0.0.1:8545/');
+
+ // create a new Web3.js account object with the private key of a Hardhat test account
+ const privateKey = '';
+ // the account is created with a wallet, which makes it easier to use
+ const sender = web3.eth.accounts.wallet.add(privateKey)[0];
+
+ // generate a new random Web3.js account object to receive the transaction
+ const receiver = web3.eth.accounts.create();
+
+ // log initial balances
+ console.log(
+ 'Initial sender balance:',
+ // account balance in wei
+ await web3.eth.getBalance(sender.address),
+ );
+ console.log(
+ 'Initial receiver balance:',
+ // account balance in wei
+ await web3.eth.getBalance(receiver.address),
+ );
+
+ // sign and send the transaction
+ const receipt = await web3.eth.sendTransaction({
+ from: sender.address,
+ to: receiver.address,
+ // amount in wei
+ value: 100,
+ });
+
+ // log transaction receipt
+ console.log(receipt);
+
+ // log final balances
+ console.log('Final sender balance:', await web3.eth.getBalance(sender.address));
+ console.log('Final receiver balance:', await web3.eth.getBalance(receiver.address));
}
main();
@@ -241,51 +235,51 @@ Note that the sender's balance has decreased by more than the amount that was tr
In the previous example, the `transaction-receipt.js` script demonstrates sending a transaction to the network and reviewing the results after it has been successfully received. However, there are more stages to the [transaction lifecycle](https://ethereum.org/en/developers/docs/transactions/#transaction-lifecycle) and Web3.js makes it easy to subscribe to these lifecycle stages and create custom handlers for each one. Web3.js supports subscriptions for the following transaction lifecycle events:
-- Sending - Web3.js is preparing to send the transaction to the network
-- Sent - the transaction has been sent to the network
-- Transaction hash - a hash of the transaction has been generated
-- Receipt - the transaction has been included in a block
-- Confirmation - the block in which the transaction was included has been [finalized](https://ethereum.org/en/glossary/#finality)
-- Error - a problem with the transaction was encountered
+- Sending - Web3.js is preparing to send the transaction to the network
+- Sent - the transaction has been sent to the network
+- Transaction hash - a hash of the transaction has been generated
+- Receipt - the transaction has been included in a block
+- Confirmation - the block in which the transaction was included has been [finalized](https://ethereum.org/en/glossary/#finality)
+- Error - a problem with the transaction was encountered
Create a new file called `transaction-events.js` in your project directory and add the following code to it:
```js
-const { Web3 } = require("web3");
+const { Web3 } = require('web3');
-const web3 = new Web3("http://127.0.0.1:8545/");
+const web3 = new Web3('http://127.0.0.1:8545/');
-const privateKey = "";
+const privateKey = '';
const sender = web3.eth.accounts.wallet.add(privateKey)[0];
const receiver = web3.eth.accounts.create();
web3.eth
- .sendTransaction({
- from: sender.address,
- to: receiver.address,
- value: 100,
- })
- .on("sending", (sending) => {
- console.log("Sending:", sending);
- })
- .on("sent", (sent) => {
- console.log("Sent:", sent);
- })
- .on("transactionHash", (transactionHash) => {
- console.log("Transaction Hash:", transactionHash);
- })
- .on("receipt", (receipt) => {
- console.log("Receipt:", receipt);
- })
- .on("confirmation", (confirmation) => {
- console.log("Confirmation:", confirmation);
- process.exit(0);
- })
- .on("error", (error) => {
- console.log("Error:", error);
- process.exit(1);
- });
+ .sendTransaction({
+ from: sender.address,
+ to: receiver.address,
+ value: 100,
+ })
+ .on('sending', sending => {
+ console.log('Sending:', sending);
+ })
+ .on('sent', sent => {
+ console.log('Sent:', sent);
+ })
+ .on('transactionHash', transactionHash => {
+ console.log('Transaction Hash:', transactionHash);
+ })
+ .on('receipt', receipt => {
+ console.log('Receipt:', receipt);
+ })
+ .on('confirmation', confirmation => {
+ console.log('Confirmation:', confirmation);
+ process.exit(0);
+ })
+ .on('error', error => {
+ console.log('Error:', error);
+ process.exit(1);
+ });
```
Execute the following command to run the code from `transaction-events.js`:
@@ -406,37 +400,35 @@ The previous examples have relied on the helpful Web3.js context to automaticall
Create a new file called `raw-transaction.js` in your project directory and add the following code to it:
```js
-const { Web3 } = require("web3");
+const { Web3 } = require('web3');
async function main() {
- const web3 = new Web3("http://127.0.0.1:8545/");
-
- const privateKey = "";
- // import the Hardhat test account without the use of a wallet
- const sender = web3.eth.accounts.privateKeyToAccount(privateKey);
-
- const receiver = web3.eth.accounts.create();
-
- // used to calculate the transaction's maxFeePerGas
- const block = await web3.eth.getBlock();
-
- const transaction = {
- from: sender.address,
- to: receiver.address,
- value: 100,
- // the following two properties must be included in raw transactions
- maxFeePerGas: block.baseFeePerGas * 2n,
- maxPriorityFeePerGas: 100000,
- };
-
- const signedTransaction = await web3.eth.accounts.signTransaction(
- transaction,
- sender.privateKey
- );
- const receipt = await web3.eth.sendSignedTransaction(
- signedTransaction.rawTransaction
- );
- console.log(receipt);
+ const web3 = new Web3('http://127.0.0.1:8545/');
+
+ const privateKey = '';
+ // import the Hardhat test account without the use of a wallet
+ const sender = web3.eth.accounts.privateKeyToAccount(privateKey);
+
+ const receiver = web3.eth.accounts.create();
+
+ // used to calculate the transaction's maxFeePerGas
+ const block = await web3.eth.getBlock();
+
+ const transaction = {
+ from: sender.address,
+ to: receiver.address,
+ value: 100,
+ // the following two properties must be included in raw transactions
+ maxFeePerGas: block.baseFeePerGas * 2n,
+ maxPriorityFeePerGas: 100000,
+ };
+
+ const signedTransaction = await web3.eth.accounts.signTransaction(
+ transaction,
+ sender.privateKey,
+ );
+ const receipt = await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction);
+ console.log(receipt);
}
main();
diff --git a/docs/docs/guides/04_transactions/tx-types.md b/docs/docs/guides/04_transactions/tx-types.md
new file mode 100644
index 00000000000..33152103aec
--- /dev/null
+++ b/docs/docs/guides/04_transactions/tx-types.md
@@ -0,0 +1,279 @@
+---
+sidebar_position: 2
+sidebar_label: 'Transaction Types'
+---
+
+# Transactions
+
+In this tutorial, we will explore how to send different types of [transactions](https://ethereum.org/en/developers/docs/transactions/) using web3.js, focusing on Ethereum's evolving transaction formats. We'll start with [legacy transactions (Transaction Type 0)](#transaction-type-0-legacy). Next, we'll delve into Transaction [Type 1 (EIP-2930)](#transaction-type-1-eip-2930), which introduces access lists to optimize gas usage. Finally, we'll cover [Transaction Type 2 (EIP-1559)](#transaction-type-2-eip-1559), the current default, which allows users to specify maximum fees and priority tips for more efficient and cost-effective transactions. Each section will include practical code examples to demonstrate sending raw transactions and interacting with ERC20 tokens on the Sepolia test network
+
+:::note
+Web3.js uses transaction type 2 by default
+:::
+
+## Transaction Type 0 (Legacy)
+
+### Raw Transaction
+
+A Legacy Transaction refers to a transaction that was created using an older version of Ethereum's transaction format, also known as "transaction type 0". This transaction format was used before the EIP-1559 upgrade, which was implemented in August 2021.
+
+```ts
+import { Web3 } from 'web3';
+
+const web3 = new Web3('https://rpc2.sepolia.org'); // RPC node url
+
+async function txLegacy() {
+ const wallet = web3.eth.wallet.add('YOUR_PRIVATE_KEY'); // make sure you have funds
+
+ const sender = wallet[0].address;
+ const recipient = '0x807BFe4940016B5a7FdA19482042917B02e68359';
+ const value = 1; // wei
+ const nonce = await web3.eth.getTransactionCount(sender);
+ const gas = 21000;
+ const gasPrice = await web3.eth.getGasPrice();
+
+ const tx = {
+ from: sender,
+ to: recipient,
+ value,
+ nonce,
+ gas,
+ gasPrice,
+ // highlight-next-line
+ type: 0,
+ };
+
+ const txReceipt = await web3.eth.sendTransaction(tx);
+ console.log('Tx hash', txReceipt.transactionHash);
+}
+
+txLegacy();
+```
+
+### ERC20 Interaction
+
+```ts
+import { Web3 } from 'web3';
+
+const web3 = new Web3('https://rpc2.sepolia.org');
+
+//WETH token in Sepolia https://sepolia.etherscan.io/address/0xfff9976782d46cc05630d1f6ebab18b2324d6b14#code
+const ADDRESS_WETH_SEPOLIA = '0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14';
+const ABI = [
+ {
+ constant: false,
+ inputs: [
+ {
+ name: 'dst',
+ type: 'address',
+ },
+ {
+ name: 'wad',
+ type: 'uint256',
+ },
+ ],
+ name: 'transfer',
+ outputs: [
+ {
+ name: '',
+ type: 'bool',
+ },
+ ],
+ payable: false,
+ stateMutability: 'nonpayable',
+ type: 'function',
+ },
+];
+
+async function transfer() {
+ //initialize wallet
+ const wallet = web3.eth.accounts.wallet.add('YOUR_PRIVATE_KEY'); //make sure you have WETH tokens in the Sepolia network
+ //you can swap Sepolia tokens for WETH here https://app.uniswap.org/swap?chain=sepolia
+
+ //initialize WETH contract in sepolia
+ const myERC20 = new web3.eth.Contract(ABI, ADDRESS_WETH_SEPOLIA);
+
+ const TO = '0xEA9eEca67682Cd9c6Ce3DdD1681049D7A897289F'; //address to send the tokens to
+ const VALUE = 1; //wei value, dont forget to multiply by decimals
+
+ //send transfer and specify the type
+ const txReceipt = await myERC20.methods.transfer(TO, VALUE).send({
+ from: wallet[0].address,
+ // highlight-next-line
+ type: 0,
+ });
+
+ console.log(txReceipt.transactionHash);
+ //=> 0x5f2087c22166f3a1909c40ce537dd564dc3d4c70c5be02f35c6406a628123b16
+}
+
+transfer();
+```
+
+## Transaction Type 1 (EIP-2930)
+
+This EIP was introduced in April 2021, it introduces a feature called 'Access List.' This improvement allows saving gas on cross-contract calls by declaring in advance which contract and storage slots will be accessed.
+
+### Raw Transaction
+
+```ts
+import { Web3 } from 'web3';
+
+const web3 = new Web3('https://rpc2.sepolia.org');
+
+async function txEIP2930() {
+ const wallet = web3.eth.wallet.add('YOUR_PRIVATE_KEY');
+
+ const sender = wallet[0].address;
+ const contractAddress1 = '0x...';
+ const gas = 500000; //could be higher
+ const gasPrice = await web3.eth.getGasPrice();
+ const data = '0x9a67c8b100000000000000000000000000000000000000000000000000000000000004d0';
+
+ // highlight-start
+ //create access list using web3.eth
+ const accessListData = await web3.eth.createAccessList({
+ from: sender,
+ to: contractAddress1,
+ data,
+ });
+ // highlight-end
+
+ console.log(accessListData);
+ /*
+ =>
+ {
+ // highlight-start
+ "accessList": [
+ {
+ "address": "0x15859bdf5aff2080a9968f6a410361e9598df62f",
+ "storageKeys": [
+ "0x0000000000000000000000000000000000000000000000000000000000000000"
+ ]
+ }
+ ],
+ // highlight-end
+ "gasUsed": "0x7671"
+ }
+ */
+
+ const tx = {
+ from: sender,
+ to: contractAddress1, //the contract we are calling
+ data,
+ gas,
+ gasPrice,
+ // highlight-next-line
+ type: 1,
+ // highlight-next-line
+ accessList: accessListData.accessList, //access the object `accessList`
+ };
+
+ const txReceipt = await web3.eth.sendTransaction(tx);
+
+ console.log('Tx hash', txReceipt.transactionHash);
+}
+
+txEIP2930();
+```
+
+## Transaction Type 2 (EIP-1559)
+
+When a user creates an EIP-1559 transaction, they specify the maximum fee they are willing to pay `maxFeePerGas` as well as a tip `maxPriorityFeePerGas` to incentivize the miner. The actual fee paid by the user is then determined by the network based on the current demand for block space and the priority of the transaction.
+
+### Raw Transaction
+
+```ts
+import { Web3 } from 'web3';
+
+const web3 = new Web3('https://rpc2.sepolia.org');
+
+async function txEIP1559() {
+ const wallet = web3.eth.wallet.add('YOUR_PRIVATE_KEY'); //make sure you have funds
+
+ const sender = wallet[0].address;
+ const recipient = '0x807BFe4940016B5a7FdA19482042917B02e68359';
+ const value = 1; //wei
+ const nonce = await web3.eth.getTransactionCount(sender);
+ const gasLimit = 21000;
+ const maxFeePerGas = Number((await web3.eth.calculateFeeData()).maxFeePerGas);
+ const maxPriorityFeePerGas = Number((await web3.eth.calculateFeeData()).maxPriorityFeePerGas);
+
+ const tx = {
+ from: sender,
+ to: recipient,
+ value,
+ nonce,
+ gasLimit,
+ maxFeePerGas,
+ maxPriorityFeePerGas,
+ // highlight-next-line
+ type: 2,
+ };
+
+ const txReceipt = await web3.eth.sendTransaction(tx);
+ console.log('Tx hash', txReceipt.transactionHash);
+}
+
+txEIP1559();
+```
+
+### ERC20 Interaction
+
+```ts
+import { Web3 } from 'web3';
+
+const web3 = new Web3('https://rpc2.sepolia.org');
+
+//WETH token in Sepolia https://sepolia.etherscan.io/address/0xfff9976782d46cc05630d1f6ebab18b2324d6b14#code
+const ADDRESS_WETH_SEPOLIA = '0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14';
+const ABI = [
+ {
+ constant: false,
+ inputs: [
+ {
+ name: 'dst',
+ type: 'address',
+ },
+ {
+ name: 'wad',
+ type: 'uint256',
+ },
+ ],
+ name: 'transfer',
+ outputs: [
+ {
+ name: '',
+ type: 'bool',
+ },
+ ],
+ payable: false,
+ stateMutability: 'nonpayable',
+ type: 'function',
+ },
+];
+
+async function transfer() {
+ //initialize wallet
+ const wallet = web3.eth.accounts.wallet.add('YOUR_PRIVATE_KEY'); //make sure you have WETH tokens in the Sepolia network
+ //you can swap Sepolia tokens for WETH here https://app.uniswap.org/swap?chain=sepolia
+
+ //initialize WETH contract in sepolia
+ const myERC20 = new web3.eth.Contract(ABI, ADDRESS_WETH_SEPOLIA);
+
+ const TO = '0xEA9eEca67682Cd9c6Ce3DdD1681049D7A897289F'; //address to send the tokens to
+ const VALUE = 1; //wei value, dont forget to multiply by decimals
+
+ //send transfer and specify the type
+ const txReceipt = await myERC20.methods.transfer(TO, VALUE).send({
+ from: wallet[0].address,
+ // highlight-next-line
+ type: 2,
+ });
+
+ console.log(txReceipt.transactionHash);
+ //=> 0x174bc88023be4af431fad1693a59f7a41135238510cdcd00f15f6409b5471d77
+}
+
+transfer();
+```
diff --git a/docs/docs/guides/smart_contracts/_category_.yml b/docs/docs/guides/05_smart_contracts/_category_.yml
similarity index 86%
rename from docs/docs/guides/smart_contracts/_category_.yml
rename to docs/docs/guides/05_smart_contracts/_category_.yml
index 8a1d21c75b4..96b97cea9d2 100644
--- a/docs/docs/guides/smart_contracts/_category_.yml
+++ b/docs/docs/guides/05_smart_contracts/_category_.yml
@@ -2,4 +2,4 @@ label: '📜 Smart Contracts'
collapsible: true
collapsed: true
link: null
-position: 4
+position: 5
diff --git a/docs/docs/guides/smart_contracts/infer_contract_types.md b/docs/docs/guides/05_smart_contracts/infer_contract_types.md
similarity index 82%
rename from docs/docs/guides/smart_contracts/infer_contract_types.md
rename to docs/docs/guides/05_smart_contracts/infer_contract_types.md
index 3e7d4bfc7f1..b5288412522 100644
--- a/docs/docs/guides/smart_contracts/infer_contract_types.md
+++ b/docs/docs/guides/05_smart_contracts/infer_contract_types.md
@@ -7,7 +7,7 @@ sidebar_label: 'Infer Contract Types from JSON Artifact (TypeScript)'
:::tip
📝 This article is for **TypeScript** developers. So, if you are using JavaScript, you do not need to read this.
-However, web3.js version 4.x has been rewritten in TypeScript. And we encorage you to use its strongly-typed features with TypeScript.
+However, web3.js version 4.x has been rewritten in TypeScript. And we encorage you to use its strongly-typed features with TypeScript.
:::
Web3.js is a popular library used for interacting with EVM blockchains. One of its key features is the ability to invoke EVM smart contracts deployed on the blockchain. In this blog post, we will show how to interact with the smart contract in **TypeScript**, with a special focus on how to infer types from JSON artifact files.
@@ -21,14 +21,14 @@ import { Contract, Web3 } from 'web3';
import ERC20 from './node_modules/@openzeppelin/contracts/build/contracts/ERC20.json';
(async function () {
- const web3 = new Web3('rpc url');
+ const web3 = new Web3('rpc url');
- const contract = new Contract(ERC20.abi, '0x7af963cF6D228E564e2A0aA0DdBF06210B38615D', web3);
+ const contract = new Contract(ERC20.abi, '0x7af963cF6D228E564e2A0aA0DdBF06210B38615D', web3);
- const holder = '0xa8F6eB216e26C1F7d924A801E46eaE0CE8ed1A0A';
+ const holder = '0xa8F6eB216e26C1F7d924A801E46eaE0CE8ed1A0A';
- //Error because Contract doesn't know what methods exists
- const balance = await contract.methods.balanceOf(holder).call();
+ //Error because Contract doesn't know what methods exists
+ const balance = await contract.methods.balanceOf(holder).call();
})();
```
@@ -72,19 +72,22 @@ const artifactContent = fs.readFileSync('./artifacts.json', 'utf-8');
const artifacts: string[] = JSON.parse(artifactContent);
(async function () {
- for (const artifact of artifacts) {
- let content;
- try {
- //try to import from node_modules
- content = JSON.stringify(await import(artifact));
- } catch (e) {
- //try to read as path on disc
- content = fs.readFileSync(artifact, 'utf-8');
- }
- const filename = path.basename(artifact, '.json');
- //create and write typescript file
- fs.writeFileSync(path.join(destination, filename + '.ts'), `const artifact = ${content.trimEnd()} as const; export default artifact;`);
- }
+ for (const artifact of artifacts) {
+ let content;
+ try {
+ //try to import from node_modules
+ content = JSON.stringify(await import(artifact));
+ } catch (e) {
+ //try to read as path on disc
+ content = fs.readFileSync(artifact, 'utf-8');
+ }
+ const filename = path.basename(artifact, '.json');
+ //create and write typescript file
+ fs.writeFileSync(
+ path.join(destination, filename + '.ts'),
+ `const artifact = ${content.trimEnd()} as const; export default artifact;`,
+ );
+ }
})();
```
@@ -98,10 +101,12 @@ To use this script, just create an `artifacts.json` file at the root of your pro
]
```
-and run the script with
-```bash
+and run the script with
+
+```bash
node -r ts-node/register
+
+
+
+
+
+
+
+
+
+