web3.js调用智能合约

1,600 阅读2分钟

image

本文将用web3.js走一个简单调用智能合约流程。

1

利用truffleinit 命令生成智能合约框架

代码参考。按照自动化生成的框架进行简单的修改如下:

contracts\Migrations0.sol

pragma solidity ^0.4.23;

contract Migrations0 {

    //编写一个函数,来完成两个数的相加操作

    function aAndb(uint a,uint b) public constant returns (uint) {

      return a+b;

    }

}

migrations\1_initial_migration0.js

var Migrations = artifacts.require("./Migrations0.sol");

module.exports = function(deployer) {

  deployer.deploy(Migrations);

};

2

编译

在truffle develop编译一下

image

在./build/contracts文件中生成json文件

image

其中:

"abi": [

    {

      "constant": true,

      "inputs": [

        {

          "name": "a",

          "type": "uint256"

        },

        {

          "name": "b",

          "type": "uint256"

        }

      ],

      "name": "aAndb",

      "outputs": [

        {

          "name": "",

          "type": "uint256"

        }

      ],

      "payable": false,

      "stateMutability": "view",

      "type": "function"

    }

  ]

压缩后的abi:

[{"constant":true,"inputs":[{"name":"a","type":"uint256"},{"name":"b","type":"uint256"}],"name":"aAndb","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]

3

部署

Migrations0的合约地址:0x345ca3e014aaf5dca488057592ee47305d9b3e10

image

4

调用

image

web3.eth.contract:

web3.eth.contract(abiArray)

创建一个Solidity的合约对象,用来在某个地址上初始化合约。

参数:

Array - 一到多个描述合约的函数,事件的ABI对象。

返回值:

Object - 一个合约对象。

具体参考http://web3.tryblockchain.org/Web3.js-api-refrence.html

本文作者:HiBlock区块链技术布道群-阿飞

原文发布于CSDN

原文链接:

https://blog.csdn.net/lxfgzm/article/details/80646578

加微信baobaotalk_com,加入技术布道群

线下活动推荐

技术工坊|如何利用ERC875协议开发世界杯区块链门票?(北京)

image