#include <eosiolib/eosio.hpp>
#include <eosiolib/print.hpp>

#include <vector>
#include <tuple>

using namespace eosio;

class carpass : public eosio::contract {
  private:
    /// @abi table
    struct vstruct {
      uint64_t      prim_key;   // primary key
      account_name  user;       // account name for the user
      std::string   frameNb;    //the frame number of the vehicle (unique)
      std::vector<uint64_t> countersValues;
      std::vector<uint64_t> countersTimestamp;

      // primary key
      auto primary_key() const { return prim_key; }
      // secondary key: user
      account_name get_by_user() const { return user; }
    };

    // create a multi-index table and support secondary key
    typedef eosio::multi_index< N(vstruct), vstruct,
      indexed_by< N(getbyuser), const_mem_fun<vstruct, account_name, &vstruct::get_by_user> >
      > vtable;

  public:
    using contract::contract;

    ///@abi action
    void add(account_name _user, std::string frameNb){
    	 
    	require_auth( _user );
    	
    	vtable vObj(_self, _self);

    	//check vehicle doesn't already exists
    	bool exists = false;
    	for(auto& item : vObj){
    		if(item.frameNb == frameNb){
    			exists = true;
    			break;
    		}
    	}

    	eosio_assert(!exists, "Vehicle already exists!");

    	uint64_t vehiclePk = vObj.available_primary_key();

        std::vector<std::tuple<uint64_t, uint64_t>> counters;

    	//insert vehicle
    	vObj.emplace(_self, [&]( auto& address ){
    		address.prim_key = vehiclePk;
    		address.user = _user;
    		address.frameNb = frameNb;
    	});
    	

    }

    ///@abi action
    void addcounter(account_name _user, uint64_t _counter, uint64_t _vehicle){
      
      require_auth( _user );
      
      vtable vObj(_self, _self);

      auto vehicleItr = vObj.find(_vehicle);
      eosio_assert(vehicleItr != vObj.end(), "vehicle doesn't exists" );

      auto vehicle = vObj.get(_vehicle);
      eosio_assert(vehicle.user == _user, "Can only add counter to owned vehicle");
      
      uint64_t prevCounter = 0;

      if(vehicle.countersValues.size() >= 1){
        prevCounter = vehicle.countersValues.at(vehicle.countersValues.size() - 1);
      }
      
      eosio_assert(prevCounter <= _counter, "Counter can only grow or stay the same");

      vObj.modify( vehicleItr, _self, [&]( auto& it ){
        it.countersTimestamp.push_back(now());
        it.countersValues.push_back(_counter);
      });


    }

};

EOSIO_ABI( carpass, (add) (addcounter))

  • EOS

    第三代区块链到来了?赶紧学习 EOS 智能合约吧

    3 引用 • 3 回帖
  • 智能合约

    智能合约(英语:Smart contract )是一种旨在以信息化方式传播、验证或执行合同的计算机协议。

    20 引用 • 9 回帖
  • 通证
    1 引用
  • 代码
    161 引用 • 44 回帖
感谢    赞同    分享    收藏    关注    反对    举报    ...