Skip to content

Latest commit

 

History

History
244 lines (174 loc) · 10.6 KB

2_第一个例子.md

File metadata and controls

244 lines (174 loc) · 10.6 KB

一个简单的合约

我们打算用来测试的合约如下:

pragma solidity ^0.4.0;

contract Calc{
/*区块链存储*/
uint count;

/*执行会写入数据,所以需要`transaction`的方式执行。*/
function add(uint a, uint b) returns(uint){
    count++;
    return a + b;
}

/*执行不会写入数据,所以允许`call`的方式执行。*/
function getCount() constant returns (uint){
    return count;
}
}

add()方法用来返回输入两个数据的和,并会对add()方法的调用次数进行计数。需要注意的是这个计数是存在区块链上的,对它的调用需要使用transaction。

getCount()返回add()函数的调用次数。由于这个函数不会修改区块链的任何状态,对它的调用使用call就可以了。

编译合约

由于合约是使用Solidity编写,所以我们可以使用web3.eth.compile.solidity来编译合约3:

//编译合约
let source = "pragma solidity ^0.4.0;contract Calc{  /*区块链存储*/  uint count;  /*执行会写入数据,所以需要`transaction`的方式执行。*/  function add(uint a, uint b) returns(uint){    count++;    return a + b;  }  /*执行不会写入数据,所以允许`call`的方式执行。*/  function getCount() returns (uint){    return count;  }}";

let calc = web3.eth.compile.solidity(source);

如果编译成功,结果如下:

{
    code: '0x606060405234610000575b607e806100176000396000f3606060405260e060020a6000350463771602f781146026578063a87d942c146048575b6000565b3460005760366004356024356064565b60408051918252519081900360200190f35b3460005760366077565b60408051918252519081900360200190f35b6000805460010190558181015b92915050565b6000545b9056',
    info: {
        source: 'pragma solidity ^0.4.0;contract Calc{  /*区块链存储*/  uint count;  /*执行会写入数据,所以需要`transaction`的方式执行。*/  function add(uint a, uint b) returns(uint){    count++;    return a + b;  }  /*执行不会写入数据,所以允许`call`的方式执行。*/  function getCount() returns (uint){    return count;  }}',
        language: 'Solidity',
        languageVersion: '0.4.6+commit.2dabbdf0.Emscripten.clang',
        compilerVersion: '0.4.6+commit.2dabbdf0.Emscripten.clang',
        abiDefinition: [
            [
                Object
            ],
            [
                Object
            ]
        ],
        userDoc: {
            methods: {
                
            }
        },
        developerDoc: {
            methods: {
                
            }
        }
    }
}

如果报错 Error: Method eth_compileSolidity not supported.

Solidity 的编译现在不能直接用 web3 这个包来编译了:

var compiled = web3.eth.compile.solidity(contractSource)

以前可以这样用web3来编译,可是现在会报错:

Returned error: Error: Method eth_compileSolidity not supported. 原因是 web3 的 Solidity 编译器已经被移除了。

替代方案:使用 solc 来编译 Solidity:

const solc = require('solc')
const solcOutput = solc.compile({sources: {main: contractSource}}, 1)

使用web3.js编译,发布,调用的完整源码

let Web3 = require('web3');
let web3;

if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
} else {
    // set the provider you want from Web3.providers
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}

let from = web3.eth.accounts[0];

//编译合约
let source = "pragma solidity ^0.4.0;contract Calc{  /*区块链存储*/  uint count;  /*执行会写入数据,所以需要`transaction`的方式执行。*/  function add(uint a, uint b) returns(uint){    count++;    return a + b;  }  /*执行不会写入数据,所以允许`call`的方式执行。*/  function getCount() constant returns (uint){    return count;  }}";
let calcCompiled = web3.eth.compile.solidity(source);

console.log(calcCompiled);
console.log("ABI definition:");
console.log(calcCompiled["info"]["abiDefinition"]);

//得到合约对象
let abiDefinition = calcCompiled["info"]["abiDefinition"];
let calcContract = web3.eth.contract(abiDefinition);

直接运行可能会报错 TypeError: Cannot read property 'abiDefinition' of undefined

编译后的ABI存放在solcOutput.contracts['main:Calc'].interface中(合约名字叫Calc), 而编译后的字节码存放在solcOutput.contracts['main:Calc'].bytecode

部署合约

获取合约的代码,部署时传递的就是合约编译后的二进制码

let deployCode = calcCompiled["code"];

部署者的地址,当前取默认账户的第一个地址。

let deployeAddr = web3.eth.accounts[0];

异步方式,部署合约

let Web3 = require('web3');
let web3;
const solc = require('solc')

if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
} else {
    // set the provider you want from Web3.providers
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));
}

let from = web3.eth.accounts[0];
// console.log(from);

