EOS开发从智能合约开始(三)—— "Hello World" 合约

Hello World 智能合约

本教程假定你已经看过了EOS开发从智能合约开始(一)EOS开发从智能合约开始(二)——通证Token合约介绍

现在将创建我们的第一个“Hello World”合约。在文件夹中创建一个名为“Hello”,进入这个新文件夹,然后创建一个文件“Hello .CPP”,内容如下:

hello/hello.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <eosiolib/eosio.hpp>
#include <eosiolib/print.hpp>
using namespace eosio;

class hello : public eosio::contract {
public:
using contract::contract;

/// @abi action
void hi( account_name user ) {
print( "Hello, ", name{user} );
}
};

EOSIO_ABI( hello, (hi) )

你可以将代码编译为 web assembly (.wast) ,如下所示:

1
$ eosiocpp -o hello.wast hello.cpp

注意:编译器可能会生成警告。这些警告可以被忽略。

现在生成ABI:

1
2
$ eosiocpp -g hello.abi hello.cpp
Generated hello.abi

创建帐户并上传合约:

1
2
3
4
$ cleos create account eosio hello.code EOS7ijWCBmoXBi3CgtK7DJxentZZeTkeUnaSDvyro9dq7Sd1C3dC4 EOS7ijWCBmoXBi3CgtK7DJxentZZeTkeUnaSDvyro9dq7Sd1C3dC4
...
$ cleos set contract hello.code ../hello -p hello.code@active
...

现在我们就可以运行合约了:

1
2
3
4
$ cleos push action hello.code hi '["user"]' -p user@active
executed transaction: 4c10c1426c16b1656e802f3302677594731b380b18a44851d38e8b5275072857 244 bytes 1000 cycles
# hello.code <= hello.code::hi {"user":"user"}
>> Hello, user

如果你正在参看nodeos的输出,你可能没有看到任何来自nodeos的输出,表明发生了状况。你可以使用--contracts-console选项重新启动nodeos,以便将打印调试输出发送到控制台,输出将如下所示:

1
2
3
4
5
6
1025500ms thread-0   producer_plugin.cpp:944       produce_block        ] Produced block 00004de945a23f63... #19945 @ 2018-05-25T19:17:05.500 signed by eosio [trxs: 0, lib: 19944, confirmed: 0]
1025830ms thread-0 apply_context.cpp:28 print_debug ]
[(hello.code,hi)->hello.code]: CONSOLE OUTPUT BEGIN =====================
Hello, user
[(hello.code,hi)->hello.code]: CONSOLE OUTPUT END =====================
1026000ms thread-0 producer_plugin.cpp:944 produce_block ] Produced block 00004deaebee2dc5... #19946 @ 2018-05-25T19:17:06.000 signed by eosio [trxs: 1, lib: 19945, confirmed: 0]

在这个时候,合约允许任何人授权它,我们也可以说:

1
2
3
4
$ cleos push action hello.code hi '["user"]' -p tester@active
executed transaction: 28d92256c8ffd8b0255be324e4596b7c745f50f85722d0c4400471bc184b9a16 244 bytes 1000 cycles
# hello.code <= hello.code::hi {"user":"user"}
>> Hello, user

在这种情况下,tester是被授权的用户,而user只是一个参数。如果我们希望我们的联系人认证正在说“hi”的用户,那么我们需要修改合同来请求认证。

修改hello.cpp中的hi()函数如下:

1
2
3
4
void hi( account_name user ) {
require_auth( user );
print( "Hello, ", name{user} );
}

重复上面步骤编译 wast 文件并生成ABI,然后再次设置合约来部署更新。

现在,如果我们试图使用的用户和权限不匹配,合约将引发一个错误:

1
2
3
4
5
6
$ cleos push action hello.code hi '["tester"]' -p user@active
Error 3030001: missing required authority
Ensure that you have the related authority inside your transaction!;
If you are currently using 'cleos push action' command, try to add the relevant authority using -p option.
Error Details:
missing authority of tester

调试信息的输出类似于下面的内容:

1
2
3
4
5
6
7
8
9
1340500ms thread-0   producer_plugin.cpp:944       produce_block        ] Produced block 0000505f9de7f4b9... #20575 @ 2018-05-25T19:22:20.500 signed by eosio [trxs: 0, lib: 20574, confirmed: 0]
1340515ms thread-0 http_plugin.cpp:369 handle_exception ] FC Exception encountered while processing chain.push_transaction: 3090004 missing_auth_exception: missing required authority
missing authority of user
{"account":"user"}
thread-0 apply_context.cpp:123 require_authorization

{"_pending_console_output.str()":""}
thread-0 apply_context.cpp:53 exec_one
1341005ms thread-0 producer_plugin.cpp:944 produce_block ] Produced block 000050601ffc5bd9... #20576 @ 2018-05-25T19:22:21.000 signed by eosio [trxs: 0, lib: 20575, confirmed: 0]

我们可以通过给予tester的许可来解决这个问题:

1
2
3
4
$ cleos push action hello.code hi '["tester"]' -p tester@active
executed transaction: 235bd766c2097f4a698cfb948eb2e709532df8d18458b92c9c6aae74ed8e4518 244 bytes 1000 cycles
# hello.code <= hello.code::hi {"user":"tester"}
>> Hello, tester

Ricardian Contract 李嘉图合约

