solidity 智能合约(4):在js项目通过web3js调用

2019-11-29  本文已影响0人  ag4kd

1 案例源码

var Web3 = require("Web3");

async function testContract() {
    web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:7545"));
    // 合约ABI
    let abi = [
        {
            "inputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "constructor"
        },
        {
            "constant": false,
            "inputs": [
                {
                    "internalType": "uint256",
                    "name": "x",
                    "type": "uint256"
                }
            ],
            "name": "set",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        },
        {
            "constant": true,
            "inputs": [],
            "name": "get",
            "outputs": [
                {
                    "internalType": "uint256",
                    "name": "",
                    "type": "uint256"
                }
            ],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        }
    ];
    //合约地址
    let address = "0x35030F7C367bd4c7e671A7Fd2b45b96E478F5cA9";

    //获取合约实力
    let simpleStorage = new web3.eth.Contract(abi, address);
    //获取一个账户地址
    let from = web3.eth.accounts[0];
    //调用 send 函数 ,将发送一笔交易到智能合约,同时执行set函数,send 调用可以改变合约中的状态变量
    await simpleStorage.methods.set(14).send({from: "0xb70041b092b9e684d4Ee2caDBe5c3ffE6cA83c98"});

    
    // 调用 call 函数,执行智能合约中的一个只读函数,,此时调用call,不会发交易,不会改变合约中的变量的状态
    let value = await simpleStorage.methods.get().call();

    // console.log("value = " + JSON.stringify(newVar));
    console.log("value = " + value);
}

testContract();

2 创建合约实力所需的几个参数

new web3.eth.Contract(jsonInterface[, address][, options])

2.1 jsonInterface

The json interface is a json object describing the Application Binary Interface (ABI) for an Ethereum smart contract.

Using this json interface web3.js is able to create JavaScript object representing the smart contract and its methods and events using the web3.eth.Contract object.

案例中的abi是从前面一章的truffle项目复制过来的。执行 truffle compile 编译合约,就会生成对应的文件。

举个例子

[{
    "type":"constructor",
    "payable":false,
    "stateMutability":"nonpayable"
    "inputs":[{"name":"testInt","type":"uint256"}],
  },{
    "type":"function",
    "name":"foo",
    "constant":false,
    "payable":false,
    "stateMutability":"nonpayable",
    "inputs":[{"name":"b","type":"uint256"}, {"name":"c","type":"bytes32"}],
    "outputs":[{"name":"","type":"address"}]
  },{
    "type":"event",
    "name":"Event",
    "inputs":[{"indexed":true,"name":"b","type":"uint256"}, {"indexed":false,"name":"c","type":"bytes32"}],
    "anonymous":false
  },{
    "type":"event",
    "name":"Event2",
    "inputs":[{"indexed":true,"name":"b","type":"uint256"},{"indexed":false,"name":"c","type":"bytes32"}],
    "anonymous":false
}]

2.2 type类型的各种取值

2.2.1 关于一般 function 的描述

这个例子是本案例中的一个描述

{
    "constant": true,
    "inputs": [],
    "name": "get",
    "outputs": [
        {
            "internalType": "uint256",
            "name": "",
            "type": "uint256"
        }
    ],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
}

2.2.2 关于 constructor 函数的描述

{
    "type":"constructor",
    "payable":false,
    "stateMutability":"nonpayable"
    "inputs":[{"name":"testInt","type":"uint256"}],
}

描述同上。

2.2.3 关于 event 函数的描述

{
    "type":"event",
    "name":"Event2",
    "inputs":[{"indexed":true,"name":"b","type":"uint256"},{"indexed":false,"name":"c","type":"bytes32"}],
    "anonymous":false
}

2.3.4 官方案例

contract Test {
    uint a;
    address d = 0x12345678901234567890123456789012;

    function Test(uint testInt)  { a = testInt;}

    event Event(uint indexed b, bytes32 c);

    event Event2(uint indexed b, bytes32 c);

    function foo(uint b, bytes32 c) returns(address) {
        Event(b, c);
        return d;
    }
}

