Web3.js连接metaMask钱包

先确认自己的浏览器安装了metaMask插件,建议谷歌浏览器
编写前端代码测试,通过npm install web3 引入需要的库

function Init(callback) {
    //判断用户是否安装MetaMask钱包插件
    if (typeof window.ethereum === "undefined") {
        //没安装MetaMask钱包进行弹框提示
        Message.warning("请安装MetaMask")
    } else {
        //如果用户安装了MetaMask,你可以要求他们授权应用登录并获取其账号
        ethereum.enable()
            .catch(function(reason) {
                //如果用户拒绝了登录请求
                if (reason === "User rejected provider access") {
                    // 用户拒绝登录后执行语句;
                } else {
                    // 本不该执行到这里,但是真到这里了,说明发生了意外
                    Message.warning("There was a problem signing you in");
                }
            }).then(function(accounts) {
                // 判断是否连接以太
                if (ethereum.networkVersion !== desiredNetwork) {}
                let currentProvider = web3.currentProvider;
                web3.setProvider(currentProvider);
                //如果用户同意了登录请求,你就可以拿到用户的账号
                web3.eth.defaultAccount = accounts[0];

                myContract = new web3.eth.Contract(ABI, metaMaskAddress);
                //这里返回用户钱包地址
                callback(accounts[0]);
            });
    }
}

在vue中引入

<script>
import WB3 from "../utils/web3";
export default {
  data() {
    return {};
  },
  mounted() {
    WB3.Init((res) => {
      console.log(res);//这里就是MetaMask钱包的地址
  },
  watch: {},
  methods: {},
  components: {},
};
</script>

官方API方法监听账号切换

 mounted() {
	 this.fn();
 }
 methods:{
    fn() {
      ethereum.on("accountsChanged", function(accounts) {
        console.log(accounts[0]);//一旦切换账号这里就会执行
      });
    },
  },

转账

transfer(){
    let value= web3.utils.toWei('1', 'ether')
    var message = {from: this.fromAddress, to:this.toAddress, value:value};

	web3.eth.sendTransaction(message, (err, res) => {
	    var output = "";
	    if (!err) {
	    	output += res;
	    	this.txHash=res
	    } else {
	    	output = "Error"+err;
	    }
	    console.log('转账:',output)
    })
},

猜你喜欢

转载自blog.csdn.net/watson2017/article/details/122427120
今日推荐