每一个智能合约都必须有一个匹配的李嘉图合约。李嘉图合约规定了与智能合约的每一个行为相关的具有法律约束力的行为。这里列出了符合李嘉图合约的Hello World智能合约。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
## CONTRACT FOR HELLO WORLD

### Parameters
Input parameters: NONE

Implied parameters:

* _**account_name**_ (name of the party invoking and signing the contract)

### Intent
INTENT. The intention of the author and the invoker of this contract is to print output. It shall have no other effect.

### Term
TERM. This Contract expires at the conclusion of code execution.

### Warranty
WARRANTY. {{ account_name }} shall uphold its Obligations under this Contract in a timely and workmanlike manner, using knowledge and recommendations for performing the services which meet generally acceptable standards set forth by EOSIO Blockchain Block Producers.

### Default
DEFAULT. The occurrence of any of the following shall constitute a material default under this Contract:

### Remedies
REMEDIES. In addition to any and all other rights a party may have available according to law, if a party defaults by failing to substantially perform any provision, term or condition of this Contract, the other party may terminate the Contract by providing written notice to the defaulting party. This notice shall describe with sufficient detail the nature of the default. The party receiving such notice shall promptly be removed from being a Block Producer and this Contract shall be automatically terminated.

### Force Majeure
FORCE MAJEURE. If performance of this Contract or any obligation under this Contract is prevented, restricted, or interfered with by causes beyond either party's reasonable control ("Force Majeure"), and if the party unable to carry out its obligations gives the other party prompt written notice of such event, then the obligations of the party invoking this provision shall be suspended to the extent necessary by such event. The term Force Majeure shall include, without limitation, acts of God, fire, explosion, vandalism, storm or other similar occurrence, orders or acts of military or civil authority, or by national emergencies, insurrections, riots, or wars, or strikes, lock-outs, work stoppages, or supplier failures. The excused party shall use reasonable efforts under the circumstances to avoid or remove such causes of non-performance and shall proceed to perform with reasonable dispatch whenever such causes are removed or ceased. An act or omission shall be deemed within the reasonable control of a party if committed, omitted, or caused by such party, or its employees, officers, agents, or affiliates.

### Dispute Resolution
DISPUTE RESOLUTION. Any controversies or disputes arising out of or relating to this Contract will be resolved by binding arbitration under the default rules set forth by the EOSIO Blockchain. The arbitrator's award will be final, and judgment may be entered upon it by any court having proper jurisdiction.

### Entire Agreement
ENTIRE AGREEMENT. This Contract contains the entire agreement of the parties, and there are no other promises or conditions in any other agreement whether oral or written concerning the subject matter of this Contract. This Contract supersedes any prior written or oral agreements between the parties.

### Severability
SEVERABILITY. If any provision of this Contract will be held to be invalid or unenforceable for any reason, the remaining provisions will continue to be valid and enforceable. If a court finds that any provision of this Contract is invalid or unenforceable, but that by limiting such provision it would become valid and enforceable, then such provision will be deemed to be written, construed, and enforced as so limited.

### Amendment
AMENDMENT. This Contract may be modified or amended in writing by mutual agreement between the parties, if the writing is signed by the party obligated under the amendment.

### Governing Law
GOVERNING LAW. This Contract shall be construed in accordance with the Maxims of Equity.

### Notice
NOTICE. Any notice or communication required or permitted under this Contract shall be sufficiently given if delivered to a verifiable email address or to such other email address as one party may have publicly furnished in writing, or published on a broadcast contract provided by this blockchain for purposes of providing notices of this type.

### Waiver of Contractual Right
WAIVER OF CONTRACTUAL RIGHT. The failure of either party to enforce any provision of this Contract shall not be construed as a waiver or limitation of that party's right to subsequently enforce and compel strict compliance with every provision of this Contract.

### Arbitrator's Fees to Prevailing Party
ARBITRATOR’S FEES TO PREVAILING PARTY. In any action arising hereunder or any separate action pertaining to the validity of this Agreement, both sides shall pay half the initial cost of arbitration, and the prevailing party shall be awarded reasonable arbitrator's fees and costs.

### Construction and Interpretation
CONSTRUCTION AND INTERPRETATION. The rule requiring construction or interpretation against the drafter is waived. The document shall be deemed as if it were drafted by both parties in a mutual effort.

### In Witness Whereof
IN WITNESS WHEREOF, the parties hereto have caused this Agreement to be executed by themselves or their duly authorized representatives as of the date of execution, and authorized as proven by the cryptographic signature on the transaction that invokes this contract.

另:《EOS智能合约与DApp开发入门》教程已经上线,欢迎大家关注:

EOS教程

本教程帮助你快速入门EOS区块链去中心化应用的开发,内容涵盖EOS工具链、账户与钱包、发行代币、智能合约开发与部署、使用代码与智能合约交互等核心知识点,最后综合运用React和EOS的各知识点完成一个便签DApp的开发。

  • web3j教程,主要是针对java和android程序员进行区块链以太坊开发的web3j详解。
  • 以太坊教程,主要介绍智能合约与dapp应用开发,适合入门。
  • 以太坊开发,主要是介绍使用node.js、mongodb、区块链、ipfs实现去中心化电商DApp实战,适合进阶。
  • python以太坊,主要是针对python工程师使用web3.py进行区块链以太坊开发的详解。
  • php以太坊,主要是介绍使用php进行智能合约开发交互,进行账号创建、交易、转账、代币开发以及过滤器和事件等内容。

汇智网原创翻译,转载请标明出处。原文