參考的文章和資料如下
主要看的是這篇文章:
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;