//编译合约
let source = "pragma solidity ^0.4.0;contract Calc{  /*区块链存储*/  uint count;  /*执行会写入数据,所以需要`transaction`的方式执行。*/ uint result; function add(uint a, uint b) returns(uint){    count++;  result = a + b;  return result;  }  /*执行不会写入数据,所以允许`call`的方式执行。*/  function getCount() constant returns (uint){    return count;  } function getResult() constant returns (uint){ return result; }}";

// let source = "pragma solidity ^0.4.0; contract Calc {/*区块链存储*/uint count; /*执行会写入数据,所以需要`transaction`的方式执行。*/uint result; /*执行会写入数据,所以需要`transaction`的方式执行。*/function add(uint a, uint b)returns(uint) {count++; result = a + b; return result; }/*执行不会写入数据,所以允许`call`的方式执行。*/function getCount()constant returns (uint) {return count; }} function getResult() constant returns (uint){ return result; }}";


// let calcCompiled = web3.eth.compile.solidity(source);
const calcCompiled = solc.compile({ sources: { main: source } }, 1)

//得到合约对象
let abiDefinition = calcCompiled.contracts['main:Calc'].interface;


//2. 部署合约

//2.1 获取合约的代码,部署时传递的就是合约编译后的二进制码
let deployCode = calcCompiled.contracts['main:Calc'].bytecode;

//2.2 部署者的地址,当前取默认账户的第一个地址。
let deployeAddr = web3.eth.accounts[0];

// console.log(calcContract);


// // creation of contract object
let calcContract = web3.eth.contract(JSON.parse(abiDefinition));

// return;
let gasEstimate = web3.eth.estimateGas({ data: deployCode });
console.log(gasEstimate);
// return;
//2.3 异步方式,部署合约
let myContractReturned = calcContract.new({
    data: deployCode,
    from: deployeAddr,
    gas: gasEstimate
}, function(err, myContract) {
    console.log("+++++");
    if (!err) {
        // 注意:这个回调会触发两次
        //一次是合约的交易哈希属性完成
        //另一次是在某个地址上完成部署

        // 通过判断是否有地址,来确认是第一次调用,还是第二次调用。
        if (!myContract.address) {
            console.log("contract deploy transaction hash: " + myContract.transactionHash) //部署合约的交易哈希值

            // 合约发布成功后,才能调用后续的方法
        } else {
            console.log("contract deploy address: " + myContract.address) // 合约的部署地址

            //使用transaction方式调用,写入到区块链上
            myContract.add.sendTransaction(1, 2, {
                from: deployeAddr
            });

            console.log("after contract deploy, call:" + myContract.getCount.call());
            console.log("result:" + myContract.getResult.call());
        }

        // 函数返回对象`myContractReturned`和回调函数对象`myContract`是 "myContractReturned" === "myContract",
        // 所以最终`myContractReturned`这个对象里面的合约地址属性也会被设置。
        // `myContractReturned`一开始返回的结果是没有设置的。
    } else {
        console.log(err);
    }
});

//注意,异步执行,此时还是没有地址的。 console.log("returned deployed didn't have address now: " + myContractReturned.address);

发布合约

web3.js其实也像框架一样对合约的操作进行了封装。发布合约时,可以使用web3.eth.contract的new方法4。

let myContractReturned = calcContract.new({
    data: deployCode,
    from: deployeAddr
}, function(err, myContract) {
    if (!err) {
        // 注意:这个回调会触发两次
        //一次是合约的交易哈希属性完成
        //另一次是在某个地址上完成部署

        // 通过判断是否有地址,来确认是第一次调用,还是第二次调用。
        if (!myContract.address) {
            console.log("contract deploy transaction hash: " + myContract.transactionHash) //部署合约的交易哈希值

            // 合约发布成功
        } else {
        }
});

部署过程中需要主要的是,new方法的回调会执行两次,第一次是合约的交易创建完成,第二次是在某个地址上完成部署。需要注意的是只有在部署完成后,才能进行方法该用,否则会报错

TypeError: myContractReturned.add is not a function。

调用合约

由于web3.js封装了合约调用的方法。我们可以使用可以使用web3.eth.contract的里的sendTransaction来修改区块链数据。在这里有个坑,有可能会出现Error: invalid address,原因是没有传from,交易发起者的地址。在使用web3.js的API都需留意,出现这种找不到地址的,都看看from字段吧。

//使用transaction方式调用,写入到区块链上
myContract.add.sendTransaction(1, 2,{
    from: deployeAddr
});

console.log("after contract deploy, call:" + myContract.getCount.call());

需要注意的是,如果要修改区块链上的数据,一定要使用sendTransaction,这会消耗gas。如果不修改区块链上的数据,使用call,这样不会消耗gas。