Hive Small Codes: Receive incoming transaction information from an account

in Programming & Dev2 months ago

Hive Small Codes

One of the exciting things to do in programming is communicating with blockchain. Let's connect with the Hive blockchain today and write codes that can quickly retrieve information from this blockchain.

What I want to do in this post and similar posts is to write small and practical pieces of code that can be used in future ideas. So let's get started.

One of the things that is said about blockchain is that it is a ledger. Well, let's imagine that the blockchain is a database. The information is clearly available to us. One of these cases is transactions.

Today I want to check incoming or outgoing transactions. Since I'm writing code with NodeJS, the first step is to create a directory called hive and put my package file inside it. So I write this command:

npm init

so, I'm asked a few questions to create the package.json file.

init new project

Now I have two files in my hive directory. One is index.js and the other is package.json.

project directory

I open the package.json file with a text editor and add the following to it.

"type": "module"

package.json file

First of all I install dhive.js.

npm install @hiveio/dhive

install dhive.js

Now, if I go to my hive directory, one file and folder have been added. One is the node_modules folder and the other is the package-lock.json file.

hive directory

If I open the package.json file with the editor, I see that the dhive.js module is also added to it. So, let's skip the extra explanation.

package.json

If I look at @albro account information in hiveblockexplorer created by @penguinpablo, I see that about an hour ago @tipu sent 0.002 HIVE to @albro account.

input transaction

Of course, you can see other information about this transaction. But for now I have nothing to do with the rest of the details. So, you can retrieve the information by having the transaction itself, but what if you want to know if an account sent you an amount or had a transaction?

So I want to know if @tipu sent me some amount without knowing the transaction! Let's write this code together:

import { Client } from "@hiveio/dhive";
const DEFAULT_SERVER = [
  'https://rpc.mahdiyari.info',
  'https://api.hive.blog',
  'https://rpc.ecency.com',
];
const client = new Client(DEFAULT_SERVER, {
  timeout: 4000,
  failoverThreshold: 10,
  consoleOnFailover: true,
});
// Replace with the name of the target account
const fromAccount = 'tipu';
const toAccount = 'albro';
async function fetchTransactions(toAC, fromAC) {
  try {
    const transactions = await client.database.getAccountHistory(toAC, -1, 1000);
    const targetTransactions = transactions.filter(tx => tx[1].op[1].from === fromAC).slice(-1);
    console.log(targetTransactions);
  } catch (error) {
    console.error('Error fetching transactions:', error);
  }
}
(async () => {
fetchTransactions(toAccount, fromAccount);
})();

In the explanation of this code, I can say that I first imported the dhive.js package and specified a number of default servers and created the client object to connect to the Hive blockchain.

After that, I created two variables called fromAccount and toAccount, which as their name suggests, I want to get the incoming transaction to the account from a specific account.

What is important is the fetchTransactions function which gives me the most recent or in other words the last incoming transaction from a given account. It first returns the transaction history of my account by getAccountHistory and then returns only the transactions that are specified by the account using filter and finally with slice(-1) I get only the most recent transaction.

If I want to change this code to filter only the transaction with a specific amount and a specific memo from a specific account, then it is enough to change the code as follows:

// Replace with the name of the target account
const fromAccount = 'tipu';
const toAccount = 'albro';
const tx_amount = '0.002 HIVE';
const tx_memo = '@tipU investor payout - check out https://tipu.online/hive for detailed info - thank you!';
async function fetchTransactions(toAC, fromAC, amount = '', memo = '') {
  try {
    const transactions = await client.database.getAccountHistory(toAC, -1, 1000);
    const filteredTransactions = (transactions.filter(tx => 
      tx[1].op[0] === 'transfer' && 
      tx[1].op[1].from === fromAC &&
      tx[1].op[1].memo === memo &&
      tx[1].op[1].amount === amount
    ).slice(-1))[0][1];
    console.log('id = ' + filteredTransactions.trx_id + '\n' +
            'from = ' + filteredTransactions.op[1].from + '\n' +
'to = ' + filteredTransactions.op[1].to + '\n' +
'amount = ' + filteredTransactions.op[1].amount + '\n' +
'memo = ' + filteredTransactions.op[1].memo);
  } catch (error) {
    console.error('Error fetching transactions:', error);
  }
}
(async () => {
fetchTransactions(toAccount, fromAccount, tx_amount, tx_memo);
})();

So, This code is a simple code that assumes that the transaction exists. It can be modified with just a few conditions to do something specific if there is no transaction.

Sort:  

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support.