Using Steem-API with Ruby Part 16 — Print Steem Engine Token balances

in #utopian-io5 years ago (edited)

Steemit_Ruby_Engine.png

Repositories

SteemRubyTutorial

All examples from this tutorial can be found as fully functional scripts on GitHub:

radiator

Radiator is one of the tree Ruby APIs to the Steem Blockchain.

Steem Engine

steem-engine_logo-horizontal-dark.png

What Will I Learn?

This tutorial shows how to interact with the Steem blockchain, Steem database and Steem Engine using Ruby. When accessing Steem Engine using Ruby their only the radiator APIs available.

img_train-dark.png

In this particular chapter you learn how extend Steem-Print-Balances.rb from the Print Account Balances improved tutorial so it prints the steem engine token as well.

Requirements

Basic knowledge of Ruby programming is needed. It is necessary to install at least Ruby 2.5 as well as the following ruby gems:

gem install bundler
gem install colorize
gem install contracts
gem install radiator

The tutorial build on top of the following previous chapters:

Difficulty

For reader with programming experience this tutorial is basic level.

Tutorial Contents

Just like the last tutorial the majority of the work is done inside a newly written class. This class can read the ballances from the database and converts the JSON objects returned into propper ruby classes.

Implementation using radiator


A simple standard constructor for the various properties a balance holds:

PropertyDescription
symbolID of token held
accountID of account holding
balancebalance held
stakebalance staked
delegated_stakestake delegated
received_stakestake stake
pending_unstakedelegated stake to be returned to owner.
lokisome internal informations
module SCC
   class Balance < SCC::Steem_Engine
      include Contracts::Core
      include Contracts::Builtin

      attr_reader :key, :value,
                  :symbol,
                  :account,
                  :balance,
                  :stake,
                  :delegated_Stake,
                  :received_stake,
                  :pending_unstake,
                  :loki

      public

         Contract Any => nil
         def initialize(balance)
            super(:symbol, balance.symbol)

            @symbol          = balance.symbol
            @account         = balance.account
            @balance         = balance.balance.to_f
            @stake           = balance.stake.to_f
            @delegated_stake = balance.delegatedStake.to_f
            @received_stake  = balance.receivedStake.to_f
            @pending_unstake = balance.pendingUnstake.to_f
            @loki            = balance["$loki"]

            return
         end

Convert the balance into steem using the Metric class from Print Steem Engine Token values tutorial.

         Contract None => Radiator::Type::Amount
         def to_steem
            _steem = if @symbol == "STEEMP" then
               @balance
            else
               @balance * metric.last_price
            end

            return Radiator::Type::Amount.to_amount(
               _steem,
               Radiator::Type::Amount::STEEM)
         end

Convert the current balance into SBD using the Amount class from the Print Account Balances improved tutorial.

         Contract None => Radiator::Type::Amount
         def to_sbd
            return to_steem.to_sbd
         end

The metrics for the balance as lazy initialised property. The metric is used to convert the balance into Steem.

         Contract None => SCC::Metric
         def metric
            if @metric == nil then
               @metric = SCC::Metric.symbol @symbol
            end

            return @metric
         end

The token information of the balance also as lazy initialised property. The token informations contain, among other, the display name of the token which we will later use.

         Contract None => SCC::Token
         def token
            if @token == nil then
               @token = SCC::Token.symbol @symbol
            end

            return @token
         end

Create a colourised string showing the amount in SDB, STEEM and the steem engine token. The actual value is colourised in blue while the converted values are colourised in grey (aka dark white).

A try catch is used for token which have no metics and therefore no steem value. "N/A" is then printed instead of the steem values.

         Contract None => String
         def to_ansi_s
            begin
               _steem = self.to_steem
               _sbd   = self.to_sbd

               _retval = (
               "%1$15.3f %2$s".white +
                  " " +
                  "%3$15.3f %4$s".white +
                  " " +
                  "%5$18.6f %6$s".blue) % [
                  _sbd.to_f,
                  _sbd.asset,
                  _steem.to_f,
                  _steem.asset,
                  @balance,
                  @symbol]
            rescue KeyError
               _na = "N/A"

               _retval = (
               "%1$15s %2$s".white +
                  " " +
                  "%3$15s %4$5s".white +
                  " " +
                  "%5$18.6f %6$s".blue) % [
                  _na,
                  _na,
                  _na,
                  _na,
                  @balance,
                  @symbol]
            end

            return _retval
         end

Get the list of balances for a gives account using the find function from contracs API. The find function has been explained in the Print Steem Engine Token values tutorial.

         class << self
            Contract String => ArrayOf[SCC::Balance]
            def account (name)
               _retval  = []
               _current = 0
               _query   = {
                  "account": name
               }

               loop do
                  # Read the next batch of balances using
                  # the find function.
                  #
                  _balances = Steem_Engine.contracts_api.find(
                     contract:   "tokens",
                     table:      "balances",
                     query:      _query,
                     limit:      SCC::Steem_Engine::QUERY_LIMIT,
                     offset:     _current,
                     descending: false)

                  # Exit loop when no result set is
                  # returned.
                  #
               break if (not _balances) || (_balances.length == 0)

                  # convert each returned JSON object into
                  # a class instance.
                  #
                  _retval += _balances.map do |_balance|
                     SCC::Balance.new _balance
                  end

                  # Move current by the actual amount of
                  # rows returned
                  #
                  _current = _current + _balances.length
               end

               return _retval
            end
         end # self
   end # Balance
