参考的文章和资料如下
主要看的是这篇文章:
ETH开发DAPP使用Web3+Vue唤醒MetaMask钱包和合约交互_IT_浩哥的博客-CSDN博客_metamask合约交互
不过如果自己要是尝试的话,不要完全照搬照抄代码,因为文章中的 provider 是因为安装了 ganache 环境(安装完 ganache环境之后就相当于在本地有了自己的节点)
所以在文章中的 provider 都是 localhost
实际这里我用的节点是 崔大师开发僵尸游戏时所写的前端
https://www.bilibili.com/video/BV13g4y1a767?spm_id_from=333.999.0.0
下面是解决此问题时查阅到的资料
《web3.js 的中文文档手册 》
源自登链社区:https://learnblockchain.cn/docs/web3.js/web3-eth.html#givenprovider
《以太坊Web3学习笔记》
https://www.jianshu.com/p/9722b5d687cf
《通过MetaMask向智能合约转入ETH和转出ETH》
https://www.jianshu.com/p/28292f35b7b0?tt_from=weixin
这个是能运行的完整代码,里面有许多没用的代码,2022/1/4
import React, {Component} from 'react'; import Web3 from "web3"; /******************************************************************************************* * 1.一个实例化的provider,可以是metamask ,infura,ganache,或者搭建以太坊节点 ** * ** 2.合约的abi,自己填写的合约通过编译后获得abi,链上的合约需要开源才能获得abi,erc代币合约的abi其实都一样 ** ** * 3.实例化web3.js 或者 ether.js * 4.通过abi和合约地址将合约实例化 * 5.调用合约方法 call 或者 send * * ******************************************************************************************/ class App extends Component { constructor(props) { super(props); this.state = { value: 0 }; } //这个com是react的一个生命周期,在页面加载完之后会执行这里面的程序 async componentDidMount() { //判断用户是不是安装了metamask if (typeof window.ethereum !== 'undefined') { const ethereum = window.ethereum //禁止自动刷新,meta mask要求写的 ethereum.autoRefreshOnNetworkChange = false; try { //这一步就是第一次和metamask进行链接 const accounts = await ethereum.enable() console.log(accounts) console.log("链接成功小狐狸!!") //初始化provider,其实这个provider就是节点,小狐狸也是一个节点 const provider = window['ethereum'] //实例化web3,注意哈,这里是大写 const web3 = new Web3(provider) console.log("ssssssss") console.log(accounts[0]) let fromAddress = accounts[0]; //转账数量 let amount = 1*Math.pow(10,18); //收款地址 let toAddress = "0x40141cF4756A72DF8D8f81c1E0c2ad403C127b9E"; web3.eth.sendTransaction({ gas: 21000, gasPrice: 5000000000, from: fromAddress, to: toAddress, value: amount }, (err, result) => { console.log("转账Hash=",result) }) //捕获两个事件,当前的页面切换网络ID和当前账号 ethereum.on('accountsChanged', function (accounts) { console.log("当前账户发生更改:" + accounts) }) ethereum.on('networkChanged', function (networkVersion) { console.log("networkChanged" + networkVersion) }) } catch (e) { } } else { console.log("没有安装小狐狸!") } } //定义两个方法 Getter = () => { window.myContract.methods.getdata().call(null,function(error, resultt){ console.log("the data:"+resultt); // this.setState({value: resultt}) }); } Increase = () => { window.myContract.methods.increase(2).send({from:window.defauleAccount}) .on('transactionHash',(transactionHash)=>{ console.log('transactionhash == ' + transactionHash) }) .on('confirmation',(confirmation) => { // console.log('confirmation == ' + confirmation ) }) } render() { return ( <div> <div>{this.state.value}</div> <div> <button onClick={() => {this.Getter()}}>Getter</button> </div> <div> <button onClick={() => {this.Increase()}}>Increase</button> </div> <div></div> </div> ); } } export default App;