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

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"
}
  • type: "function", "constructor" (can be omitted, defaulting to "function"; "fallback" also possible but not relevant(相关) in web3.js);
  • name: the name of the function (only present for function types);
  • constant: true if function is specified to not modify the blockchain state;
  • payable: true if function accepts ether, defaults to false;
  • stateMutability(可变性): a string with one of the following values: pure (specified to not read blockchain state), view (same as constant above), nonpayable and payable (same as payable above);
  • inputs: an array of objects, each of which contains:
  • name: the name of the parameter;
  • type: the canonical type of the parameter.
  • outputs: an array of objects same as inputs, can be omitted if no outputs exist.

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
}
  • type: always "event"
  • name: the name of the event;
  • anonymous: true if the event was declared as anonymous.
  • inputs: an array of objects, each of which contains:
  • name: the name of the parameter;
  • type: the canonical type of the parameter.
  • indexed: true if the field is part of the log’s topics, false if it one of the log’s data segment.

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.

  • 发布合约到区块链上

  • 参数:可选
  • data(字符串):合约的字节码
  • argument(数组):可选,用来传递参数到构造函数

  • 返回值:交易对象

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[, ...]]])

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

  • The name: myContract.methods.myMethod(123)
  • The name with parameters: myContract.methods['myMethod(uint256)'](123)
  • The signature: myContract.methods['0x58cf5f10'](123)

  • 功能:调用智能合约中的方法

  • 参数:Parameters of any method depend on the smart contracts methods, defined in the JSON interface.

  • 返回值:一个交易对象

// 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);
  • 功能:Encodes the ABI for this method. This can be used to send a transaction, call a method, or pass it into another smart contracts method as arguments.

  • 参数:无

  • 返回值(字符串):The encoded ABI byte code to send via a transaction or call.

3.4 Events

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

你可能感兴趣的:(智能合约,javascript,web3,区块链,开发语言)