區塊鏈-以太坊學習筆記(四)

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

 

 

 

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章