2

I am creating a smart contract but came to a halt when writing the code.

Is there a way, in a smart contract, to prevent me from spending tokens transferred to me by another user through the smart contract until another action is called that unlocks it for spending?

1
  • Do you mean EOS token or some token your smart contract has created?
    – tmm
    Feb 21, 2019 at 14:25

2 Answers 2

0

Yes this is possible.

  1. Create a table with the user's name and whether they are allowed to spend their tokens or not.
  2. Check this table in the transfer function.
  3. When the appropriate action is called, update the table entry to permit transfers.

For example:

token code

ACTION transfer(eosio::name from, eosio::name to, eosio::asset quantity, std::string memo){
  transfer_not_allowed_table table(contract, scope);
  eosio::check(table.find(from.value) == table.end(), "may not transfer");
  // rest of transfer code
}

transfer allowed code

TABLE allowed{
  eosio::name user;
  uint64_t primary_key() const{return user.value;}
};
typedef eosio::multi_index< "allowed"_n, allowed > transfer_not_allowed_table;

ACTION disallow(eosio::name user){
  transfer_not_allowed_table table(contract, scope);
  eosio::check(table.find(user) == table.end(), "already not allowed to transfer");
  table.emplace(_self, [&](auto & entry){
    entry.user = user;
  });
}

ACTION allow(eosio::name user){
  transfer_not_allowed_table table(contract, scope);
  eosio::check(table.find(user.value) != table.end(), "already allowed to transfer");
  table.erase(table.find(user.value));
}
0

You can add handler method with annotation [[eosio::on_notify("eosio.token::transfer")]] to control token transfers. Through the handler you can check is this transfer is corresponding to the contract logic.

By the way, as I know you can change code in anyway while you have permission to that. So, if you want to make you contract 100% safe, after the code is completed you need to remove permissions. I did it by looping permission. But it's dangerous after that you cannot control contract and change code. It will live by themself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.