声明:本站文章均为作者个人原创,图片均为实际截图。如有需要请收藏网站,禁止转载,谢谢配合!!!

区块链网络是一个点对点的对等网络,网络由各个节点相互连接构成,智能合约的代码与数据存储在区块链中。使用web3.js可以向区块链网络中某个以太坊节点发出请求,与区块链网络进行交互。

点击下载 Web3Js和BigNumberJs

1、引入web3.min.jsbignumber.min.js

<script src="/assets/diy/js/web3.min.js"></script>
<script src="/assets/diy/js/bignumber.min.js"></script>

2、使用web3js进行登录和转账功能

new Vue({
    el: '#app',
        data() {
        return {
            web3js: {},
        }
    },
    created(){
        this.initWeb3()
        this.grantAccount() //初始化获取用户账户信息
    },
    methods: {
        //初始化web3js
        initWeb3(){
            let web3Provider;
            if (window.ethereum) {
                web3Provider = window.ethereum;
            }
            this.web3js = new Web3(web3Provider);//web3js就是你需要的web3实例
        },

        //发起转账
        transfer() {
            ethereum.request({
                method: 'eth_sendTransaction',
                params: [{
                    from: this.account,
                    to: this.config.account_address,
                    //value: "0x16345785d8a0000", // 此处默认为0.1,测试使用,实际使用应该换算
                    value: this.getValue(this.price), // 此处默认为0.1,测试使用,实际使用应该换算
                }]
            })
            .then((res)=>{
                //'0x0d270410ea7d04de89ff1b5700599c88e924226a9cb03677653f0b005d5e3464'
                //写入转账记录
            })
            .catch((err)=>{
                if (err.code == 4001){
                    this.$message.error('User denied transaction signature.')
                }
            })
        },

        //转换
        getValue(data){
            return '0x' + (parseFloat(data) * 1000000000000000000).toString(16)
        },

        //授权账户
        grantAccount(){
            let flag = false;
            try {
            // 请求用户授权
                window.ethereum.enable();
            } catch (error) {
            // 用户不授权时
                this.$message.info('please install plugin: metamask')
                //console.error("User denied account access")
            }
            this.web3js.eth.getAccounts((error, result) => {
                if (!error){
                    if (result.length > 0){
                        this.accountList = result
                        this.account = result[0]
                        this.$message.success('your current account address:' + this.account)
                    }
                flag = true
                this.plugin = true
                }
            })
            return flag
        },

}
})