一、编写合约
1. HelloWorld合约提供两个接口,分别是get()
和set()
,用于获取/设置合约变量name
。
合约内容如下:
pragma solidity ^0.4.24;
contract HelloWorld {
string name;
function HelloWorld() {
name = "Hello, World!";
}
function get()constant returns(string) {
return name;
}
function set(string n) {
name = n;
}
}
2. 合约存储位置
位于控制台目录下contracts/solidity/HelloWorld.sol
二、 部署合约
# 在控制台输入以下指令 部署成功则返回合约地址
[group:1]> deploy HelloWorld
transaction hash: 0xd0305411e36d2ca9c1a4df93e761c820f0a464367b8feb9e3fa40b0f68eb23fa
contract address:0xb3c223fc0bf6646959f254ac4e4a7e355b50a344
部署成功之后,会得到2个值:
1. transaction hash
这个transaction记录了事件“该智能合约部署”
2. contract address
调用该合约时,需要指定此合约地址
三、调用合约
1. 调用
(1)无参数
call 合约名 合约地址 合约中要调用的函数名
(2)有参数
call 合约名 合约地址 合约中要调用的函数名 参数1
2. 是否会改变账本状态
(1)查询操作 不改变
# 查看当前块高
[group:1]> getBlockNumber
1
# 调用get接口获取name变量 此处的合约地址是deploy指令返回的地址
[group:1]> call HelloWorld 0xb3c223fc0bf6646959f254ac4e4a7e355b50a344 get
---------------------------------------------------------------------------------------------
Return code: 0
description: transaction executed successfully
Return message: Success
---------------------------------------------------------------------------------------------
Return values:
[
"Hello,World!"
]
---------------------------------------------------------------------------------------------
# 查看当前块高,块高不变,因为get接口不更改账本状态
[group:1]> getBlockNumber
1
调用合约并不会改变账本状态,不改变账本状态则不会增加区块
(2)设置操作 会改变
# 调用set设置name
[group:1]> call HelloWorld 0xb3c223fc0bf6646959f254ac4e4a7e355b50a344 set "Hello, FISCO BCOS"
transaction hash: 0x7e742c44091e0d6e4e1df666d957d123116622ab90b718699ce50f54ed791f6e
---------------------------------------------------------------------------------------------
transaction status: 0x0
description: transaction executed successfully
---------------------------------------------------------------------------------------------
Output
Receipt message: Success
Return message: Success
---------------------------------------------------------------------------------------------
Event logs
Event: {}
# 再次查看当前块高,块高增加表示已出块,账本状态已更改
[group:1]> getBlockNumber
2
# 调用get接口获取name变量,检查设置是否生效
[group:1]> call HelloWorld 0xb3c223fc0bf6646959f254ac4e4a7e355b50a344 get
---------------------------------------------------------------------------------------------
Return code: 0
description: transaction executed successfully
Return message: Success
---------------------------------------------------------------------------------------------
Return values:
[
"Hello,FISCO BCOS"
]
---------------------------------------------------------------------------------------------
# 退出控制台
[group:1]> quit
3. 返回值
如果改变了账本状态,则会形成一个transaction,然后返回transaction hash