What use instead Web3Contract.setProvider("RPC_URL") in web3-eth-contract 4.x version?

40 views Asked by At

In web3-eth-contract 1.x, using this is possible.

Web3Contract.setProvider("https://rpc2.sepolia.org/")

But in 4.x, setProvider in the Web3Contract object does not exist.

enter image description here

What is the solution?

I tried to get methods from smart contract in dapp without connection wallet, so I used web3-eth-contract. Because I already used it in my projects. But the version was 1.x. I'm working with 4.x, but the method to use the module is not written in detail.

If there is another solution without using web3-eth-contract, it will be better. Don't suggest me to use web3.eth.contract.

1

There are 1 answers

0
Akeel Ahmed Qureshi On

In web3.js version 4 you can use Web3Context for setting the provider at the time of creating the contract instance.

This block of code may help you:

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();

Document Link: https://docs.web3js.org/api/web3-eth-contract/class/Contract/#constructor:~:text=import%20%7B%20Web3Context%20%7D%20from%20%27web3%2Dcore%27%3B