How to write a smart contract in eos

A smart contract is an important part of dApp development. In the EOS blockchain network, a smart contract helps you saving all logic and data which you want on the blockchain.
In this post, you will be guided to creating a simple smart contract and deploy it to the EOS testnet and EOS mainnet.

Prerequisites

EOSIO versions:

  • eosio: 2.0.0
  • eosio.cdt: 1.7.0
  • eosio.contracts: 1.9.0

Programming language & Operating systems:

  • C++
  • Linux: Ubuntu, Centos 7, MacOS 10.14 (Mojave) and higher, Amazon Linux 2

Development tools:

  • Sublime Text
  • Atom Editor
  • CLion
  • Eclipse
  • Visual Studio Code

Create a smart contract

Basic definations

Before creating a smart contract, here is a list of definition that you should understand first:

  • Action: Each action is a representation of your business logic, for example, in bank we have 2 main functions: transfer and withdraw. To present it on a smart contract, you will write the logic for it.
  • Table: The place for storing your data in the blockchain. It is the same as the table in a traditional database. But note that, everything you save on it will be persistent in RAM and you have to charge a fee for it. Therefore please save the necessary information to reduce your cost.

Write a smart contract

Let’s write a smart contract for your book store.

  1. Create a structure of source code
$ mkdir -p bookstore
# cd bookstore 
# mkdir include src

Choose a development tool for you then start writing the smart contract.

  1. Define actions and a table in a header file

You will create a header file which has the name bookstore.hpp

  • Actions:
- Add a book (bookid, author, price, name, publisher, number of copies)
- Delete a book (name)
  • Table:
 - book (bookid, name, price, author, publisher, number of copies, status)

Here is the simple code:

#include <eosio/eosio.hpp>

using namespace eosio;

class [[eosio::contract("bookstore")]] bookstore : public eosio::contract {
  public:
    bookstore(name receiver, name code, datastream<const char*> ds):contract(receiver, code, ds) {}
    /**
     * Add a book to book table 
     */
    [[eosio::action]]
     void addbook(uint64_t bookid, const std::string& name, const std::string& author, const std:string& publisher, double price, uint64_t number_copies);
    /**
     * Delete a book from book table 
     */
    [[eosio::action]]
     void deletebook(uint64_t bookid);
  private:
    /**
     * A book table for data persistence 
     */
      struct [[eosio::table]] book 
      {
            uint64_t bookid;
            std::string name;
            std::string author;
            std::string publisher;
            double prices;
            uint64_t number_copies;
            bool status;

            uint64_t primary_key() const { return bookid; }
      };
    
      /* Define the multi-index table */
      typedef eosio::multi_index<"books"_n, book> books;

};
  1. Write logic for actions to the source file bookstore.cpp
#include <bookstore.hpp>


namespace eosio
{
 
  void bookstore::addbook(
      uint64_t bookid, 
      const std::string& name, 
      const std::string& author, 
      const std:string& publisher, 
      double price, 
      uint64_t number_copies
){
    require_auth(get_self());

    /**
     * Check that bookid has existed or not
     */     
    books _books(get_self(), get_self().value);
    auto iter = _books.find(bookid);
    check(iter != _books.end(), "The book has existed");

    /**
     *  Add book to the book table
     */ 
    
    _books.emplace(get_self(), [&](auto &b) {
        b.id            = bookid;
        b.name          = name;
        b.author        =  author;
        b.publisher     = publisher;
        b.price         = price;
        b.number_copies = number_copies;
        b.status        = true;
    });
  }

  void bookstore::deletebook(uint64_t bookid)
  {
    require_auth(get_self());
    
    /**
     * Check that bookid has existed or not
     */     

    books _books(get_self(), get_self().value);
    auto iter = _books.find(bookid);
    check(iter != _books.end(), "The book has not existed");

    /**
     * Delete by update status to false
     */ 

    _books.modify(iter, same_payer, [&](auto & b) {
        b.status = false;
    });
  }


} // namespace eosio

EOSIO_DISPATCH(eosio::bookstore,(addbook)(deletebook))

Deploy the smart contract

Please check my post to deploy the smart contract

Enjoy the EOS blockchain network!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s