Action Return Values

Did you know that you can now have smart contract actions directly return data to your front end?! No need for storing the data in a table row, then waiting a second or 2, then fetching that table row from an API.

This is such a useful feature, I'll show you how to implement it below.

It should be noted that it is not recommended to use action return values for things that require randomness, such as pack openings, etc. These actions need to be separated into 2 transactions to avoid being abused by malicious actors.

[[eosio::action]] asset mycontract::claimtokens(const name& user){
    require_auth( user );
    auto itr = users_t.require_find( user.value, "no user found" );
    asset claimable_amount = itr->balance;
    check( claimable_amount.amount > 0, "nothing to claim" );
    transfer_tokens( user, claimable_amount, itr->contract, std::string("token claim") );
    users_t.modify(itr, same_payer, [&](auto &row){
        row.balance.amount = 0;
    });
    
    return claimable_amount;
}

This is obviously a bit of pseudo-code here, but you get the point. This action can be called via a front end, or Node JS script etc, and it will return the claimed amount to you.

You can retrieve the data like this.

const claimTokens = async () => {

    try { 

      const result = await session.transact({
        actions: [{
          account: 'mycontract',
          name: 'claimtokens',
          authorization: [{
            actor: session.actor,
            permission: session.permission,
          }],
          data: {
            user: session.actor,
          }
        }]
      }, {
        blocksBehind: 3,
        expireSeconds: 90,
      });

    
    const actionTraces = result.response.processed.action_traces;

    const returnValues = actionTraces
      .filter(trace => trace.return_value_data !== undefined)
      .map(trace => trace.return_value_data);     
       
    console.log(returnValues[0])
       
    } catch (e) {
      console.log(`error submitting return value: ${e}`);
    }

};

claimTokens();

This will log the result directly into the console. You can also return multiple values if needed, and change the console.log(returnValues[0]) to just console.log(returnValues).

This same logic can also be implemented into a front end, and stored in a state variable rather than a console log.

To learn more about using Wharfkit, check out their documentation here:

Last updated