2

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.

  • Do you mean, is it possible to figure out beforehand how much CPU an action in a smart contract will use? – Phillip Hamnett - EOS42 Sep 11 '18 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 '18 at 8:20
  • This is possible, I'll write an answer – Phillip Hamnett - EOS42 Dec 20 '18 at 9:05
0

EDITED: ::get_resource_limits() is privileged API, so it cannot be used by normal account (only privileged account can call it like eosio)

You can get the limit of cpu, net or ram by the next:

void get_resource_limits( capi_name account, int64_t* ram_bytes, int64_t* net_weight, int64_t* cpu_weight );

But I don't think that you can get the info about the used amount in contract.

  • This does not work for me! Is there an offical documentation how to get cpu-limits in a smartcontract or an snippet of githup? - get_account_info(N(some_account_name)) seems not to exist! – sven Nov 19 '18 at 7:44
  • Hmm, I checked source code just now, and found that get_resource_limits() is a privileged API, so the contract deployed on normal account (not privileged) cannot call it. In that case, you may not have any way to access resource limits from contract. – conr2d Nov 20 '18 at 7:53
0

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

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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