Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to develop intelligent contracts for EOSIO platform

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to develop an intelligent contract for the EOSIO platform". In the daily operation, I believe many people have doubts about how to develop an intelligent contract for the EOSIO platform. The editor consulted all kinds of materials and sorted out a simple and easy-to-use method of operation. I hope it will be helpful to answer the doubts of "how to develop an intelligent contract for the EOSIO platform". Next, please follow the editor to study!

The purpose of the example smart contract is to simulate the election. I created an EOSIO user to host smart contracts. Two citizen users were created to vote for the candidate. The voting record is kept in the EOSIO block chain. In this example, all operations are run in command mode. Let's get started.

Develop intelligent contracts

EOSIO executes intelligent contracts developed in the WebAssembly standard. So I used C++ to develop an election intelligence contract. The following is the complete source code for election.cpp:

# include using namespace eosio;class election: public contract {private: / / create the multi index tables to store the data / @ abi table struct candidate {uint64_t _ key; / / primary key std::string _ name; / / candidate name uint32_t _ count = 0; / / voted count uint64_t primary_key () const {return _ key;}}; typedef eosio::multi_index candidates; / / @ abi table struct voter {uint64_t _ key Uint64_t _ candidate_key; / / name of poll account_name _ account; / / this account has voted, avoid duplicate voter uint64_t primary_key () const {return _ key;} uint64_t candidate_key () const {return _ candidate_key;}}; typedef eosio::multi_index voters; / / local instances of the multi indexes candidates_ candidates; voters _ voters; uint64_t _ candidates_count Public: election (account_name s): contract (s), _ candidates (s, s), _ voters (s, s), _ candidates_count (0) {} / / public methods exposed via the ABI / / on candidates / @ abi action void version () {print ("Election Smart Contract version 0.0.1\ n");} / / @ abi action void addc (std::string name) {print ("Adding candidate", name, "\ n"); uint64_t key = _ candidates.available_primary_key (); / / update the table to include a new candidate _ candidates.emplace (get_self (), [&] (auto & p) {p._key = key; p._name = name; p._count = 0;}) Print ("Candidate added successfully. Candidate_key = ", key,"\ n ");}; / / @ abi action void reset () {/ / Get all keys of _ candidates std::vector keysForDeletion; for (auto & itr: _ candidates) {keysForDeletion.push_back (itr.primary_key ());} / / now delete each item for that poll for (uint64_t key: keysForDeletion) {auto itr = _ candidates.find (key) If (itr! = _ candidates.end ()) {_ candidates.erase (itr);}} / / Get all keys of _ voters keysForDeletion.empty (); for (auto & itr: _ voters) {keysForDeletion.push_back (itr.primary_key ());} / now delete each item for that poll for (uint64_t key: keysForDeletion) {auto itr = _ voters.find (key) If (itr! = _ voters.end () {_ voters.erase (itr);}} print ("candidates and voters reset successfully.\ n");}; / / @ abi action void results () {print ("Start listing voted results\ n"); for (auto& item: _ candidates) {print ("Candidate", item._name, "has voted count:", item._count, "\ n") }}; / / @ abi action void vote (account_name s, uint64_t candidate_key) {require_auth (s); bool found = false; / / Did the voter vote before? For (auto& item: _ voters) {if (item._account = = s) {found = true; break;}} eosio_assert (! found, "You're voted already!"); / / Findout the candidate by id std::vector keysForModify For (auto& item: _ candidates) {if (item.primary_key () = = candidate_key) {keysForModify.push_back (item.primary_key ()); break;}} if (keysForModify.size () = = 0) {eosio_assert (found, "Invalid candidate id!"); return } / / Update the voted count inside the candidate for (uint64_t key: keysForModify) {auto itr = _ candidates.find (key); auto candidate = _ candidates.get (key); if (itr! = _ candidates.end ()) {_ candidates.modify (itr, get_self (), [&] (auto& p) {p. Print ("Voted candidate:", candidate._name, "successfully\ n");} / / Add this user to voters array _ voters.emplace (get_self (), [&] (auto& p) {p._key = _ voters.available_primary_key (); p._candidate_key = candidate_key; p._account = s;});};} EOSIO_ABI (election, (version) (reset) (addc) (results) (vote))

