Skip to main content

Web3.js

Overview​

Web3.js is a robust and flexible collection of TypeScript and JavaScript libraries that allows developers to interact with local or remote Ethereum nodes over HTTP, IPC or WebSocket connections. By using Web3.js, you can interact with smart contracts deployed on Soneium Minato.

Install​

To install Web3.js, run the following command:

$ pnpm i web3

Setting Up the Web3 Instance and connecting to Minato​

To begin using web3.js, set up your web3.js instance as shown below:

// For web3.js v1.x
import Web3 from 'web3';

// For web3.js v4.x
import { Web3 } from 'web3';

const rpc = 'https://rpc.minato.soneium.org/'
const provider = new Web3.providers.HttpProvider(rpc);
// Connect to the Soneium Minato RPC
const web3 = new Web3(provider);

Reading Data from Soneium Minato​

You can read data from Soneium Minato by using the provider. For instance, to get the balance of a specific wallet address, you can use the getBalance method:

import { web3 } from './config';

const address = '0xYourWalletAddress';
const balance = await web3.eth.getBalance(address);
console.log(`Balance: ${web3.utils.fromWei(balance, 'ether')} ETH`);

Writing Data to Soneium Minato​

To send transactions or interact with accounts, you need to use privateKeyToAccount to import a signer. This allows you to manage accounts, sign messages, and execute transactions:

import { PRIVATE_KEY, web3 } from './config';

// Import the private key and add the account
const account = web3.eth.accounts.privateKeyToAccount(PRIVATE_KEY);

const transaction = {
from: account.address,
to: '0xDestinationAddress',
value: web3.utils.toWei('0.01', 'ether'),
};

const gasPrice = await web3.eth.getGasPrice();
const gas = await web3.eth.estimateGas({ ...transaction, gasPrice });
const txInfo = { ...transaction, gas, gasPrice };

// Sign the transaction
const signedTx = await account.signTransaction(txInfo);
// Send the transaction
const { blockHash } = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);

Interacting with Smart contracts​

The web3-eth package allows you to interact with an Ethereum blockchain and Ethereum smart contracts. Below is an example of interacting with an ERC20 contract on Soneium Minato:

import { erc20Abi } from './ABI';
import { web3, USDC_ADDRESS, SENDER_ADDRESS, SPENDER_ADDRESS } from './config';
import { AbiItem } from 'web3-utils';

const contract = new web3.eth.Contract(erc20Abi as AbiItem[], USDC_ADDRESS);

// Read the value from the contract
const allowance = await contract.methods.allowance(SENDER_ADDRESS, SPENDER_ADDRESS).call();

// Send contract function
const amount = "1000000";
await contract.methods.approve(SPENDER_ADDRESS, amount).send({ from: SENDER_ADDRESS });