### Setup Project and Install Dependencies Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/10_web3_eth/eth.md Essential bash commands to create a new project directory, initialize a Node.js project, install TypeScript and Node.js types, and install the web3.js library. This is crucial for starting any web3.js project. ```bash mkdir web3-eth-tutorial cd web3-eth-tutorial npm init -y npm i typescript @types/node npm i web3 ``` -------------------------------- ### Install Web3.js with npm Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/01_getting_started/quickstart.md Installs the Web3.js library using npm. This command brings in all Web3.js sub-packages. For specific packages, install them individually (e.g., `npm i web3-eth-contract`). ```shell npm i web3 ``` -------------------------------- ### Install web3modal-web3js and web3js Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/07_dapps/web3_modal_guide/index.mdx Installs the necessary packages for integrating Web3modal with web3js using npm. This command ensures you have the required libraries to connect wallets and interact with the blockchain. ```bash npm install web3modal-web3js web3js ``` -------------------------------- ### Install Web3.js with Yarn Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/01_getting_started/quickstart.md Installs the Web3.js library using Yarn. This command brings in all Web3.js sub-packages. For specific packages, install them individually (e.g., `yarn add web3-eth-contract`). ```shell yarn add web3 ``` -------------------------------- ### Install web3-plugin-example using NPM Source: https://github.com/web3/web3.js/blob/4.x/tools/web3-plugin-example/README.md Command to install the web3-plugin-example package using NPM. This is the standard way to add the plugin to your project's dependencies. ```bash npm install web3-plugin-example ``` -------------------------------- ### Run web3.js Gas Estimation Example Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/10_web3_eth/eth.md Command to execute the TypeScript file for estimating gas using Node.js and ts-node. This command compiles and runs the 'estimate.ts' script. ```bash npx ts-node estimate.ts ``` -------------------------------- ### Install Web3.js and Initialize Hardhat Project (Bash) Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/05_smart_contracts/smart_contracts_guide.md Installs the necessary web3 and hardhat packages using npm. Initializes a new Hardhat project, prompting the user to select default options for project setup. ```bash npm i web3 hardhat ``` ```bash npx hardhat init ``` -------------------------------- ### Install web3-plugin-example using Yarn Source: https://github.com/web3/web3.js/blob/4.x/tools/web3-plugin-example/README.md Command to install the web3-plugin-example package using Yarn. This is an alternative method for adding the plugin to your project. ```bash yarn add web3-plugin-example ``` -------------------------------- ### Import web3-eth Directly for Reduced Build Size Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/10_web3_eth/eth.md Demonstrates importing the 'web3-eth' package directly instead of relying on the global 'web3' instance. This approach can lead to a reduction in the overall build size of your application. The example shows how to use the getBalance method from the imported package. ```typescript import { Web3Eth } from 'web3-eth'; const eth = new Web3Eth('http://localhost:7545'); async function test() { const accounts = await eth.getAccounts(); const currentBalance = await eth.getBalance(accounts[0]); console.log('Current balance:', currentBalance); // 115792089237316195423570985008687907853269984665640564039437613106102441895127n } (async () => { await test(); })(); ``` -------------------------------- ### Run web3.js Send Signed Transaction Example Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/10_web3_eth/eth.md Command to execute the TypeScript file for signing and sending transactions using Node.js and ts-node. This command compiles and runs the 'sendSigned.ts' script. ```bash npx ts-node sendSigned.ts ``` -------------------------------- ### HttpProvider Options: v1.x Example Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/15_web3_upgrade_guide/providers_migration_guide.md Provides a concrete example of how to structure options for the HttpProvider in web3.js v1.x, demonstrating the use of keep-alive, timeouts, and custom headers. ```javascript let httpOptions = { keepAlive: true, withCredentials: false, timeout: 20000, // ms headers: [ { name: 'Access-Control-Allow-Origin', value: '*' }, ], agent: { http: http.Agent(...), baseUrl: '' } }; ``` -------------------------------- ### Web3.js 1.x IpcProvider Path Example Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/15_web3_upgrade_guide/providers_migration_guide.md Demonstrates how to instantiate the IpcProvider in Web3.js version 1.x, showing platform-specific IPC paths for Ethereum nodes. ```javascript var net = require('net'); new Web3.providers.IpcProvider('/Users/myuser/Library/Ethereum/geth.ipc', net); // mac os path // on windows the path is: "\\\\.\\pipe\\geth.ipc" // on linux the path is: "/users/myuser/.ethereum/geth.ipc" ``` -------------------------------- ### Use a web3.js Plugin Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/14_web3_plugin_guide/index.mdx Shows how to integrate a custom plugin into a web3.js instance. This involves importing the plugin, initializing Web3, registering the plugin using `web3.registerPlugin()`, and then accessing its methods via the defined namespace. ```javascript //1. import the plugin and web3 module import { Web3 } from "web3"; import MyPlugin from "./plugin"; //2. Initialize the web3 instance const web3 = new Web3("https://eth.llamarpc.com"); //3. Register plugin to add the current Web3Context web3.registerPlugin(new MyPlugin()); //4. Use the plugin methods web3.pluginExample.doSomething(); //--> Hello web3! ``` -------------------------------- ### Create a web3.js Plugin Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/14_web3_plugin_guide/index.mdx Demonstrates the basic structure for creating a custom web3.js plugin. It involves extending `Web3PluginBase`, defining a unique `pluginNamespace`, and implementing custom methods for extended functionality. ```javascript //1. import the `Web3PluginBase` module import { Web3PluginBase } from "web3"; //2. Create a Class extending the `Web3Pluginbase` class MyPlugin extends Web3PluginBase { //3. Add a name to the plugin pluginNamespace = "pluginExample"; //4. Create any methods with your desired functionality async doSomething(){ console.log("Hello web3!"); //send transactions //initialize contracts //deploy or interact with contracts //add your own library, logic or functionality //much more... } } module.exports = MyPlugin; ``` -------------------------------- ### Write to Smart Contract Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/01_getting_started/quickstart.md Demonstrates how to send a transaction to a smart contract to perform a write operation, such as transferring tokens. This requires an account with funds and consumes gas. The example shows sending tokens and logging the transaction hash. ```ts // address to send the token const to = '0xcf185f2F3Fe19D82bFdcee59E3330FD7ba5f27ce'; // value to transfer (1 with 18 decimals) 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 }); console.log('Tx hash:', txReceipt.transactionHash); // ↳ Tx hash: 0x14273c2b5781cc8f1687906c68bfc93482c603026d01b4fd37a04adb6217ad43 ``` -------------------------------- ### Transfer ETH using Account Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/01_getting_started/quickstart.md This example shows how to create a transaction object to send Ether from an account previously added to the wallet. It then sends the transaction using `web3.eth.sendTransaction` and logs the transaction hash. ```ts // add an account to a wallet 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'), }; // 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); // ↳ Tx hash: 0x03c844b069646e08af1b6f31519a36e3e08452b198ef9f6ce0f0ccafd5e3ae0e ``` -------------------------------- ### Run TypeScript File Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/10_web3_eth/eth.md Command to execute a TypeScript file using ts-node, allowing for direct execution of TypeScript code without manual compilation to JavaScript. ```bash npx ts-node index.ts ``` -------------------------------- ### Initialize Web3 with Provider Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/01_getting_started/quickstart.md Initializes the Web3 instance with an Ethereum network provider. Web3.js is compliant with EIP-1193, allowing any EIP-1193 provider to be used. This example shows initialization with a private RPC endpoint. ```ts import { Web3 } from 'web3'; // 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'); web3.eth.getBlockNumber().then(console.log); // ↳ 18849658n ``` -------------------------------- ### Interact with Smart Contracts Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/14_web3_plugin_guide/index.mdx Demonstrates initializing a smart contract instance using its ABI and address. It covers interacting with read-only functions using `.call()` and write functions using `.send()`. Sending transactions requires prior wallet initialization. ```js import { Web3PluginBase, Contract } from 'web3'; class MyPlugin extends Web3PluginBase { pluginNamespace = 'pluginExample'; async interactWithContract() { //1. Initialize contract const myContract = new Contract(ABI, ADDRESS); //2. Interact with reading functions const response = myContract.methods.doSomething().call(); //3. Interact with writing functions //You must initialize a wallet to be able to send the TX from wallet[0].address const txReceipt = myContract.methods.doSomething().send({from: wallet[0].address}) } } export default MyPlugin; ``` -------------------------------- ### Web3 Configuration Parameters Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/14_web3_plugin_guide/index.mdx Illustrates how to configure web3.js instances by modifying properties on the `this.config` object. This allows customization of behaviors like handling transaction reverts and setting default transaction types. ```js import { Web3PluginBase } from 'web3'; class MyPlugin extends Web3PluginBase { pluginNamespace = 'pluginExample'; async configParams() { this.config.handleRevert = true; this.config.defaultTransactionType = 0x1; //more params... } } // Refer to https://docs.web3js.org/guides/web3_config/index for all config params. ``` -------------------------------- ### Use web3.js Accounts Module in Plugin Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/14_web3_plugin_guide/index.mdx Shows how to use the `eth.accounts` submodule within a web3.js plugin to create new Ethereum accounts. The output includes the account's address, private key, and available signing methods. ```javascript import { Web3PluginBase, eth } from 'web3'; class MyPlugin extends Web3PluginBase { pluginNamespace = 'pluginExample'; async createAccount() { const account = eth.accounts.create(); console.log("account:", account); /* account: { address: '0x59E797F2F66AffA9A419a6BC2ED4742b7cBc2570', privateKey: '0x52a81fc3a7fd6ce9644147c9fb5bfbe1f708f37b4611b3c3310eb9a6dc85ccf4', signTransaction: [Function: signTransaction], sign: [Function: sign], encrypt: [Function: encrypt] } */ } } export default MyPlugin; ``` -------------------------------- ### Create Tutorial Directory Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/07_dapps/metamask-vanilla.md Sets up the project environment by creating a new directory for the tutorial and navigating into it using standard bash commands. This prepares your workspace for the subsequent steps. ```bash mkdir web3js-metamask-tutorial cd web3js-metamask-tutorial ``` -------------------------------- ### Use web3.js Utils Module in Plugin Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/14_web3_plugin_guide/index.mdx Demonstrates the usage of the `utils` module within a web3.js plugin. This example shows a common utility function, `utils.fromWei`, for converting currency values from Wei to Ether. ```javascript import { Web3PluginBase, utils } from 'web3'; class MyPlugin extends Web3PluginBase { pluginNamespace = 'pluginExample'; weiToEth(value) { //`this` is the web3context used when you register the plugin in the usage return utils.fromWei(value, 'ether'); } //more web3.eth. methods... } export default MyPlugin; ``` -------------------------------- ### Instantiate Smart Contract Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/01_getting_started/quickstart.md Demonstrates how to instantiate a smart contract object by providing its ABI and address. This is the first step to interacting with any smart contract, allowing calls to its methods. ```ts // Uniswap token smart contract address (Mainnet) 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', }, ]; // instantiate the smart contract const uniswapToken = new web3.eth.Contract(ABI, address); ``` -------------------------------- ### Querying Blockchain Data Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/01_getting_started/quickstart.md Demonstrates how to use the `web3-eth` package to fetch various data points from the Ethereum network after instantiating the Web3 instance. ```ts // get the balance of an address await web3.eth.getBalance('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'); // ↳ 114438180989009447638n // get last block number await web3.eth.getBlockNumber(); // ↳ 18849658n // get the chain id of the current provider await web3.eth.getChainId(); // ↳ 1n // get the nonce of an address await web3.eth.getTransactionCount('0x37826D8B5F4B175517A0f42c886f8Fca38C55Fe7'); // ↳ 7n // get the current gas price await web3.eth.getGasPrice(); // ↳ 23879160756n ``` -------------------------------- ### Execute Transaction Script Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/10_web3_eth/eth.md This command executes the TypeScript transaction script using `ts-node`, which compiles and runs TypeScript code directly. It's used to initiate the Ether transaction example against a local Ethereum network. ```bash npx ts-node transaction.ts ``` -------------------------------- ### Start Hardhat Development Network (Bash) Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/05_smart_contracts/smart_contracts_guide.md Starts the Hardhat development network, which provides a local Ethereum environment. It outputs the RPC URL and available test accounts for connecting to the network. ```bash npx hardhat node ``` -------------------------------- ### Send EIP-1559 Transaction with web3.js Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/10_web3_eth/eth.md Illustrates how to send an EIP-1559 compliant transaction using web3.js. This type of transaction (type: 2) introduces new fee parameters like `maxFeePerGas` and `maxPriorityFeePerGas` for more predictable fee structures. The example shows setting up the transaction object and sending it. ```typescript import { Web3 } from 'web3'; const web3 = new Web3('http://localhost:8545'); async function test() { const privateKey = 'YOUR PRIVATE KEY HERE'; // add private key to wallet to have auto-signing transactions feature const account = web3.eth.accounts.privateKeyToAccount(privateKey); web3.eth.accounts.wallet.add(account); // create transaction object const tx = { from: account.address, to: '0x27aa427c1d668ddefd7bc93f8857e7599ffd16ab', value: '0x1', gasLimit: BigInt(21000), type: BigInt(2), // <- specify type // maxFeePerGas - you can specify this property directly or web3js will fill this field automatically // maxPriorityFeePerGas - you can specify this property directly or web3js will fill this field automatically }; // send transaction const receipt = await web3.eth.sendTransaction(tx); console.log('Receipt:', receipt); // Receipt: { // blockHash: '0xfe472084d1471720b6887071d32a793f7c4576a489098e7d2a89aef205c977fb', // blockNumber: 23n, // cumulativeGasUsed: 21000n, // effectiveGasPrice: 2546893579n, // from: '0xe2597eb05cf9a87eb1309e86750c903ec38e527e', // gasUsed: 21000n, // logs: [], // logsBloom: '0x0000...00000000000', // status: 1n, // to: '0x27aa427c1d668ddefd7bc93f8857e7599ffd16ab', // transactionHash: '0x5c7a3d2965b426a5776e55f049ee379add44652322fb0b9fc2f7f57b38fafa2a', // transactionIndex: 0n, // type: 2n // } } (async () => { await test(); })(); ``` -------------------------------- ### Send Legacy Ethereum Transaction with Web3.js (TypeScript) Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/10_web3_eth/eth.md This snippet demonstrates how to send a legacy transaction using Web3.js. It covers account setup, transaction object creation with explicit gas price and limit, and sending the transaction. Ensure you have a running Ethereum node and a valid private key. ```typescript import { Web3 } from 'web3'; const web3 = new Web3('http://localhost:8545'); async function test() { const privateKey = 'YOUR PRIVATE KEY HERE'; // add private key to wallet to have auto-signing transactions feature const account = web3.eth.accounts.privateKeyToAccount(privateKey); web3.eth.accounts.wallet.add(account); // create transaction object const tx = { from: account.address, to: '0x27aa427c1d668ddefd7bc93f8857e7599ffd16ab', value: '0x1', gas: BigInt(21000), gasPrice: await web3.eth.getGasPrice(), type: BigInt(0), // <- specify type }; // send transaction const receipt = await web3.eth.sendTransaction(tx); console.log('Receipt:', receipt); // Receipt: { // blockHash: '0xc0f2fea359233b0843fb53255b8a7f42aa7b1aff53da7cbe78c45b5bac187ad4', // blockNumber: 21n, // cumulativeGasUsed: 21000n, // effectiveGasPrice: 2569891347n, // from: '0xe2597eb05cf9a87eb1309e86750c903ec38e527e', // gasUsed: 21000n, // logs: [], // logsBloom: '0x0...00000', // status: 1n, // to: '0x27aa427c1d668ddefd7bc93f8857e7599ffd16ab', // transactionHash: '0x0ffe880776f5631e4b64caf521bd01cd816dd2cc29e533bc56f392211856cf9a', // transactionIndex: 0n, // type: 0n // } } (async () => { await test(); })(); ``` -------------------------------- ### Initialize Node.js Project (Bash) Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/05_smart_contracts/smart_contracts_guide.md Creates a new project directory, navigates into it, and initializes a new Node.js project with a default `package.json` file. This sets up the basic structure for a Node.js application. ```bash mkdir smart-contract-tutorial cd smart-contract-tutorial npm init -y ``` -------------------------------- ### Setup Web3 and ENS Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/11_ens/index.md Demonstrates setting up the Web3 instance with a provider and accessing the ENS functionality through the web3.eth.ens object. It shows how to initialize Web3 and immediately use an ENS method like getAddress. ```typescript import Web3 from 'web3'; // Assuming you have a provider, replace 'http://localhost:8545' with your Web3 provider const web3 = new Web3('http://localhost:8545'); // You can use ENS with web3 object: const ens = await web3.eth.ens.getAddress('alice.eth'); ``` -------------------------------- ### Install web3.js Utils Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/12_web3_utils_module/index.md Instructions for installing the web3-utils package or the full web3 library via npm. ```bash npm i web3-utils ``` ```bash npm i web3 ``` -------------------------------- ### Add Account from Private Key Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/01_getting_started/quickstart.md Demonstrates adding an account to the web3.js wallet using a private key. The method returns an array of accounts, and this snippet shows how to access the address and private key of the first added account. ```ts const account = web3.eth.accounts.wallet.add( '0x50d349f5cf627d44858d6fcb6fbf15d27457d35c58ba2d5cfeaf455f25db5bec' ); console.log(account[0].address); //↳ 0xcE6A5235d6033341972782a15289277E85E5b305 console.log(account[0].privateKey); //↳ 0x50d349f5cf627d44858d6fcb6fbf15d27457d35c58ba2d5cfeaf455f25db5bec ``` -------------------------------- ### Connect to Ganache and Get Block Number Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/10_web3_eth/eth.md TypeScript code to establish a connection to a local Ganache network using HttpProvider and retrieve the current block number. It demonstrates basic interaction with the Ethereum blockchain via web3.js. ```typescript import { Web3 } from 'web3'; // Set up a connection to the Ganache network const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545')); /* NOTE: instead of using ganache, you can also interact with a testnet/mainnet using another provider https://app.infura.io/ https://dashboard.alchemy.com/ or use a public provider https://chainlist.org/ */ // Log the current block number to the console const block = await web3.eth.getBlockNumber(); console.log('Last block:', block); ``` -------------------------------- ### Install Plugin Dependency Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/14_web3_plugin_guide/plugin_users.md Demonstrates how to add a web3.js plugin as a dependency in your project's package.json file using yarn. ```json { "dependencies": { "web3-plugin-example": "0.1.0" } } ``` -------------------------------- ### Install and Initialize Hardhat Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/08_hardhat_tutorial/index.md Commands to install the Hardhat development environment and initialize a new project, setting up the basic project structure. ```bash npm install hardhat npx hardhat init ``` -------------------------------- ### Web3.js Default Common Configuration Example Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/09_web3_config/index.md Demonstrates how to set defaultCommon, defaultHardfork, and defaultChain properties in web3.js for configuring smart contract transactions. ```javascript import { Web3, Hardfork } from 'web3'; const web3 = new Web3('http://127.0.0.1:7545'); web3.defaultHardfork = 'berlin'; web3.defaultChain = 'goerli'; web3.defaultCommon = { baseChain: 'goerli', hardfork: 'berlin' as Hardfork, customChain: { networkId: 1, chainId: 1, }, }; console.log(web3.getContextObject().config); ``` -------------------------------- ### Registering a Plugin with Web3Context Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/14_web3_plugin_guide/plugin_authors.md Example of how a user registers a custom plugin with the `Web3Context`. It shows instantiating `Web3Context`, registering the plugin, and then calling a plugin method. ```typescript // registering_a_plugin.ts import { Web3Context } from 'web3'; import { CustomRpcMethodsPlugin } from './custom_rpc_methods_plugin'; const web3Context = new Web3Context('http://127.0.0.1:8545'); web3Context.registerPlugin(new CustomRpcMethodsPlugin()); await web3Context.customRpcMethods.someMethod(); ``` -------------------------------- ### Web3.js v4 Catching Reconnect Error Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/15_web3_upgrade_guide/providers_migration_guide.md Provides an example of how to catch errors related to maximum reconnect attempts in Web3.js v4 when auto-reconnect is enabled. ```typescript provider.on('error', error => { if (error.message.startsWith('Maximum number of reconnect attempts reached!')) { // the `error.message` will be `Maximum number of reconnect attempts reached! (${maxAttempts})` // the `maxAttempts` is equal to the provided value by the user, or the default value `5`. } }); ``` -------------------------------- ### Install Solidity Compiler (solc) Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/05_smart_contracts/smart_contracts_guide.md Installs the `solc` package, a JavaScript wrapper for the Solidity compiler. Ensure the version matches your `pragma solidity` directive. This is a prerequisite for compiling contracts. ```bash npm i solc@^0.8.0 ``` -------------------------------- ### Import Specific web3-eth Package Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/13_advanced/tree_shaking.md Import only the necessary modules from 'web3-eth' to leverage tree shaking. This example shows importing `Web3Eth` for both JavaScript and TypeScript. ```javascript const { Web3Eth } = require('web3-eth'); // ... ``` ```typescript import { Web3Eth } from 'web3-eth'; // ... ``` -------------------------------- ### Subscribing to Contract Events in Web3.js Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/01_getting_started/quickstart.md Demonstrates how to subscribe to contract events using Web3.js. This example shows setting up a WebSocket provider, instantiating a contract, and listening for 'Transfer' events. Requires a WebSocket provider and contract ABI/address. Outputs event data to the console. HTTP providers are not supported for subscriptions. ```typescript import { Web3 } from 'web3'; // WebSocket provider const web3 = new Web3('wss://ethereum.publicnode.com'); // instantiate contract // 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); // ↳ [{...},{...}, ...] live events will be printed in the console // Placeholder for actual contract interaction as abi and address are not provided console.log('Web3.js event subscription example setup.'); console.log('Replace abi and address with actual contract details.'); console.log('Ensure a WebSocket provider is used.'); ``` -------------------------------- ### Check Node.js and npm Versions Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/07_dapps/metamask-react.md Verifies the installed versions of Node.js and npm, which are prerequisites for the project setup. Displays the output of `node -v` and `npm -v` commands. ```bash $: node -v # your version may be different, but it's best to use the current stable version v18.16.1 $: npm -v 9.5.1 ``` -------------------------------- ### Create a Random Account Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/01_getting_started/quickstart.md Uses the `Wallet` object to create a random account for development purposes. Note: This is not suitable for mainnet or production use due to the lack of funds for gas fees. The `Wallet.create` method generates an account with an address and private key. ```ts // create random wallet with 1 account web3.eth.accounts.wallet.create(1); /* ↳ Wallet(1) [ { address: '0xcE6A5235d6033341972782a15289277E85E5b305', privateKey: '0x50d349f5cf627d44858d6fcb6fbf15d27457d35c58ba2d5cfeaf455f25db5bec', signTransaction: [Function: signTransaction], sign: [Function: sign], encrypt: [Function: encrypt] }, _accountProvider: { create: [Function: createWithContext], privateKeyToAccount: [Function: privateKeyToAccountWithContext], decrypt: [Function: decryptWithContext] }, _addressMap: Map(1) { '0xce6a5235d6033341972782a15289277e85e5b305' => 0 }, _defaultKeyName: 'web3js_wallet' ] */ ``` -------------------------------- ### Plugin package.json Dependencies Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/14_web3_plugin_guide/plugin_authors.md Specifies peer dependency on web3.js for plugin compatibility. This ensures the plugin utilizes the user's installed web3.js version, adhering to version constraints. ```json { "name": "web3-plugin-custom-rpc-methods", "version": "0.1.0", "peerDependencies": { "web3": ">= 4.0.2 < 5" } } ``` -------------------------------- ### Import Specific web3-utils Functions Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/13_advanced/tree_shaking.md Import specific utility functions from 'web3-utils' to minimize bundle size. This example shows importing `numberToHex` and `hexToNumber` for both JavaScript and TypeScript. ```javascript const { numberToHex, hexToNumber } = require('web3-utils'); // ... ``` ```typescript import { numberToHex, hexToNumber } from 'web3-utils'; // ... ``` -------------------------------- ### WebSocketProvider: Manual Disconnect Example Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/15_web3_upgrade_guide/providers_migration_guide.md Demonstrates how to manually disconnect from a WebSocket provider in web3.js to properly close the connection and terminate the program. This is necessary in v4 when the program should not run indefinitely. ```javascript const web3 = new Web3(wsUrl); // When you are ready to terminate your program web3.currentProvider?.disconnect(); // The program will now terminate ``` -------------------------------- ### Resolve ENS Names Source: https://github.com/web3/web3.js/blob/4.x/docs/docs/guides/14_web3_plugin_guide/index.mdx Shows how to use the ENS utility to resolve Ethereum Name Service (ENS) names to their corresponding addresses. The ENS utility is initialized with a web3 context. ```js import { Web3PluginBase } from "web3"; import { ENS } from "web3-eth-ens"; class MyPlugin extends Web3PluginBase { pluginNamespace = "pluginExample"; async getAddressENS() { const ens = new ENS(undefined, this); //link to current web3Context return ens.getAddress("ethereum.eth"); } } ```