Note that the last line EOSIO_ABI () is a macro statement that automatically generates the ABI file instead of writing it manually. The ABI file is used to define the submit action handler. This tells EOSIO the definition of the handler in the smart contract.

EOSIO provides us with a multi-index database API, which can save the data to the blockchain. In the above election intelligence contract, I defined two multi_index (similar to the SQL table): candidates and voters. There are actually two arrays that store two structures: candidates and voters. I use C++ STL to manipulate multi_index, such as add,update,delete.

Notice that both structures are marked with / @ abi table at the beginning. This tells the EOSIO abi generator to generate the ABI table in the election.abi file. It's convenient.

Compile the election smart contract:

$eosiocpp-o election.wast election.cpp

Generate WAST and WASM files respectively. But that's not enough for EOSIO. We also need to generate the ABI file:

Optional file for $eosiocpp-g election.abi election.cppVisual Studio Code

To enhance the development experience, I created a properties file c_cpp_properties.json for Visual Studio Code (VSCode) and told it how to find the header file. The file needs to be stored in the .vscode directory, as follows:

The contents of the .vscode / c_cpp_properties file are as follows:

{"configurations": [{"name": "Linux", "includePath": ["${workspaceFolder} / *", "~ / eos/contracts", "~ / opt/boost/include"], "defines": [], "compilerPath": "/ usr/bin/clang++-4.0", "cStandard": "c11", "cppStandard": "c11" "intelliSenseMode": "clang-x64"}], "version": 4} start EOSIO

Well-configured virtual machines are used all the time (mentioned in part 1). To start a single-node Testnet server:

$nodeos-e-p eosio-- plugin eosio::wallet_api_plugin-- plugin eosio::chain_api_plugin-- plugin eosio::history_api_plugin-- access-control-allow-origin=*-- contracts-console

Click here for more information about the nodeos parameter.

Create an account

The next task is to unlock the default wallet. EOSIO stores the key pair in the wallet. The server needs to be unlocked every time it restarts or every 15 minutes. Unlock the wallet:

$cleos wallet unlock-- password ${wallet_password}

We need to create an owner key pair and an active key pair, respectively. Then import the private key into the wallet. Type the following command:

$cleos create key # Create an owner key$ cleos create key # Create an active key$ cleos wallet import ${private_owner_key} $cleos wallet import ${private_active_key}

Don't forget to record these key pairs somewhere.

The next task is to create a new account to hold the election smart contract. Type the following command:

$cleos create account eosio election ${public_owner_key} ${public_active_key}

In addition, create two citizens for the voting simulation:

$cleos create account eosio voter1 ${public_owner_key} ${public_active_key} $cleos create account eosio voter2 ${public_owner_key} ${public_active_key} deployment Smart contract

Enter the following command to upload the election smart contract:

$cleos set contract election.. / election-p election

The result is similar to the following figure:

Run a smart contract

We can try to run the contract.

1. Run the version operation

$cleos push action election version'- p election

We can output from the nodeos inspection console:

two。 Increase the number of election candidates

$cleos push action election addc'["Hillary Clinton"]'- p election$ cleos push action election addc'["Donald J. Trump"]'- p election

3. Display candidate databases stored in the block chain

$cleos get table election election candidate

The result is shown in the figure:

4. Mock voting (both voters were voted for Donald J. Trump)

$cleos push action election vote'["voter1", 1]'- p voter1 $cleos push action election vote'["voter2", 1]'- p voter2

If voter1 votes again:

$cleos push action election vote'["voter1", 0]'- p voter1

EOSIO will return an exception:

5. View the voting results

$cleos get table election election candidate

As you can see, the candidate "Donald J. Trump" cast 2. This means that the election intelligence contract is working!

At this point, the study on "how to develop an intelligent contract for the EOSIO platform" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report