如何向合約轉(zhuǎn)BNB?
現(xiàn)在遇到了一大問(wèn)題,就是不知道如何向合約來(lái)轉(zhuǎn)BNB
我想實(shí)現(xiàn)的功能就是說(shuō),有一個(gè)button,點(diǎn)擊button,Metamask的彈窗就彈出來(lái)授權(quán),然后從錢包中轉(zhuǎn)出1個(gè)BNB
我參考的資料如下,沒(méi)準(zhǔn)把這些知識(shí)串起來(lái)就明白了
參考文章如下:
https://blog.csdn.net/qq_16137795/article/details/120239103?utm_source=app&app_version=4.17.2&code=app_1562916241&uLinkId=usr1mkqgl919blen
代碼如下:
import React, {Component} from 'react';
import Web3 from "web3";
/*******************************************************************************************
* 1.一個(gè)實(shí)例化的provider,可以是metamask ,infura,ganache,或者搭建以太坊節(jié)點(diǎn) **
* **
2.合約的abi,自己填寫(xiě)的合約通過(guò)編譯后獲得abi,鏈上的合約需要開(kāi)源才能獲得abi,erc代幣合約的abi其實(shí)都一樣 ** **
*
3.實(shí)例化web3.js 或者 ether.js
*
4.通過(guò)abi和合約地址將合約實(shí)例化
*
5.調(diào)用合約方法 call 或者 send
*
* ******************************************************************************************/
class App extends Component {
constructor(props) {
super(props);
this.state = {
value: 0
};
}
//這個(gè)com是react的一個(gè)生命周期,在頁(yè)面加載完之后會(huì)執(zhí)行這里面的程序
async componentDidMount() {
//判斷用戶是不是安裝了metamask
if (typeof window.ethereum !== 'undefined') {
const ethereum = window.ethereum
//禁止自動(dòng)刷新,meta mask要求寫(xiě)的
ethereum.autoRefreshOnNetworkChange = false;
try {
//這一步就是第一次和metamask進(jìn)行鏈接
const accounts = await ethereum.enable()
console.log(accounts)
console.log("鏈接成功小狐貍!!")
//初始化provider,其實(shí)這個(gè)provider就是節(jié)點(diǎn),小狐貍也是一個(gè)節(jié)點(diǎn)
const provider = window['ethereum']
//獲取網(wǎng)絡(luò)id
console.log("chan id is ")
console.log(provider.chainId)
//實(shí)例化web3,注意哈,這里是大寫(xiě)
const web3 = new Web3(provider)
console.log("ssssssss")
console.log(accounts[0])
let fromAddress = accounts[0];
//轉(zhuǎn)賬數(shù)量
//let amount = 1*Math.pow(10,18);
// 如果要是18就是1BNB,如果要是17,就是0.1BNB
// 如果要是 2*Math.pow(10,17) 就是 0.2BNB
let amount = 1*Math.pow(10,17);
//收款地址
let toAddress = "0x40141cF4756A72DF8D8f81c1E0c2ad403C127b9E";
web3.eth.sendTransaction({
gas: 21000,
gasPrice: 5000000000,
from: fromAddress,
to: toAddress,
value: amount
}, (err, result) => {
console.log("轉(zhuǎn)賬Hash=",result)
})
//捕獲兩個(gè)事件,當(dāng)前的頁(yè)面切換網(wǎng)絡(luò)ID和當(dāng)前賬號(hào)
ethereum.on('accountsChanged', function (accounts) {
console.log("當(dāng)前賬戶發(fā)生更改:" + accounts)
})
ethereum.on('networkChanged', function (networkVersion) {
console.log("networkChanged" + networkVersion)
})
} catch (e) {
}
} else {
console.log("沒(méi)有安裝小狐貍!")
}
}
//定義兩個(gè)方法
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:
