Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(docs): quickstart #7062

Merged
merged 1 commit into from
May 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 44 additions & 28 deletions docs/docs/guides/getting_started/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,48 +5,47 @@ sidebar_label: Quickstart

# Quickstart

Use the live code editor to try Web3.js in your browser now! Keep reading to learn how to use Web3.js in a local development environment.

## Live code editor

<iframe width="100%" height="700px" src="https://stackblitz.com/edit/vitejs-vite-aksddx?embed=1&file=main.js&showSidebar=1"></iframe>

## Installation

If NPM is being used as package manager, use the following for installing the web3.js library.
If NPM is being used as package manager, install Web3.js with the following command:

```
npm i web3
```

For installing using yarn package manager:
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, if you only need specific packages, it is recommended to install the specific required packages (e.g, if you want the contract package `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 CJS ( CommonJS ) and native ESM module imports. For importing the main Web3 class in CJS you can use:
Web3.js v4 supports both CommonJS (CJS) and native ECMAScript module (ESM) imports. For importing the main Web3 class in CJS, use:

``` js
const { Web3 } = require('web3');
```

and for ESM style imports, you can use:
For ESM-style imports, use:

``` ts
import { Web3 } from 'web3';
```

## Initialize `Web3` with a provider

Web3.js is in compliance with [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) so any EIP-1193 provider can be injected in web3.js . There are HTTP, WebSocket and IPC providers also available as web3.js packages for using.
[Providers](/guides/web3_providers_guide/) are objects that are responsible for enabling connectivity with the Ethereum network. The `Web3` object must be initialized with a valid provider to function as intended. Web3.js supports [HTTP](/guides/web3_providers_guide/#http-provider), [WebSocket](/guides/web3_providers_guide/#websocket-provider), and [IPC](/guides/web3_providers_guide/#ipc-provider) providers, and exposes packages for working with each type of provider.

:::warning
You must initialize the `Web3` object with a provider, otherwise, you won't be able to fully use web3.js functionalities. Here is an example of creating a `web3` instance with an HTTP provider:
:::
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
import { Web3 } from 'web3';
Expand All @@ -62,7 +61,7 @@ web3.eth.getBlockNumber().then(console.log);
```
## Querying the blockchain

After instantiating the `web3` instance with a `new Web3 provider`, we can access the `web3.eth` package to fetch data from 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:

```ts
// get the balance of an address
Expand All @@ -88,11 +87,13 @@ await web3.eth.getGasPrice();

## Setting up a wallet

If you want to write data/interact with contracts or send transactions on the blockchain, you must have an account with funds to cover the gas fees.
To send transactions to the Ethereum network (e.g. [transferring ETH](/guides/getting_started/quickstart#transfer-eth) or [interacting with smart contracts](/guides/getting_started/quickstart#interact-with-smart-contracts)), it's necessary to use an [account](https://ethereum.org/en/developers/docs/accounts/) with funds to cover [gas fees](https://ethereum.org/en/developers/docs/gas/).

The object `Wallet` is an array of accounts, it will allow you to hold several accounts from which you can send transactions `web3.eth.sendTransaction` or interact with contract objects `web3.eth.contract.methods.contractfunction().send()`, when you perform these actions, the `Wallet` object uses the account/s it holds to send the transactions.
The [`Wallet`](/api/web3-eth-accounts/class/Wallet) object is designed to manage a set of accounts that can be used to send transactions with [`web3.eth.sendTransaction`](/api/web3/class/Web3Eth#sendTransaction) or [`web3.eth.contract.methods.contractfunction().send()`](/api/web3-eth-contract/class/Contract).

### Create random wallet
### Create a random account

Using the `Wallet` to create a random account is a good way to accelerate the development process, but it's not suitable for mainnet or production uses, since random accounts will not have funds to cover gas fees. Use the [`Wallet.create`](/api/web3-eth-accounts/class/Wallet#create) method to create a random account.

```ts
//create random wallet with 1 account
Expand All @@ -118,7 +119,13 @@ Wallet(1)
*/
```

### Add a private key to create a wallet
### Add an account from a private key

Use the [`Wallet.add`](/api/web3-eth-accounts/class/Wallet#add) method to use a private key to add an existing account to a wallet.

:::warning
Private keys are sensitive data and should be treated as such. Make sure that private keys are kept private, which includes making sure they are not committed to code repositories.
:::

```ts
//the private key must start with the '0x' prefix
Expand All @@ -131,9 +138,11 @@ console.log(account[0].privateKey);
//↳ 0x50d349f5cf627d44858d6fcb6fbf15d27457d35c58ba2d5cfeaf455f25db5bec
```

### Send transactions
### Transfer ETH

This is an example of using a private key to add an account to a wallet, and then using that account to transfer ETH:

```ts title='Sending value'
```ts
//add an account to a wallet
const account = web3.eth.accounts.wallet.add('0x50d349f5cf627d44858d6fcb6fbf15d27457d35c58ba2d5cfeaf455f25db5bec');

Expand All @@ -155,15 +164,18 @@ console.log('Tx hash:', txReceipt.transactionHash)

## Interact with smart contracts

[Smart contracts](https://ethereum.org/en/developers/docs/smart-contracts/) are programs that run on the Ethereum network. Keep reading to learn how to use Web3.js to interact with smart contracts.

### Instantiate a contract

The first step to interact with a contract is to instantiate the contract, for which we will need the ABI and the address of the contract
The first step to interacting with a smart contract is to instantiate it, which requires the [ABI](https://docs.soliditylang.org/en/develop/abi-spec.html) and address of the smart contract. The following examples demonstrates instantiating the [Uniswap](https://uniswap.org/) token smart contract:

```ts
//Uniswap token address in mainnet
//Uniswap token smart contract address (mainnet)
const address = '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984'

//you can find the complete ABI in etherscan.io
//https://etherscan.io/address/0x1f9840a85d5af5bf1d1762f925bdaddc4201f984#code
const ABI =
[
{
Expand All @@ -178,11 +190,13 @@ const ABI =
},
];

//instantiate the contract
//instantiate the smart contract
const uniswapToken = new web3.eth.Contract(abi, address);
```

### Read-methods
### Read methods

Since reading data from a smart contract does not consume any gas, it's not necessary to use an account to do so. Here are some examples of reading data from the Uniswap token smart contract:

```ts
//make the call to the contract
Expand All @@ -196,13 +210,11 @@ const totalSupply = await uniswapToken.methods.totalSupply().call();

console.log('Uniswap Total supply:', totalSupply);
// ↳ Uniswap Total Supply: 1000000000000000000000000000n

//use web3 utils to format the units
console.log(web3.utils.fromWei(totalSupply, 'ether'))
// ↳ 1000000000
```

### Writing-methods
### Write methods

Writing data to a smart contract consumes gas and requires the use of an account with funds. The following example demonstrates such an interaction:

```ts
//address to send the token
Expand All @@ -220,6 +232,8 @@ console.log('Tx hash:',txReceipt.transactionHash);

### Query past events

Smart contracts emit [events](https://ethereum.org/en/developers/docs/smart-contracts/anatomy/#events-and-logs) to communicate important interactions. This example demonstrates how to query the Uniswap token smart contract for all `Transfer` events that occurred after a certain block number:

```ts
//get past `Transfer` events from block 18850576
const eventTransfer = await uniswapToken.getPastEvents('Transfer', { fromBlock: 18850576 });
Expand All @@ -229,10 +243,12 @@ console.log(eventTransfer);
//you can only query logs from the previous 100_000 blocks
```

### Listening to live events
### Subscribing to events

:::warning
You MUST initialize the `Web3 provider` with a WebSocket endpoint to subscribe to live events
Web3.js allows user to subscribe to events for real-time notification of important contract interactions. Here is an example of creating a subscription to the Uniswap token's `Transfer` event:

:::note
You MUST initialize the `Web3` object with a [WebSocket](/guides/web3_providers_guide/#websocket-provider) provider to subscribe to live events.
:::

```ts
Expand Down
Loading