### Setup react-native-quick-crypto for iOS Source: https://docs.web3js.org/guides/resources_and_troubleshooting Run `pod install` in the `ios` directory after installing `react-native-quick-crypto` to link the native dependencies for iOS. ```bash cd ios && pod install ``` -------------------------------- ### Start the React Development Server Source: https://docs.web3js.org/guides/dapps/metamask-react This command starts the development server for your React application. Ensure MetaMask is installed and unlocked in the browser where the app will open. ```bash npm start ``` -------------------------------- ### Install Viem Source: https://docs.web3js.org/guides/migration_viem Install the Viem package to begin the migration process. ```bash npm install viem@2 ``` -------------------------------- ### Install Web3Modal and Web3.js Source: https://docs.web3js.org/guides/dapps/web3_modal_guide Install the necessary packages for Web3Modal and Web3.js using npm. This is the first step before implementation. ```bash npm install web3modal-web3 web3js ``` -------------------------------- ### web3.eth.getProof Example Source: https://docs.web3js.org/guides/web3_upgrade_guide/web3_eth_migration_guide This example demonstrates the expected output format for web3.eth.getProof, showing the key, value, and proof array for different entries. ```javascript // { // key: '0x0000000000000000000000000000000000000000000000000000000000000000', // value: '0x736f6c79656e7420677265656e2069732070656f706c6500000000000000002e', // proof: [Array] // }, // { // key: '0x0000000000000000000000000000000000000000000000000000000000000001', // value: '0x0', // proof: [Array] // } // ] // } ``` -------------------------------- ### Install Ethers.js Source: https://docs.web3js.org/guides/migration_ethers Install the ethers.js package to begin the migration process. ```bash npm install ethers@6 ``` -------------------------------- ### Install Web3.js with NPM Source: https://docs.web3js.org/guides/getting_started/quickstart Install the Web3.js library using NPM for your project. This command installs all sub-packages. ```bash npm i web3 ``` -------------------------------- ### Import and Use Web3Eth Directly Source: https://docs.web3js.org/guides/web3_eth/eth Import the Web3Eth package directly to reduce build size. This example shows how to get account balances. ```javascript 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(); })(); ``` -------------------------------- ### Get Account and Storage Proofs with Custom Formatting Source: https://docs.web3js.org/api/web3-eth/class/Web3Eth This example demonstrates how to retrieve account and storage proofs with custom formatting for numbers and bytes. By setting `bytes: FMT_BYTES.HEX` and `number: FMT_NUMBER.NUMBER`, you ensure the output is in hexadecimal for bytes and as a BigNumber for numbers. Passing `undefined` for the block parameter defaults to the latest state. ```javascript web3.eth.getProof( "0x1234567890123456789012345678901234567890", ["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001"], undefined, { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } ).then(console.log); ``` -------------------------------- ### Start Local HTTP Server Source: https://docs.web3js.org/guides/dapps/metamask-vanilla This command starts a local HTTP server to serve your project files. Ensure you run this in your project directory. The server will automatically refresh the webpage upon detecting changes. ```bash npx watch-http-server . ``` -------------------------------- ### Install web3.js Source: https://docs.web3js.org/guides/ens Install web3.js version 4 in your project using npm. ```bash npm install web3 ``` -------------------------------- ### Install Web3.js and Hardhat Source: https://docs.web3js.org/guides/smart_contracts/smart_contracts_guide Installs the necessary packages for Web3.js and Hardhat development. ```bash npm i web3 hardhat ``` -------------------------------- ### Install Web3.js with Yarn Source: https://docs.web3js.org/guides/getting_started/quickstart Install the Web3.js library using Yarn for your project. This command installs all sub-packages. ```bash yarn add web3 ``` -------------------------------- ### Install Solidity Compiler (solc) Source: https://docs.web3js.org/guides/smart_contracts/smart_contracts_guide Install the solc package using npm. Ensure the version is compatible with your Solidity code's pragma directive. ```bash npm i solc@^0.8.0 ``` -------------------------------- ### Install Web3.js and Hardhat Source: https://docs.web3js.org/guides/transactions/transactions Install the necessary packages, Web3.js and Hardhat, using npm. These are required for interacting with the blockchain and setting up the development environment. ```bash npm i web3 hardhat ``` -------------------------------- ### Create Tutorial Directory Source: https://docs.web3js.org/guides/dapps/metamask-vanilla Create a new directory for the tutorial and navigate into it. This sets up the project structure. ```bash mkdir web3js-metamask-tutorial cd web3js-metamask-tutorial ``` -------------------------------- ### Initialize and Set Up Web3.js dApp Source: https://docs.web3js.org/guides/dapps/lightweight-dapp Install the create-web3js-dapp utility globally, initialize a new minimal React dApp, and navigate into the project directory. This sets up the basic structure for your dApp. ```bash npm install -g create-web3js-dapp npx create-web3js-dapp --framework react --template minimal cd web3js-react-dapp-min ``` -------------------------------- ### Get Network ID using web3-net Package Source: https://docs.web3js.org/api/web3/class/Net Install the 'web3-net' package and instantiate the Net class directly with your provider URL to get the network ID. ```javascript import {Net} from 'web3-net'; const net = new Net('https://mainnet.infura.io/v3/'); console.log(await net.getId()); ``` -------------------------------- ### Initialize React Project and Add Dependencies Source: https://docs.web3js.org/guides/dapps/intermediate-dapp Set up a new React project with TypeScript and install necessary libraries like Web3.js and Hardhat. ```bash npx create-react-app web3-intermediate-dapp --template typescript cd web3-intermediate-dapp npm i web3 npm i -D hardhat ``` -------------------------------- ### Create and Navigate to Project Directory Source: https://docs.web3js.org/guides/smart_contracts/smart_contracts_guide Create a new directory for your smart contract project and navigate into it using the command line. ```bash mkdir smart-contract-tutorial cd smart-contract-tutorial ``` -------------------------------- ### Using personal.getAccounts() from web3-eth-personal Source: https://docs.web3js.org/libdocs/Personal This example shows how to get accounts using the dedicated `web3-eth-personal` package. ```APIDOC ## Using personal.getAccounts() from web3-eth-personal ### Description Retrieves a list of accounts from the Ethereum node using the `Personal` class from `web3-eth-personal`. ### Method ``` personal.getAccounts() ``` ### Parameters None ### Response #### Success Response - `Array`: A list of Ethereum account addresses. ### Request Example ```javascript import { Personal } from 'web3-eth-personal'; const personal = new Personal('http://127.0.0.1:7545'); console.log(await personal.getAccounts()); ``` ``` -------------------------------- ### Get Node Version Source: https://docs.web3js.org/libdocs/Web3Eth Example of retrieving the version of the Ethereum node software. This can be helpful for debugging and compatibility checks. ```javascript web3.eth.getNodeInfo().then(console.log); ``` -------------------------------- ### Get Gas Price Source: https://docs.web3js.org/libdocs/Web3Eth Example of retrieving the current gas price on the network. This is essential for estimating transaction fees. ```javascript web3.eth.getGasPrice().then(console.log); ``` -------------------------------- ### Set up web3 and ENS Source: https://docs.web3js.org/guides/ens Initialize web3 and access the ENS functionality. Ensure you replace the provider URL with your actual Web3 provider. ```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'); ``` -------------------------------- ### Get Balance Source: https://docs.web3js.org/libdocs/Web3Eth Example of retrieving the Ether balance of a specific account. This is a fundamental operation for checking account funds. ```javascript web3.eth.getBalance("0x0000000000000000000000000000000000000000").then(console.log); ``` -------------------------------- ### Get Transaction Source: https://docs.web3js.org/libdocs/Web3Eth Example of retrieving details of a specific transaction using its hash. This provides information about the transaction before it was mined. ```javascript web3.eth.getTransaction("0x95222290dd544201079744315052409217339714073784306917207940132132").then(function(tx){ console.log(tx); }); ``` -------------------------------- ### Initialize and Use Wallet for Transactions Source: https://docs.web3js.org/libdocs/Wallet Demonstrates initializing a wallet with multiple accounts and using an account to sign data and send a transaction. Ensure accounts are funded before sending transactions. ```javascript import { Web3 } from 'web3'; const web3 = new Web3('http://127.0.0.1:7545'); const wallet = await web3.eth.accounts.wallet.create(2); const signature = wallet.at(0).sign("Test Data"); // use wallet // fund account before sending following transaction ... const receipt = await web3.eth.sendTransaction({ // internally sign transaction using wallet from: wallet.at(0).address, to: "0xdAC17F958D2ee523a2206206994597C13D831ec7", value: 1 //.... }); ``` -------------------------------- ### Get Network ID Source: https://docs.web3js.org/libdocs/Web3Eth Example of retrieving the network ID of the connected Ethereum node. This is useful for ensuring the correct network is being interacted with. ```javascript web3.eth.net.getId().then(console.log); ``` -------------------------------- ### Get Accounts Source: https://docs.web3js.org/libdocs/Web3Eth Example of retrieving a list of accounts available to the Web3 provider. This is typically used with browser-based wallets like MetaMask. ```javascript web3.eth.getAccounts().then(console.log); ``` -------------------------------- ### Initialize web3-eth-accounts Package Source: https://docs.web3js.org/libdocs/Accounts Import and use specific functions from the `web3-eth-accounts` package for a more efficient and lightweight application. This is recommended for smaller projects. ```javascript import {create,hashMessage} from 'web3-eth-accounts'; const account = create(); const result = hashMessage("Test Message"); ``` -------------------------------- ### Initialize Web3 Eth with Web3 Package Source: https://docs.web3js.org/api/web3-eth/class/Web3Eth Instantiate the Web3 Eth object using the main Web3 package. This approach is suitable when you need access to all Web3 functionalities. Ensure you replace '' with your actual project ID. ```javascript import { Web3 } from 'web3'; const web3 = new Web3('https://mainnet.infura.io/v3/'); const block = await web3.eth.getBlock(0); ``` -------------------------------- ### Get Latest Block Number Source: https://docs.web3js.org/libdocs/Web3Eth Example of retrieving the number of the most recent block on the chain. This is useful for tracking the current state of the blockchain. ```javascript web3.eth.getBlockNumber().then(console.log); ``` -------------------------------- ### Initialize Web3 and Use ENS Source: https://docs.web3js.org/api/web3-eth-ens/class/ENS Instantiate the Web3 class with a provider and then access ENS functionalities through `web3.eth.ens`. This approach is suitable when you are already using the main Web3 instance. ```javascript import { Web3 } from 'web3'; const web3 = new Web3('https://127.0.0.1:4545'); console.log(await web3.eth.ens.getAddress('ethereum.eth')) ``` -------------------------------- ### Get Block By Hash Source: https://docs.web3js.org/libdocs/Web3Eth Example of retrieving a block's details using its hash. This allows direct access to specific blocks on the chain. ```javascript web3.eth.getBlock("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef").then(console.log); ``` -------------------------------- ### Importing the Entire Web3 Library Source: https://docs.web3js.org/guides/web3_utils_module Demonstrates how to import the entire web3 library and access its utility functions, both before and after initializing a provider. ```javascript // import web3 module import { Web3 } from 'web3'; // no need to initialize a provider Web3.utils.toHex('web3'); //=> 0x77656233 // initializing a provider const web3 = new Web3('https:// eth.llamarpc.com'); // access the utils package web3.utils.toHex('web3'); //=> 0x77656233 ``` -------------------------------- ### Get Transaction Receipt Source: https://docs.web3js.org/libdocs/Web3Eth Example of retrieving the receipt for a specific transaction using its hash. The receipt contains information about the transaction's execution. ```javascript web3.eth.getTransactionReceipt("0x95222290dd544201079744315052409217339714073784306917207940132132").then(function(receipt){ console.log(receipt); }); ``` -------------------------------- ### Initialize Web3 Eth with web3-eth Package Source: https://docs.web3js.org/api/web3-eth/class/Web3Eth Instantiate the Web3 Eth object using the dedicated 'web3-eth' package for more lightweight applications. This is efficient for projects that only require Ethereum-specific functionalities. Replace '' with your project ID. ```javascript import { Web3Eth } from 'web3-eth'; const eth = new Web3Eth('https://mainnet.infura.io/v3/'); const block = await eth.getBlock(0); ``` -------------------------------- ### Set and Get Provider in Web3.js Source: https://docs.web3js.org/api/web3/class/Web3EthPluginBase Demonstrates how to set and retrieve the current provider for Web3.js. This includes examples of using both HTTP and WebSocket providers. ```javascript const web3 = new Web3Context("http://localhost:8545"); console.log(web3.provider); > HttpProvider { clientUrl: 'http://localhost:8545', httpProviderOptions: undefined } ``` ```javascript const web3Context = new web3ContextContext("http://localhost:8545"); web3Context.provider = "ws://localhost:8545"; console.log(web3Context.provider); > WebSocketProvider { _eventEmitter: EventEmitter { _events: [Object: null prototype] {}, _eventsCount: 0, ... } } ``` -------------------------------- ### Initialize Web3 and Accounts Source: https://docs.web3js.org/libdocs/Accounts Instantiate the Web3 library and access accounts functions. This approach uses the full web3 package. ```javascript import {Web3} from 'web3'; const web3 = new Web3(); const account = web3.eth.accounts.create(); const result = web3.eth.accounts.hashMessage("Test Message"); ``` -------------------------------- ### Instantiate IpcProvider with Options (v4) Source: https://docs.web3js.org/guides/web3_upgrade_guide/providers_migration_guide Demonstrates instantiating an IpcProvider in v4, including optional client and reconnection configurations. ```javascript import { IpcProvider } from 'web3-providers-ipc'; const provider = new IpcProvider( `path.ipc`, { writable: false, }, { delay: 500, autoReconnect: true, maxAttempts: 10, }, ); ``` -------------------------------- ### Get Block Transaction Hashes Source: https://docs.web3js.org/libdocs/Web3Eth Example of retrieving an array of transaction hashes included in a specific block. This can be used to list all transactions within a block. ```javascript web3.eth.getBlockTransactionCount("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef").then(console.log); ``` -------------------------------- ### Get Block Information Source: https://docs.web3js.org/libdocs/Web3Eth Retrieves detailed information about a specific block on the Ethereum blockchain. This example shows how to fetch block details and format the output. ```javascript web3.eth.getBlock( "0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d", false, { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } ).then(console.log); ``` -------------------------------- ### Get Ethereum Accounts using Web3.js Source: https://docs.web3js.org/api/web3/class/Personal Use the `web3.eth.personal.getAccounts()` method to retrieve a list of accounts managed by the Ethereum node. Ensure you have the Web3 package installed. ```javascript import { Web3 } from 'web3'; const web3 = new Web3('http://127.0.0.1:7545'); console.log(await web3.eth.personal.getAccounts()); ``` -------------------------------- ### Get Network ID using Web3.js Source: https://docs.web3js.org/api/web3/class/Net Instantiate Web3 with your project ID and use `web3.eth.net.getId()` to retrieve the network ID. Ensure you have installed the Web3 package. ```javascript import { Web3 } from 'web3'; const web3 = new Web3('https://mainnet.infura.io/v3/'); console.log(await web3.eth.net.getId()); ``` -------------------------------- ### Example Plugin Package.json Source: https://docs.web3js.org/guides/web3_plugin_guide/plugin_users Shows how a plugin is added as a dependency in a project's package.json file. ```json { "dependencies": { "web3-plugin-example": "0.1.0" } } ``` -------------------------------- ### Get Message to Sign for Signing Source: https://docs.web3js.org/api/web3-eth-accounts/class/AccessListEIP2930Transaction Retrieve the serialized unsigned transaction message, which can be used for signing, for example, when sending to a hardware wallet. The raw message format is already serialized and does not require RLP encoding. ```javascript const serializedMessage = tx.getMessageToSign(false) // use this for the HW wallet input ``` -------------------------------- ### Instantiate IpcProvider with Options (v1.x vs. v4) Source: https://docs.web3js.org/guides/web3_upgrade_guide/providers_migration_guide Shows how to instantiate an IpcProvider in version 1.x with a network path and in v4 with client and reconnect options. ```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" // in v4 let clientOptions: SocketConstructorOpts = { allowHalfOpen: false; readable: true; writable: true; }; const reconnectOptions: ReconnectOptions = { autoReconnect: true, delay: 5000, maxAttempts: 5, }; ``` -------------------------------- ### Initialize Web3 with Web3Eth Source: https://docs.web3js.org/api/web3/class/Web3Eth Import the entire Web3 package and initialize it with a provider URL. This makes all Web3 Eth functions available. ```javascript import { Web3 } from 'web3'; const web3 = new Web3('https://mainnet.infura.io/v3/'); const block = await web3.eth.getBlock(0); ``` -------------------------------- ### Get Transaction from Block (Custom Format) Source: https://docs.web3js.org/libdocs/Web3Eth Fetches a transaction from a specified block, allowing custom formatting for bytes and numbers. This example uses `hexToBytes` for the block hash and specifies `NUMBER` and `HEX` formats for the return data. ```javascript web3.eth.getTransactionFromBlock( hexToBytes("0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"), 0, { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } ).then(console.log); ``` -------------------------------- ### Initialize Public Client with HTTP Provider Source: https://docs.web3js.org/guides/migration_viem Replace Web3.js provider initialization with Viem's `createPublicClient` for network interaction. ```javascript import Web3 from 'web3'; const web3 = new Web3(providerURL); ``` ```javascript import { createPublicClient, http } from 'viem'; const client = createPublicClient({ transport: http(providerURL) }); ``` -------------------------------- ### Get Proof with Custom Formatting Source: https://docs.web3js.org/api/web3/interface/Web3EthInterface Fetches the proof for a given account address and storage keys, specifying custom formatting for number and bytes types. This allows control over how the returned data is represented, for example, as hex strings. ```javascript web3.eth.getProof( "0x1234567890123456789012345678901234567890", ["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001"], undefined, { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } ).then(console.log); ``` -------------------------------- ### Initialize Hardhat Project Source: https://docs.web3js.org/guides/hardhat_tutorial Initializes a new Hardhat project, setting up the basic file structure and configuration. ```bash npx hardhat init ``` -------------------------------- ### Constructor Source: https://docs.web3js.org/api/web3-eth-accounts/class/Wallet Initializes a new Wallet instance with a given account provider. ```APIDOC ## Constructor ### `__new Wallet (accountProvider: Web3AccountProvider): Wallet` #### Type parameters * **T** : Web3BaseWalletAccount = Web3BaseWalletAccount #### Parameters * `accountProvider`: Web3AccountProvider #### Returns Wallet ``` -------------------------------- ### CommonOpts Initialization Source: https://docs.web3js.org/api/web3-eth-accounts/interface/CommonOpts Demonstrates how to initialize a Common instance with custom chain configurations. ```APIDOC ## CommonOpts Options for instantiating a Common instance. ### Properties * **chain** (string | number | bigint | object) - Required - Chain name, id, or Chain enum. Can be a supported chain or a custom chain provided via `customChains`. * **customChains** (ChainConfig[]) - Optional - Initialize with selected custom chains in addition to supported chains. Custom genesis state should be passed to the Blockchain class if used. *Usage Example:* ```javascript import myCustomChain1 from '[PATH_TO_MY_CHAINS]/myCustomChain1.json' const common = new Common({ chain: 'myCustomChain1', customChains: [ myCustomChain1 ]}) ``` * **eips** (number[]) - Optional - Selected EIPs to activate. Use an array for instantiation (e.g., `eips: [ 2537, ]`). Currently supported: EIP-2537 - BLS12-381 precompiles. * **hardfork** (string) - Optional - String identifier for a hardfork or Hardfork enum. Defaults to `Hardfork.London`. ``` -------------------------------- ### Instantiate Web3 with Context Options Source: https://docs.web3js.org/api/web3/changelog The Web3 constructor now accepts Web3ContextInitOptions as an alternative to undefined, string, or SupportedProviders. ```javascript Web3 constructor accepts `Web3ContextInitOptions` as alternative to the still supported `undefined`, `string`, and `SupportedProviders` (#6262). ``` -------------------------------- ### Instantiate IpcProvider with Options Source: https://docs.web3js.org/api/web3-providers-ipc/class/IpcProvider Demonstrates how to instantiate the IpcProvider with a socket path, socket options, and reconnection options. The second and third parameters are optional. ```javascript const provider = new IpcProvider( `path.ipc`, { writable: false, }, { delay: 500, autoReconnect: true, maxAttempts: 10, }, ); ``` -------------------------------- ### Create and Add Account to Wallet Source: https://docs.web3js.org/guides/wallet Demonstrates how to create a new Ethereum account using web3.eth.accounts.create() and add it to an existing wallet instance. The console output shows the structure of the wallet after the addition. ```javascript // create a new account and add it to the wallet const newAccount = web3.eth.accounts.create(); wallet.add(newAccount); console.log(wallet); ``` -------------------------------- ### Install Hardhat Source: https://docs.web3js.org/guides/hardhat_tutorial Installs the Hardhat development environment in your project using npm. ```bash npm install hardhat ``` -------------------------------- ### Deploy Contract with Viem Source: https://docs.web3js.org/guides/migration_viem Example of deploying a contract using Viem's `deployContract` function. Requires a wallet client and provides bytecode, ABI, and constructor arguments. ```javascript import { createWalletClient, custom } from 'viem'; import { mainnet } from 'viem/chains'; const walletClient = createWalletClient({ chain: mainnet, transport: custom(window.ethereum), }); const hash = await walletClient.deployContract({ abi, account, args: ['constructor param'], bytecode: bytecode, }); ``` -------------------------------- ### Install TypeScript and Node Types Source: https://docs.web3js.org/guides/web3_eth/eth Installs TypeScript and Node.js type definitions for your project. ```bash npm i typescript @types/node ``` -------------------------------- ### Install web3.js ENS package Source: https://docs.web3js.org/guides/ens Install the dedicated web3-eth-ens package for direct ENS interactions. ```bash npm install web3-eth-ens ``` -------------------------------- ### Deploying a Smart Contract Instance Source: https://docs.web3js.org/guides/smart_contracts/mastering_smart_contracts Use this to deploy a new contract instance. Ensure you have the contract's bytecode and constructor arguments ready. The default account is obtained from the connected provider. ```javascript // this will give you the accounts from the connected provider // For example, if you are using MetaMask, it will be the account available. const providersAccounts = await web3.eth.getAccounts(); const defaultAccount = providersAccounts[0]; console.log('deployer account:', defaultAccount); // NOTE: If you want to manually unlock an account with a private key, you can use wallet.add(privateKey). // however, exercise caution and ensure the security of your private keys. // this is how to obtain the deployer function, // so you can estimate its needed gas and deploy it. const contractDeployer = myContract.deploy({ data: bytecode, // prefix the bytecode with '0x' if it is note already arguments: [1], // provide the parameters in an array; in this case, it's the number `1`. }); // optionally, estimate the gas that will be used for development and log it const gas = await contractDeployer.estimateGas({ from: defaultAccount, }); console.log('estimated gas:', gas); // Deploy the contract to the Ganache network const tx = await contractDeployer.send({ from: defaultAccount, gas, gasPrice: 10000000000, }); console.log('Contract deployed at address: ' + tx.options.address); ``` -------------------------------- ### Initialize Web3Eth with Web3 Package Source: https://docs.web3js.org/libdocs/Web3Eth Instantiate the Web3 Eth object using the main Web3 package. This requires installing the 'web3' package and initializing it with a provider URL. ```javascript import { Web3 } from 'web3'; const web3 = new Web3('https://mainnet.infura.io/v3/'); const block = await web3.eth.getBlock(0); ``` -------------------------------- ### Instantiate Contract with Individual Packages Source: https://docs.web3js.org/api/web3/class/Contract For a more lightweight approach, install and use the `web3-eth-contract` and `web3-core` packages. This is efficient for applications where only contract functionality is needed. ```javascript import { Web3Context } from 'web3-core'; import { Contract } from 'web3-eth-contract'; const abi = [...] as const; // your contract ABI let contract = new web3.eth.Contract( abi, '0xdAC17F958D2ee523a2206206994597C13D831ec7' new Web3Context('http://127.0.0.1:8545')); await contract.methods.balanceOf('0xdAC17F958D2ee523a2206206994597C13D831ec7').call(); ``` -------------------------------- ### Install Web3.js and Hardhat Plugin Source: https://docs.web3js.org/guides/hardhat_tutorial Installs the Web3.js library (version 4) and the hardhat-web3-v4 plugin as development dependencies. ```bash npm install --save-dev @nomicfoundation/hardhat-web3-v4 'web3@4' ``` -------------------------------- ### Instantiate a Smart Contract Source: https://docs.web3js.org/guides/getting_started/quickstart Shows how to instantiate a smart contract using its ABI and address. The ABI should contain the function signatures for the methods you intend to call. ```javascript // 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); ``` -------------------------------- ### Start Hardhat Development Network Source: https://docs.web3js.org/guides/smart_contracts/smart_contracts_guide Starts the Hardhat local development network. This command must remain running. ```bash npx hardhat node ``` -------------------------------- ### Web3Eth Initialization and Usage Source: https://docs.web3js.org/libdocs/Web3Eth Demonstrates how to install and initialize the Web3Eth module, and use it to retrieve block information. ```APIDOC ## Installation Install the Web3Eth package using npm or yarn: ```bash npm i web3-eth # or yarn add web3-eth ``` ## Initialization Initialize Web3Eth with a provider URL. ### Example ```javascript import { Web3Eth } from 'web3-eth'; const eth = new Web3Eth('https://mainnet.infura.io/v3/'); const block = await eth.getBlock(0); console.log(block); ``` ## Accessors ### getBlock Retrieves a block from the blockchain by its number or hash. #### Parameters - **blockNumberOrHash** (number | string): The block number or hash. #### Returns - **Promise** The block object. ### BatchRequest • `get` **BatchRequest**(): `Object` Will return the Web3BatchRequest constructor. #### Returns `Object` #### Inherited from Web3Context.BatchRequest * * * ### blockHeaderTimeout • `get` **blockHeaderTimeout**(): `number` The blockHeaderTimeout is used over socket-based connections. This option defines the amount seconds it should wait for `'newBlockHeaders'` event before falling back to polling to fetch transaction receipt. Default is `10` seconds. #### Returns `number` #### Inherited from Web3Context.blockHeaderTimeout • `set` **blockHeaderTimeout**(`val`): `void` Will set the blockHeaderTimeout #### Parameters Name| Type ---|--- `val`| `number` #### Returns `void` #### Inherited from Web3Context.blockHeaderTimeout * * * ### contractDataInputFill • `get` **contractDataInputFill**(): `"input"` | `"data"` | `"both"` The `contractDataInputFill` options property will allow you to set the hash of the method signature and encoded parameters to the property either `data`, `input` or both within your contract. This will affect the contracts send, call and estimateGas methods Default is `data`. #### Returns `"input"` | `"data"` | `"both"` #### Inherited from Web3Context.contractDataInputFill • `set` **contractDataInputFill**(`val`): `void` Will set the contractDataInputFill #### Parameters Name| Type ---|--- `val`| `"input"` | `"data"` | `"both"` #### Returns `void` #### Inherited from Web3Context.contractDataInputFill * * * ### currentProvider • `get` **currentProvider**(): `undefined` | `Web3BaseProvider`<`API`> Will return the current provider. (The same as `provider`) #### Returns `undefined` | `Web3BaseProvider`<`API`> Returns the current provider **`Example`** ```javascript const web3Context = new Web3Context("http://localhost:8545"); console.log(web3Context.provider); // > HttpProvider { // clientUrl: 'http://localhost:8545', // httpProviderOptions: undefined // } ``` #### Inherited from Web3Context.currentProvider • `set` **currentProvider**(`provider`): `void` Will set the current provider. (The same as `provider`) #### Parameters Name| Type| Description ---|---|--- `provider`| `undefined` | `string` | `LegacyRequestProvider` | `LegacySendProvider` | `LegacySendAsyncProvider` | `EIP1193Provider`<`API`> | `Web3BaseProvider`<`API`> | `SimpleProvider`<`API`> | `MetaMaskProvider`<`API`>| SupportedProviders The provider to set #### Returns `void` **`Example`** ```javascript const web3Context = new Web3Context("http://localhost:8545"); web3Context.currentProvider = "ws://localhost:8545"; console.log(web3Context.provider); // > WebSocketProvider { // _eventEmitter: EventEmitter { // _events: [Object: null prototype] {}, // _eventsCount: 0, // ... // } ``` #### Inherited from Web3Context.currentProvider * * * ### defaultAccount • `get` **defaultAccount**(): `undefined` | `string` This default address is used as the default `from` property, if no `from` property is specified in for the following methods: * web3.eth.sendTransaction() * web3.eth.call() * myContract.methods.myMethod().call() * myContract.methods.myMethod().send() #### Returns `undefined` | `string` #### Inherited from Web3Context.defaultAccount • `set` **defaultAccount**(`val`): `void` Will set the default account. #### Parameters Name| Type ---|--- `val`| `undefined` | `string` #### Returns `void` #### Inherited from Web3Context.defaultAccount * * * ### defaultBlock • `get` **defaultBlock**(): `BlockNumberOrTag` The default block is used for certain methods. You can override it by passing in the defaultBlock as last parameter. The default value is `"latest"`. * web3.eth.getBalance() * web3.eth.getCode() * web3.eth.getTransactionCount() * web3.eth.getStorageAt() * web3.eth.call() * myContract.methods.myMethod().call() #### Returns `BlockNumberOrTag` ``` -------------------------------- ### Custom RPC API Example Source: https://docs.web3js.org/api/web3/class/Web3PluginBase Example of defining a custom RPC API specification and extending Web3PluginBase with it for type support. ```APIDOC ## Custom RPC API Definition ### Description Define a TypeScript interface to specify custom RPC methods and their signatures. This allows for type-safe interactions with RPC endpoints that support these custom methods. ### Usage ```typescript type CustomRpcApi = { custom_rpc_method: () => string; custom_rpc_method_with_parameters: (parameter1: string, parameter2: number) => string; }; class CustomPlugin extends Web3PluginBase { ... } ``` ### Parameters * **CustomRpcApi** (type): An interface defining the custom RPC methods available. * **custom_rpc_method**: A method that takes no arguments and returns a string. * **custom_rpc_method_with_parameters**: A method that accepts a string and a number, returning a string. ``` -------------------------------- ### Install rn-nodeify for BigInt Polyfill Source: https://docs.web3js.org/guides/resources_and_troubleshooting Install `rn-nodeify` as a development dependency to help resolve BigInt-related errors in React Native projects. ```bash yarn add --dev rn-nodeify ``` -------------------------------- ### Initialize Iban with Web3 Package Source: https://docs.web3js.org/api/web3-eth-iban/class/Iban Instantiate the Iban class using the Web3 package. Ensure Web3 is installed and configured with a provider. ```javascript import { Web3 } from 'web3'; const web3 = new Web3('https://mainnet.infura.io/v3/'); const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); console.log(iban.checksum()); ``` -------------------------------- ### Initialize Web3Eth with web3-eth Package Source: https://docs.web3js.org/libdocs/Web3Eth Instantiate the Web3Eth object directly using the 'web3-eth' package for a more lightweight application. This requires installing 'web3-eth' and initializing it with a provider URL. ```javascript import { Web3Eth } from 'web3-eth'; const eth = new Web3Eth('https://mainnet.infura.io/v3/'); const block = await eth.getBlock(0); ``` -------------------------------- ### Get Filter Changes - Web3.eth Source: https://docs.web3js.org/api/web3/class/Web3Eth Retrieves changes for a specific filter. Use this to get logs that have occurred since the last call. ```javascript web3.eth.getFilterChanges(123).then(console.log); > [{ data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] logIndex: 0n, transactionIndex: 0n, transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', blockNumber: 1234n, address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' }, {...}] ``` -------------------------------- ### Create and Use Wallet Accounts Source: https://docs.web3js.org/api/web3-eth-accounts/class/Wallet Demonstrates creating a wallet with multiple accounts, signing data with a specific account, and sending a transaction using an account from the wallet. Ensure accounts are funded before sending transactions. ```javascript import { Web3 } from 'web3'; const web3 = new Web3('http://127.0.0.1:7545'); const wallet = await web3.eth.accounts.wallet.create(2); const signature = wallet.at(0).sign("Test Data"); // use wallet // fund account before sending following transaction ... const receipt = await web3.eth.sendTransaction({ from: wallet.at(0).address, to: "0xdAC17F958D2ee523a2206206994597C13D831ec7", value: 1 //.... }); ``` -------------------------------- ### Install react-native-quick-crypto Source: https://docs.web3js.org/guides/resources_and_troubleshooting Install `react-native-quick-crypto` as a dependency to resolve 'TypeError: Cannot read property \'prototype\' of undefined' errors when using Web3.js with React Native. ```bash yarn add react-native-quick-crypto ```