New to Nutbox?

Lesson 1:Mastering Steem.js for Blockchain Development

3 comments

dev-pro
47
3 days agoSteemit5 min read

Aftab Irshad

@dev-pro

#Pakistan


invited me this Contest

@alejos7ven

Domain Steem with JavaScript: Lesson #2 - Exploring the Steem API: Steem JS


image.png


This image is created by Canva Pro

General Knowledge

This is the Overview and introduction into Steem.js library, and why it matters to consider using it. Although previous lessons introduced the usage of HTTP queries and RPC nodes for more manual interaction, Steem.js relieves the problem, providing a very well structured API of methods intended for JavaScript developers specifically. By the end of this lecture, You will grasp the concepts of how to use Steem.js to automate a wide range of interactions with the Steem blockchain such as educational, and basic trading activities to more complex research or building custom applications on top of blockchain.


First Things First, How to Use Steem.js

Step 1: Getting Steem.js installed

If you need to include Steem.js into your project, here’s how to do that:


npm install steem --save

Step 2: Getting the Advanced Steem.js Library started

So now you have to import steemjs into your project and set up the api you wish to use:


const steem = require('steem');

steem.api.setOptions({ url: 'https://api.steemit.com' });

Well done! Now you are prepared to utilize the Steem blockchain through the Steem.js library.

Example 1: Getting Data from Blockchain

Code Snippet: Fetching A Particular Block


let blockNumber = 1;

steem.api.getBlock(blockNumber, function(err, block) {

if (err) {

console.error('An error occurred while retrieving the block:', err);

} else {

console.log(`Block ${blockNumber} Created On: ${block.timestamp}, Was Witnessed By: ${block.witness}`);

}

}

}

}```

#### **Explanation:**

- **`steem.api.getBlock`**: Retrieves information attached to a block identified by the block number.

- Parameters:

  - `blockNumber`: The block being sought.

  - Result/Error handling function.

- **Output**: A block’s timestamp and a witness in case the block was signed is shown.

#### **Use case:**

Usage of this function is crucial while researching the past of a blockchain or the behavioral patterns of the network.

---
### **Example 2: Retrieving Account Information**

#### **Code Snippet: Fetching Account Details**

```javascript

steem.api.getAccounts(['steemcurator01'], function (err, result) {

    if (err) {

        console.error('Error fetching account:', err);

    } else {

        const account = result[0];

        console.log('Account Details:', account);

        console.log('Reputation:', steem.formatter.reputation(account.reputation));

    }

});

Explanation:

  • steem.api.getAccounts: Allows you to access detailed account data by entering a username.

  • steem.formatter.reputation: Changes reputation figures to something that makes sense.

Output Example:

  • Shows the user’s reputation and balances, and any other account related information.

Example 3: Fetching Recent Posts

Code Snippet: Fetching Posts the easy way


steem.api.getDiscussionsByCreated({tag: ‘steem’, limit: 5}, function (err, posts) {

if (err) {

console.error(‘Error fetching posts:’, err);

} else {

console.log(‘Recent Posts:’, posts);

}

});

Discussion

  • getDiscussionsByCreated: Used to get the latest posts that bear a specified tag.

  • Parameters:

    • tag: A name given to or assigned an object in order to publish discussion or posts on it

    • limit: The upper threshold of posts that that need to be returned

Example of how to use it:

This is the best example to use when creating a feed of the most up to date posts on a given topic.


Advanced Example: Calculation of Steem Power (SP) in Detail

General Procedures for the Conversion of SP

  • Conversion of VESTS into SP :

Conversion of VESTS into Steem Power is determined by dividing the total value of steam in the total fund by the total number of shares of the total vesting. In some case we can use the pre-provided formula to ease the approach:

1.Dividend:\

 ```plaintext

 steem_per_mvests=  (total_vesting_fund_steem * 1,000,000) / total_vesting_shares

 SP = (vesting_shares * steem_per_mvests)/1,000000

 ``` 
  • The Formula for Effective SP:

The following describes SP now that one has the amount of Steem Power:


effective_SP = vesting_shares + received_vesting_shares - delegated_vesting_shares – vesting_withdraw_rate

Code Snippet: Computing the Effective SP


steem.api.getDynamicGlobalProperties((err, globalProps) => {

    if (err) {
        console.log('Error while getting global properties: ', err);
        return;
    }

    const steem_per_mvests = ((globalProps.total_vesting_fund_steem * 1000000) / globalProps.total_vesting_shares)).toFixed(2);
    
    steem.api.getAccounts(['steemcurator01'], (e, accounts) => {
        
        if (e) {
            console.log('Error while getting account: ', e);
            return;
        }
        
        // `accounts` array's first element Core Account.
        const coreAccount = accounts[0];

        const vesting_shares = parseFloat(coreAccount.vesting_shares);
        const received_vesting_shares = parseFloat(coreAccount.received_vesting_shares);
        const delegated_vesting_shares = parseFloat(coreAccount.delegated_vesting_shares);
        const vesting_withdraw_rate = parseFloat(coreAccount.vesting_withdraw_rate);

        // effective sp 
        /// calculate effective stake which determines the voting power of a core account
        const effectiveSP = vesting_shares + received_vesting_shares - delegated_vesting_shares - vesting_withdraw_rate;

        console.debug(`Effective SP of steemcurator01 is ${(effectiveSP * steem_per_mvests) / 1000000}`);
    });
  });
});

Explanation:

  1. Takes global blockchain properties with the use of getDynamicGlobalProperties.

  2. Works out information on specific accounts with getAccounts.

  3. Computes total effective SP by taking into account delegated SP, received SP, and SP to be withdrawn percentages.


Homework

  1. Execute 3 API Methods:

    Incorporate the use off Steem.js methods such as getBlock, getAccounts, and getDiscussionsByCreated.

  2. Declaration:

    Write a script that computes effective SP in all steemcurator accounts from sc01 to sc08.

  3. Research:

    Write a research paper explaining the workings of getDynamicGlobalProperties at least for 5 values many people want to know, for a start head_block_number, time, total_vesting_fund_steem, total_vesting_shares, current_supply.


Conclusion

Steem.js tools provide an amazing combination for developers to easily connect with the Steem Blockchain. Moreover, by learning its methods, you can build interactive dApps, harvest blockchain data, and conduct administrative tasks such as user-managed accounts. Take advantage of the homework to test your theories, and integrate new aspects with the help of Steem.js.

I am Invited this contest my steemian friends

@yoyopk
@ulfatulrahmah
@faisalamin
@tasonya
@ahp93

Comments

Sort byBest