web3js调用已部署智能合约的function


#1

简介与环境

简介

web3.js是以太坊提供的一个Javascript库,它封装了以太坊的JSON RPC API、IPC调用,提供了一系列与以太坊区块链交互的J对象和函数。几乎囊括JSON RP的API,还可以编译和部署智能合约以及调用智能合约等,其中最重要的就是与智能合约交互的JS对象及函数。

开发环境

macos操作系统
nodejs 8.9.4
npm 5.6.0

调用智能合约

首先需要使用Solidity编写智能合约,最简单的合约如下,不与区块发生联系:

pragma solidity ^0.4.2;
 contract hello {
 
     function hello() public {
         
     }
 
     function say() constant public returns (string) {
         return "Hello World!";
     }
 }

注:Solidity在线编译环境地址 点我

编译后会产生很多不同的东西,部分如下:

WEB3DEPLOY

var helloContract = web3.eth.contract([{"constant":true,"inputs":[],"name":"say","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function","stateMutability":"view"},{"inputs":[],"payable":false,"type":"constructor","stateMutability":"nonpayable"}]);
var hello = helloContract.new(
   {
     from: web3.eth.accounts[0], 
     data: '0x6060604052341561000c57fe5b5b5b5b6101598061001e6000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063954ab4b21461003b575bfe5b341561004357fe5b61004b6100d4565b604051808060200182810382528381815181526020019150805190602001908083836000831461009a575b80518252602083111561009a57602082019150602081019050602083039250610076565b505050905090810190601f1680156100c65780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6100dc610119565b604060405190810160405280600c81526020017f48656c6c6f20576f726c6421000000000000000000000000000000000000000081525090505b90565b6020604051908101604052806000815250905600a165627a7a72305820b88ade0e1b40d9f8ffeba3f2bc9aa2ee4a1ae17f03fc52fc568812eb5d96f5ad0029', 
     gas: '4700000'
   }, function (e, contract){
    console.log(e, contract);
    if (typeof contract.address !== 'undefined') {
         console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
    }
 })

ABI (后面会用到):

[
    {
        "constant": true,
        "inputs": [],
        "name": "say",
        "outputs": [
            {
                "name": "",
                "type": "string"
            }
        ],
        "payable": false,
        "type": "function",
        "stateMutability": "view"
    },
    {
        "inputs": [],
        "payable": false,
        "type": "constructor",
        "stateMutability": "nonpayable"
    }
]

创建一个test.js,内容如下:

// 引入依赖模块
var express = require("express")
var Web3 = require("web3")
var net = require("net")
var http = require("http")

var web3;
// 创建web3对象并连接到以太坊节点
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("http://192.168.53.60:8545"));
}

// 合约ABI
var abi = [{"constant":true,"inputs":[],"name":"say","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"}];
// 合约地址
var address = "0xf77976c9a552f2934d3694c38fbd057ae803ef45";
// 通过ABI和地址获取已部署的合约对象
var helloContract = new web3.eth.Contract(abi,address);

http.createServer(function (request, response) {
    
    // 调用智能合约方法
    var helloResult = helloContract.methods.say().call().then(function(result){
    console.log("返回值:" + result);
    // 发送 HTTP 头部 
    // HTTP 状态值: 200 : OK
    // 内容类型: text/plain
    response.writeHead(200, {'Content-Type': 'text/plain'});
    
    // 发送响应数据
    response.end(result);
});
    
}).listen(8888);

// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');

启动之前应该先加载test.js所依赖的模块:

$ npm install express  
$ npm install web3  
$ npm install http

运行

    $ node test.js

终端打印出"Server running at http://127.0.0.1:8888" 时即可访问"http://127.0.0.1:8888" ,网页会返回"Hello World"!

作者:从一打到替补席
链接:https://www.jianshu.com/p/ec9aaace7158
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。