Image generated with @karina.gpt in @cryptoshots.nft Discord server
I am in contact with the DappRadar team to fix how they track stuff for Crypto Shots.
I ended up sending them some code snippets and decided to post them here too, in case I want to find them easily in the future.
1. Calculate the $ worth of a token transfer
HIVE:
var getHiveEngineTokenPrice = async ({ tokenName }) => {
const tokenInfoUrl = `https://api.hive-engine.com/rpc/contracts`;
const tokenInfoBody = {
"jsonrpc":"2.0",
"method":"find",
"params": {
"contract":"market",
"table":"metrics",
"query":{ "symbol": tokenName },
"limit": 1,
"offset": 0,
"indexes":[]
},
"id":1
};
const tokenInfoResponse = await fetch(tokenInfoUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(tokenInfoBody),
});
const tokenInfoData = await tokenInfoResponse.json();
const lastPrice = tokenInfoData.result[0].lastPrice;
console.log(`$${tokenName} current price on Hive-Engine: ${lastPrice} HIVE`);
const hivePriceUrl = `https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd`;
fetch(hivePriceUrl)
.then(response => response.json())
.then(data => {
const priceUSD = data.hive.usd;
console.log(`HIVE current price is $${priceUSD}`);
const tokenPriceUSD = lastPrice * priceUSD;
console.log(`The current price of $${tokenName} in USD is $${tokenPriceUSD.toFixed(4)}.`);
});
};
var tokenName = 'DOOM';
getHiveEngineTokenPrice({ tokenName });
WAX:
var getFungibleTokenPrice = async ({ tokenPair }) => {
const { tokenName, cryptoName, marketNumber } = tokenPair;
const cryptoNameLc = cryptoName.toLowerCase();
const data = await fetch(`https://wax.alcor.exchange/api/markets/${marketNumber}/deals`).then(res => res.json());
const lastTransactionPrice = data[0].unit_price;
console.log(`$${tokenName} current price on the open market: ${lastTransactionPrice} ${cryptoName}`);
fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${cryptoNameLc}&vs_currencies=usd`)
.then(response => response.json())
.then(data => {
const priceUSD = data[cryptoNameLc].usd;
console.log(`$${cryptoName} current price is $ ${priceUSD}`);
const tokenPriceUSD = lastTransactionPrice * priceUSD;
console.log(`The current price of $${tokenName} is $ ${tokenPriceUSD.toFixed(4)}.`);
});
};
var tokenPair = {
tokenName: 'BOOM',
contract: 'csboomcsboom',
cryptoName: 'WAX',
marketNumber: 368,
};
getFungibleTokenPrice({ tokenPair });
2. How to consume custom_json operations
...broadcasted on the Hive chain (eg. from a game/Dapp).
This is what such operations look like:
block_num 82670298
expiration 2024-02-09T23:53:30
extensions []
operations [["custom_json", {"id": "ssc-mainnet-hive", "json": "{\"contractName\":\"tokens\",\"contractAction\":\"stake\",\"contractPayload\":{\"symbol\":\"DOOM\",\"to\":\"athunderstruck\",\"quantity\":\"6.6700\",\"memo\":\"Crypto Shots PVP Alpha reward. GG!\"}}", "required_auths": ["cryptoshots.tips"], "required_posting_auths": [] }]]
ref_block_num 29401
ref_block_prefix 2126063433
signatures [ "1f5054e3996f04805b4a7b070c78d94cd50ee8097094f832335b7119199ca421470e6a5a6c6e63c6dc272eb6ca549761b4c176f209eb3de0a049ccbbc9e3472057" ]
transaction_id 9ee3b9672bf71e0e5d853cb44dfb275ed2fd46a8
transaction_num 80
Example: https://hiveblockexplorer.com/tx/9ee3b9672bf71e0e5d853cb44dfb275ed2fd46a8
Example of how to stream blocks of the Hive blockchain and parse custom_json
operations found in blocks:
const fetch = require('node-fetch');
const { Client, Blockchain } = require('@hiveio/dhive');
const fetchHealthyHiveNode = () => fetch(
'https://beacon.peakd.com/api/nodes',
{
credentials: 'omit',
headers: { Accept: 'application/json' },
method: 'GET',
},
)
.then((res) => res.json())
.then((allNodes) => {
const healthyNodes = allNodes.filter(({ score } = {}) => score === 100);
return ({ hiveNode: healthyNodes[0].endpoint });
})
.catch((fetchErr) => ({ err: `Url fetch failed: ${fetchErr}` }));
const streamBlocks = async () => {
const { err, hiveNode } = await fetchHealthyHiveNode();
if (err) return;
const client = new Client(hiveNode);
const blockchain = new Blockchain(client);
console.log('Streaming blocks from', hiveNode);
blockchain.getBlockStream()
.on('data', (block) => {
console.log(`Received block #${block.block_id} containing ${block.transactions.length} transactions`);
block.transactions.forEach(
tx => tx.operations.forEach(
op => op[0] === 'custom_json' && console.log(op[1]),
)
);
})
.on('error', console.error);
};
streamBlocks();
That's all folks!
If you spare a vote, please vote for these witnesses! 😎
Gabe, thank you for sharing!
wonderful information, thanks for sharing these functions and variables for smart contracts and other data, I'm glad to see content from programmers like you :D
Thank you for your witness vote!
Have a !BEER on me!
To Opt-Out of my witness beer program just comment STOP below
View or trade
BEER
.Hey @gaottantacinque, here is a little bit of
BEER
from @isnochys for you. Enjoy it!Learn how to earn FREE BEER each day by staking your
BEER
.