web3.js調用智能合約

image

本文將用web3.js走一個簡單調用智能合約流程。html

1

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

代碼參考。按照自動化生成的框架進行簡單的修改以下:web

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編譯一下json

image

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

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)ui

建立一個Solidity的合約對象,用來在某個地址上初始化合約。.net

參數:

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

相關文章
相關標籤/搜索