web3.js调用智能合约
上文讲到:
Atom工具的使用和web3.js的基本介绍,今天看看利用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编译一下
在./build/contracts文件中生成json文件
其中:
"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
4、调用
web3.eth.contract:
web3.eth.contract(abiArray)
创建一个Solidity的合约对象,用来在某个地址上初始化合约。
参数:
Array - 一到多个描述合约的函数,事件的ABI对象。
返回值:
Object - 一个合约对象。
具体参考http://web3.tryblockchain.org/Web3.js-api-refrence.html