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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,284评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,115评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,614评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,671评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,699评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,562评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,309评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,223评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,668评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,859评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,981评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,705评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,310评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,904评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,023评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,146评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,933评论 2 355

推荐阅读更多精彩内容