美文网首页
Web3.js与以太坊区块链交互

Web3.js与以太坊区块链交互

作者: JennyVeil | 来源:发表于2018-05-13 17:43 被阅读0次

    在前面的博客中已经介绍了如何搭建一个以太坊客户端节点。不止是以太坊,区块链的节点一般会提供一些接口,大部分都是通过JSON RPC和节点进行交互。JSON-RPC ,是一个无状态且轻量级的远程过程调用(RPC)传送协议,可以在同一个进程中,在套接字上,在HTTP上,或在许多不同的消息传递环境中使用。RPC、客户端(节点)、以太坊网络三者的关系:用户通过RPC调用客户端功能, 客户端通过EVM执行智能合约以及跟整个以太坊P2P网络连接。

    除了通过Geth的JavaScript Console进行交互以外,还有许多第三方库可以使用,方便开发基于以太坊区块链的应用:

    Library Language Project Page
    web3.js JavaScript https://github.com/ethereum/web3.js
    web3j Java https://github.com/web3j/web3j
    Nethereum C# .NET https://github.com/Nethereum/Nethereum
    ethereum-ruby Ruby https://github.com/DigixGlobal/ethereum-ruby
    web3.py Python https://github.com/ethereum/web3.py

    本文使用web3.js与Geth客户端交互,首先搭建开发环境。

    一、node.js安装

    Ubuntu 16.4 64位

    更新源

    sudo apt-get update
    sudo apt-get install -y python-software-properties software-properties-common
    sudo add-apt-repository ppa:chris-lea/node.js
    sudo apt-get update

    node.js、npm安装

    sudo apt-get install nodejs
    sudo apt install nodejs-legacy
    sudo apt install npm

    安装完后,可以通过 node --version npm --version 查看是否安装成功及版本号。npm 包管理工具随 node 一起安装,如果版本太低,建议升到新版本。

    二、web3.js模块安装

    使用npm可完成本地安装、全局安装模块。

    npm install -global <package name> //全局安装
    npm install <package name> //本地安装

    我这里选择使用本地安装模块,这样方便开发的应用移植、上线等。创建一个工程文件夹etherjs。在该文件夹下初始化一个新的 package.json 文件,使用下面命令自动生成。

    npm init -y

    本地安装并添加模块名到 package.json

    npm install <package name> --save
    或者npm install <package name> --save-dev

    区别在于--save-dev 是你开发时候依赖的东西,--save 是你发布之后还依赖的东西。一般使用--save。

    npm install web3 --save

    如果这样安装不成功,使用下面命令安装指定版本:

    npm install web3@^0.20.1 --save

    三、solc.js模块安装

    solc是用来编译智能合约的模块

    npm install solc --save

    四、编译器——Visual Studio Code

    这里选择Visual Studio Code,适合node.js开发,集成的终端可以很方便运行程序。

    安装Ubuntu Make

    sudo add-apt-repository ppa:ubuntu-desktop/ubuntu-make
    sudo apt-get update
    sudo apt-get install ubuntu-make

    安装visual-studio-code

    umake web visual-studio-code

    安装完成后,直接搜索Visual Studio Code应用,把图标拖拽到Unity启动器上,就可以方便使用了。


    把Visual Studio Code终端功能调用出来,这样可以在下方直接输入node xx.js运行程序,其他功能这里不再多介绍。 搭建环境可能会遇到各种错误,善用Google,多找一些解决办法看看。

    五、交互实现——部署智能合约

    通过编写一个depoly.js程序实现自动化的部署智能合约。首先要保持Geth客户端正常运行,并开启rpc。

    geth --identity "TestNode" --rpc --rpcport "8545" --datadir data0 --port "30303" --nodiscover --networkid 6666 --rpcapi admin,eth,miner,personal,txpool,eth,web3,net console

    合约应该在智能合约编译器(如remix)调试好,然后将其写到test.sol文件里。

    pragma solidity ^0.4.0;
    contract TestContract
    {
        function multiply(uint a, uint b) returns (uint)
        {
            return a * b;
        }
    }
    

    使用solc模块生成合约的code和abi,我将该过程自定义为一个模块test.js,方便depoly.js调用。

    var fs = require('fs');
    var solc = require('solc');
    //compile smart contract to get bytecode and abi
    
    var source = fs.readFileSync("./test.sol",'utf8');  //读取代码
        //console.log("compiling contract...");
    var compiledcontract = solc.compile(source); //编译
        //console.log('done');
    for (var contractName in compiledcontract.contracts){
        var bytecode = compiledcontract.contracts[contractName].bytecode;
        var abi = JSON.parse(compiledcontract.contracts[contractName].interface);
    }
    //console.log(JSON.stringify(abi, undefined, 2));
    //console.log(bytecode);
    //console.log(abi);
    
    function bytecode(){
        console.log(bytecode);
    }
    function abi(){
        console.log(abi);
    }
    module.exports = {bytecode:bytecode,abi:abi}; 
    

    depoly.js通过与Geth交互部署智能合约。当合约被区块链确认后,会直接返回合约地址。

    var Web3 = require('web3');
    var contract = require('./test');
    var web;
    
    //connect to node
    var ethereumUri = 'http://localhost:8545';
    if (typeof web3 !== 'undefined') {
        web3 = new Web3(web3.currentProvider);
    } else {
        // set the provider you want from Web3.providers
        web3 = new Web3(new Web3.providers.HttpProvider(ethereumUri));
    }
    //查询区块链中基本的账户信息
    if(!web3.isConnected()){
        throw new Error('unable to connect to ethereum node at '+ ethereumUri);
    }else{
        console.log('connected to etherum node at '+ ethereumUri);
        var coinbase = web3.eth.accounts[0];
        console.log('coinbase:' + coinbase);
        var balance = web3.eth.getBalance(coinbase);
        console.log('balance:' + web3.fromWei(balance, 'ether') + " ETH");
        var accounts = web3.eth.accounts;
        console.log(accounts);    
    }
    //通过coinbase部署智能合约
    var abi = contract.abi;
    var bytecode = contract.bytecode;
    
    if (web3.personal.unlockAccount(coinbase, '123')) {
        console.log(`${coinbase} is unlocaked`);
    }else{
        console.log(`unlock failed, ${coinbase}`);
    }
    
    var gasEstimate = web3.eth.estimateGas({data: '0x' + bytecode}); //gas估计
    console.log('gasEstimate = ' + gasEstimate);
    var MyContract = web3.eth.contract(abi);
    console.log('deploying contract...');
    var myContractReturned = MyContract.new({
        from: coinbase,
        data: '0x'+ bytecode,
        gas: gasEstimate + 50000
    }, function (err, myContract) {
        if (!err) {
            if (!myContract.address) {
                console.log(`myContract.transactionHash = ${myContract.transactionHash}`); // The hash of the transaction, which deploys the contract
            // check address on the second call (contract deployed)
            } else {
                console.log(`myContract.address = ${myContract.address}`); // the contract address
                global.contractAddress = myContract.address;
            }
    
        } else {
            console.log(err);
        }
    });
    

    参考:
    1、https://blog.csdn.net/DDFFR/article/details/74639418
    2、https://www.jianshu.com/p/2b24cd430a7d
    3、https://linux.cn/article-5423-1.html

    相关文章

      网友评论

          本文标题:Web3.js与以太坊区块链交互

          本文链接:https://www.haomeiwen.com/subject/itkldftx.html