3

Is it possible to access the CPU usage of a given account from within a smart contract?

For eg. in a smart contract transfer notification, you call get_account_info(N(some_account_name)) which returns a struct object containing {cpu_used, cpu_available, net_used, net_available, ram_used} etc.

4
  • Do you mean, is it possible to figure out beforehand how much CPU an action in a smart contract will use? Sep 11, 2018 at 7:58
  • No... it's as if you are doing 'cleos get account' but in the smart contract so that cpu, net and ram information for a given account can be available in the smart contract
    – Jeff Zheng
    Sep 11, 2018 at 8:20
  • This is possible, I'll write an answer Dec 20, 2018 at 9:05
  • still no way to get the resource usage in contract in latest eos version?
    – James Cai
    Mar 12, 2021 at 3:44

1 Answer 1

1

In order to access this information, you must create a struct as follows:

   struct [[eosio::table, eosio::contract("eosio.system")]] user_resources {
      name          owner;
      asset         net_weight;
      asset         cpu_weight;
      int64_t       ram_bytes = 0;

      uint64_t primary_key()const { return owner.value; }

      // explicit serialization macro is not necessary, used here only to improve compilation time
      EOSLIB_SERIALIZE( user_resources, (owner)(net_weight)(cpu_weight)(ram_bytes) )
   };
   typedef eosio::multi_index< "userres"_n, user_resources >      user_resources_table;

Then, in order to access a user's resources, you can do:

   user_resources_table  userres( _self, username.value );
   auto user = userres.find(username.value);
   print("User's NET EOS staked: ",user->net_weight,"\n");
   print("User's CPU EOS staked: ",user->_weight,"\n");
   print("User's RAM: ",user->ram_bytes,"\n");

Note: I haven't tested this code yet. Please edit appropriately if there is a typo or other mistake

3
  • Your answer shows how much EOS are staked on that account. This doesn't give any information of how much microseconds (or miliseconds) left in user's CPU or bytes remaining in NET etc.
    – conr2d
    Jan 19, 2019 at 12:04
  • 1
    It answers part of the question, cpu_used can not be accessed within smart contract to my knowledge. But I'm not sure about that so didn't want to say anything to that effect Jan 19, 2019 at 12:06
  • You're right. As I know, there's no way to access resource usage status from contract layer currently.
    – conr2d
    Jan 19, 2019 at 12:13

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.