blockchain - web3.js 切换网络 switch chain id rpc

访问量: 254

其实特别简单。

在初始化web3的时候,设置对应的endpoint就可以了

例如:

使用本地hardhat

var Web3 = require('web3')
var web3 = new Web3('ws://localhost:8545')
web3.eth.getAccounts()
.then(console.log);

使用本地hardhat 调用Contract

var Contract = require('web3-eth-contract')
run()
async function run(){
  Contract.setProvider('ws://localhost:8545')   // 注意这一行
  let contractAbi = [{"inputs":[],"name":"getNumber","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"num","type":"uint256"}],"name":"store","outputs":[],"stateMutability":"nonpayable","type":"function"}]
  let contractAddress = '0x5FbDB2315678afecb367f032d93F642f64180aa3'
  var contract = new Contract(contractAbi, contractAddress)
  await contract.methods.getNumber().call()
}

使用测试网络 Rinkeby 调用Contract

var Contract = require('web3-eth-contract')
run()
async function run(){
// 设置 这里,使用的是 infura提供的rinkeby endpoint Contract.setProvider('wss://rinkeby.infura.io/ws/v3/427a8f460d514ebfadf0d6c60b09ef27') let contractAbi = [{"inputs":[],"name":"getNumber","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"num","type":"uint256"}],"name":"store","outputs":[],"stateMutability":"nonpayable","type":"function"}] let contractAddress = '0x5FbDB2315678afecb367f032d93F642f64180aa3' var contract = new Contract(contractAbi, contractAddress) await contract.methods.getNumber().call() }

订阅/RSS Feed

Subscribe