// would result in the JSON:
[{
    "type":"constructor",
    "payable":false,
    "stateMutability":"nonpayable"
    "inputs":[{"name":"testInt","type":"uint256"}],
  },{
    "type":"function",
    "name":"foo",
    "constant":false,
    "payable":false,
    "stateMutability":"nonpayable",
    "inputs":[{"name":"b","type":"uint256"}, {"name":"c","type":"bytes32"}],
    "outputs":[{"name":"","type":"address"}]
  },{
    "type":"event",
    "name":"Event",
    "inputs":[{"indexed":true,"name":"b","type":"uint256"}, {"indexed":false,"name":"c","type":"bytes32"}],
    "anonymous":false
  },{
    "type":"event",
    "name":"Event2",
    "inputs":[{"indexed":true,"name":"b","type":"uint256"},{"indexed":false,"name":"c","type":"bytes32"}],
    "anonymous":false
}]

3 使用合约中的方法

3.1 clone




// 创建合约实例
var contract1 = new eth.Contract(abi, address, {gasPrice: '12345678', from: fromAddress});

var contract2 = contract1.clone();

contract1contract2是两个不同合约实例。

3.2 deploy

Call this function to deploy the contract to the blockchain. After successful deployment the promise will resolve with a new contract instance.




myContract.deploy({
    data: '0x12345...',
    arguments: [123, 'My String']
})
.send({
    from: '0x1234567890123456789012345678901234567891',
    gas: 1500000,
    gasPrice: '30000000000000'
}, function(error, transactionHash){ ... })
.on('error', function(error){ ... })
.on('transactionHash', function(transactionHash){ ... })
.on('receipt', function(receipt){
   console.log(receipt.contractAddress) // contains the new contract address
})
.on('confirmation', function(confirmationNumber, receipt){ ... })
.then(function(newContractInstance){
    console.log(newContractInstance.options.address) // instance with the new contract address
});


// When the data is already set as an option to the contract itself
myContract.options.data = '0x12345...';

myContract.deploy({
    arguments: [123, 'My String']
})
.send({
    from: '0x1234567890123456789012345678901234567891',
    gas: 1500000,
    gasPrice: '30000000000000'
})
.then(function(newContractInstance){
    console.log(newContractInstance.options.address) // instance with the new contract address
});


// Simply encoding
myContract.deploy({
    data: '0x12345...',
    arguments: [123, 'My String']
})
.encodeABI();
> '0x12345...0000012345678765432'


// Gas estimation
myContract.deploy({
    data: '0x12345...',
    arguments: [123, 'My String']
})
.estimateGas(function(err, gas){
    console.log(gas);
});

3.3 methods

myContract.methods.myMethod([param1[, param2[, ...]]])

智能合约中的方法可以同上述形式来调用:





// calling a method

myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}, function(error, result){
    ...
});

// or sending and using a promise
myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
.then(function(receipt){
    // receipt can also be a new contract instance, when coming from a "contract.deploy({...}).send()"
});

// or sending and using the events

myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
.on('transactionHash', function(hash){
    ...
})
.on('receipt', function(receipt){
    ...
})
.on('confirmation', function(confirmationNumber, receipt){
    ...
})
.on('error', function(error, receipt) {
    ...
});

可以不用这种链式调用,使用asyncawait,如案例中的用法:

//调用 send 函数 ,将发送一笔交易到智能合约,同时执行set函数,send 调用可以改变合约中的状态变量
await simpleStorage.methods.set(14).send({from: "0xb70041b092b9e684d4Ee2caDBe5c3ffE6cA83c98"});


// 调用 call 函数,执行智能合约中的一个只读函数,,此时调用call,不会发交易,不会改变合约中的变量的状态
let value = await simpleStorage.methods.get().call();

3.3.1 call 和 send

代码中注释已经描述很清楚了

//调用 send 函数 ,将发送一笔交易到智能合约,同时执行set函数,send 调用可以改变合约中的状态变量
await simpleStorage.methods.set(14).send({from: "0xb70041b092b9e684d4Ee2caDBe5c3ffE6cA83c98"});


// 调用 call 函数,执行智能合约中的一个只读函数,,此时调用call,不会发交易,不会改变合约中的变量的状态
let value = await simpleStorage.methods.get().call();

3.3.2 encodeABI

myContract.methods.myMethod([param1[, param2[, ...]]]).encodeABI()
let abi_method = await simpleStorage.methods.set(14).encodeABI();

console.log("abi_method = "+ abi_method);



3.4 Events

案例中还未涉及,后续补充

上一篇 下一篇

猜你喜欢

热点阅读