1. 程式人生 > >JavaScript API部署呼叫智慧合約

JavaScript API部署呼叫智慧合約

合約:

contract SimpleTest {
    uint data;
    function set(uint n) public {
        data = n*3;
    }
    function get() public returns (uint) {
        return data;
    }
}

編譯合約

var source = 'contract SimpleTest {uint data;function set(uint n) public {data = n*3;}function get() public returns (uint) {return data;}}'

呼叫web3中的方法編譯上面的source變數:

var compiled = web3.eth.compile.solidity(source);

編譯結果:

var code = '0x608060405234801561001057600080fd5b5060e28061001f6000396000f3006080604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806360fe47b114604e5780636d4ce63c146078575b600080fd5b348015605957600080fd5b5060766004803603810190808035906020019092919050505060a0565b005b348015608357600080fd5b50608a60ad565b6040518082815260200191505060405180910390f35b6003810260008190555050565b600080549050905600a165627a7a7230582010be0b1da73b1ecf4cbced8c6ff8eb9b29d01034260ab552932800bd69a575fa0029'

var abi = '[ { "constant": true, "inputs": [], "name": "get", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "n", "type": "uint256" } ], "name": "set", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" } ]'

部署合約

使用上述生成的code和abi把合約部署到以太坊上。需要挖礦來確認該筆交易。

web3.eth.contract(abi).new({from:"0x6815515f32312f65718bc0b1ee8d900c27167d85",data:code})

這個方法也被廢除,故而我們採取web3deploy進行部署:

var simpletestContract = web3.eth.contract([{"constant":false,"inputs":[{"name":"n","type":"uint256"}],"name":"set","outputs":[],"payable":false,"type":"function","stateMutability":"nonpayable"},{"constant":false,"inputs":[],"name":"get","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function","stateMutability":"nonpayable"}]); 
var simpletest = simpletestContract.new( { from: web3.eth.accounts[0], data: '0x6060604052341561000c57fe5b5b60c98061001b6000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806360fe47b11460445780636d4ce63c146061575bfe5b3415604b57fe5b605f60048080359060200190919050506084565b005b3415606857fe5b606e6092565b6040518082815260200191505060405180910390f35b600381026000819055505b50565b600060005490505b905600a165627a7a723058208181481e86008df4345b2647d9ae52b4f3506a91e10859601bcf04d2a0ef30660029', gas: '4700000' }, function (e, contract){ console.log(e, contract); if (typeof contract.address !== 'undefined') { console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash); } })

部署成功,合約地址為:0x9149894f935571995aee5fdf0dbe4cc9d6743624

呼叫合約的set方法:

simpletest.set.sendTransaction(22,{from:eth.accounts[0]})

呼叫get方法檢視結果:

simpletest.get.call()