end # SCC

In addition to this method the balance class committed to git has examples for retrieving the balances for a given token and all balances in the database. All three methods are very similar. For this only the one method which is actually needed for the final script has been described.

Hint: Follow this link to Github for the complete script with comments and syntax highlighting : Balance.rb.


Most of the Steem-Print-Balances.rb script has already been described in Print Account Balances improved and there are only few changes needed to print the steem engine balances as well:

Most of the functionality is not encapsulated in classes which have been explained previously. All that is needed is too require those classes.

require_relative 'Radiator/Amount'
require_relative 'Radiator/Price'
require_relative 'SCC/Balance'
require_relative 'SCC/Token'

First print the account value without the steem engine token added.

      puts(("  Account Value (steem)= " + "%1$15.3f %2$s".green) % [
         _account_value.to_f,
         _account_value.asset])

Then retrieve all balances for the currently account from the steem engine database

      _scc_balances = SCC::Balance.account account.name

Loop over all balances printing the balance and adding the value (in SBD) to the account value. For the latter a try catch is used for token which don't have a Steem value.

      _scc_balances.each do |_scc_balance|
         token = _scc_balance.token

         puts("  %1$-20.20s = %2$s" % [token.name, _scc_balance.to_ansi_s])

         begin
            _sbd           = _scc_balance.to_sbd
            _account_value = _account_value + _sbd
         rescue KeyError
            # do nothing.
         end
      end

Lastly print the account value with the value of the steem engine token added.

      puts(("  Account Value (total)= " + "%1$15.3f %2$s".green) % [
         _account_value.to_f,
         _account_value.asset])

Hint: Follow this link to Github for the complete script with comments and syntax highlighting : Steem-Print-Balances.rb.


The output of the command changes from previous only printing the steem token:

Screenshot at Mar 14 10-58-50.png

to now printing the values of the Steem Engine Token as well:

Screenshot at Jul 30 15-23-14.png

Curriculum

First tutorial

Previous tutorial

Next tutorial

Proof of Work

Image Source

comment votes posts level payout commented voted

Sort:  

I would love to get some help with steem-engine tokens and their integration with PEOS privacy token privacy features now that we have it listed on steem-engine.com

I believe i will ask @someguy123 and @privex about private peos withdraws one day if he can enable a PEOS wallet and maybe charge his own fee for a private peos withdraw which can work with accounts made with @anonsteem https://anon.steem.network

Hi, @krischik!

You just got a 7.63% upvote from SteemPlus!
To get higher upvotes, earn more SteemPlus Points (SPP). On your Steemit wallet, check your SPP balance and click on "How to earn SPP?" to find out all the ways to earn.
If you're not using SteemPlus yet, please check our last posts in here to see the many ways in which SteemPlus can improve your Steem experience on Steemit and Busy.

#utopian-io has been a gift. We would like to keep its curation-efforts alive here on 'marlians.com'. We want to curate and reward 'contributions to open-source projects' with MARLIANS on the the marlians.com tribe, a SCOT-enabled steem condenser. Contributions can include suggestions, graphics, bug-finds, code etc. You can simply add in #marlians to your #utopian-io posts and it will appear on https://www.marlians.com/created/utopian enabling you to earn some MARLIANS along with steem/sbd. You can also post directly to steem via 'marlians.com'. We have some overseers who curate and who can render you help too. You can find them enlisted on https://www.marlians.com/created/utopian

"has been" 😳 - did i miss something? Did @utopian-io die?

Posted using Partiko Android

Not exactly. But they have stopped their curation for a period. They had an update on their blog like two weeks ago. I think they stopped 31st of July

WOW I can't wait to start learning this tutorial! I feel its a must for anyone running a tribe to at least try or have someone who understands this. @gerber maybe can help me understand how this works in a private chat maybe over in https://chat.asstoken.app or https://MyFreeCrypto.org :D

I really need to learn this stuff, all i know about ruby is that @inertia uses it :D

And I know radiator is involved.

I must learn this stuff or I will be seen as a fraud to some if I say i am a software developer :D I want to be able to say that one day, but doesnt web software count as software? I guess instead of software developer its better to be called an IT project manager if youre not coding anything right?

i can be IN the software development world, obviously we all are if we are here, but we may not be developers per say

I dont even know what printing balances means, is printing a word used in ruby?

What can you use to print steem engine balances ? Is it important for allowing other apps to oen day interact with steem engine? I really need to catch up and learn some of this even tho i have a feeling it may not be relevant to anything im doing yet or maybe it is

It's a tutorial so it teaches how to access the various informations. They are only printed on the console to give an indication of what informations are out there.

I suggest you start at part 1.

Coin Marketplace

STEEM 0.36
TRX 0.12
JST 0.040
BTC 70839.13
ETH 3563.41
USDT 1.00
SBD 4.77