Readonly Actions

Readonly actions work just like action return values, but in my opinion they are even cooler.

  1. You don't need any session or private key to sign them.

  2. The transaction does not actually get submitted on-chain, consuming 0 CPU from your wallet. All it does is simulate the transaction, and return the data.

Here's an example implementation using Wharfkit.

const { ContractKit } = require("@wharfkit/contract")
const { APIClient } = require("@wharfkit/antelope")

const contractKit = new ContractKit({
  client: new APIClient({ url: "https://api.waxdaobp.io" })
});

const USER = "someuser"
const FARM_NAME = "somefarm"
let claimable_balances = []

const showRewards = async () => {

    try { 

      const contract = await contractKit.load("tf.waxdao")

      const result = await contract.readonly('showreward', {
            user: USER,
            farm_name: FARM_NAME
      })                          

      claimable_balances = result
       
    } catch (e) {
        console.log(`error in showreward action: ${e}`);
    }
};

showRewards();

And here is the contract action.

[[eosio::action, eosio::read_only]]
vector<extended_asset> tokenstaking::showreward(const name& user, const name& farm_name){
	farm_struct farm = get_farm( farm_name );
	vector<reward_struct> rs = get_rewards( farm_name );
	staker_struct staker = get_staker( user, farm_name );
	mass_update_rewards( farm, rs );
	update_staker_rewards( staker, rs );
	vector<extended_asset> pending_rewards;

	for( auto& b : staker.claimable_balances ){
		if( b.quantity.amount > 0){
			pending_rewards.push_back( b );
		}
	}

	return pending_rewards;
}

This will return a list of pending rewards for a user, so they can be displayed on a front end etc. All without any special front end math, and without submitting a transaction on chain!

Last updated