Update to TerraCore claim

in #blog10 months ago

Hello again, a little update to my previous post on claiming stash on TerraCore.

Rather than claim every 4 hours I thought I'd try pulling the leader board statistics and claiming when I reach the 'danger zone' of being attacked, this gives me flexibility to increase or decrease my mining rate (engineering) by switching gear.

Of course I'm using ChatGPT again, other than fiddling with a few values and variables it's all AI coded! Boy I wish I'd explored this concept sooner! 🤣

Basically the script pulls data using HTTP API in JSON format, parses it, displays some info on screen and triggers the previous function to claim.

One other change, rather than set active key using 'set' from command line I've used Windows environment variables as for some reason the data would get lost, causing errors and exiting the script! 😭

image.png

Code as follows:


const axios = require('axios');
const { Client, PrivateKey } = require('@hiveio/dhive');
const { exec } = require('child_process');

const myusername = 'hive_username';
const amountToClaim = 100;

const client = new Client('https://api.hive.blog');

function clearConsole() {
// Clear console
console.clear();

// Print current timestamp
console.log(Timestamp: ${new Date().toLocaleString()}\n);
}

async function claim(player, amount) {
const privateKey = PrivateKey.fromString(process.env.ACTIVE_KEY);
const publicKey = privateKey.createPublic();

const op = [
'custom_json',
{
required_auths: [],
required_posting_auths: [player.username],
id: 'terracore_claim',
json: JSON.stringify({ amount, 'tx-hash': generateHash() })
}
];

const result = await client.broadcast.sendOperations([op], privateKey, [publicKey]);
console.log('Transaction broadcasted:', result);
}

function generateHash() {
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}

function displayLeaderboard() {
clearConsole();

axios.get('http://terracore.herokuapp.com/leaderboard')
.then(response => {
const players = response.data;
const myusernamePlayer = players.find(player => player.username === myusername);

  if (!myusernamePlayer) {
    console.log(`Could not find ${myusername} in the leaderboard.`);
    return;
  }

  const filteredPlayers = players.filter(player => {
    return player.stats.defense <= myusernamePlayer.stats.defense && player.scrap > myusernamePlayer.scrap;
  });

  const sortedPlayers = filteredPlayers.sort((a, b) => b.scrap - a.scrap);
  const top10Players = sortedPlayers.slice(0, 10);

  console.log(`${myusername}:`);
  console.table({
    Player: myusernamePlayer.username,
    'Stats Engineering': myusernamePlayer.stats.engineering,
    'Stats Defense': myusernamePlayer.stats.defense,
    Scrap: myusernamePlayer.scrap,
    Claims: myusernamePlayer.claims,
    Attacks: myusernamePlayer.attacks
  });
  console.log('');

  console.log('Top 10 players with defense equal to or lower than ' + myusername + ' and higher scrap:');
  console.table(top10Players.map(player => ({
    Player: player.username,
    'Stats Engineering': player.stats.engineering,
    'Stats Defense': player.stats.defense,
    Scrap: player.scrap
  })));

  console.log('\nTotal players matching the criteria: ' + filteredPlayers.length);

  // Run claim function if claims is greater than 0 and total count is less than 8
  if (myusernamePlayer.claims > 0 && filteredPlayers.length < 8) {
    claim(myusernamePlayer, amountToClaim)
      .then(() => {
        console.log(`Successfully claimed ${amountToClaim} rewards.`);
      })
      .catch(error => {
        console.error('Error claiming rewards:', error);
      });
  }
})
.catch(error => {
  console.error('Error retrieving leaderboard:', error);
});

}

// Display leaderboard initially
displayLeaderboard();

// Set interval to refresh leaderboard every 30 seconds
setInterval(displayLeaderboard, 30000);

It's been great fun working with ChatGPT on this, highly recommend people give it a try, not just coding, ask it anything!

I really want to try building my own AI, there are plenty of open source resources but it looks like I would need a decent graphics card which is expensive and there are too many things I want to spend money on 🤑🤣🤓

Again, I hope this helps someone.

Next up I want to script Boss fights which should be fun too as there are no examples of code! (not that I've looked that hard yet)

Till next time,
Stay Frugal

Sort:  

My previous @v4vapp proposal has expired. I have a new one which is running but unfunded right now. I'm still running @v4vapp and all my other services.

I've just updated v4v.app and I'm getting ready for some exciting new features after the next hard fork.

Please consider asking your friends to vote for prop #265 or consider unvoting the return vote.

For understandable reasons in the current crypto climate it is harder to get funded by the DHF, I accept this so I'm asking a wider audience for help again. I'll also add that I power up Hive every day and usually power up larger amounts on 1st of the Month. I'm on Hive for ideological reasons much more than for only economic benefit.

Additionally you can also help with a vote for Brianoflondon's Witness using KeyChain or HiveSigner

If you have used v4v.app I'd really like to hear your feedback, and if you haven't I'd be happy to hear why or whether there are other things you want it to do.

Interesting. I tried using this AI (https://huggingface.co/chat/) to write some Blender python scripts for me (I have 0 codding skills). But it soon started to get confused and spit out some totally unrelated nonsense so I gave up. Maybe I will have another go with chatgpt or something else.

Yes, I found ChatGPT also sometimes went down a funny path, responding with 'sorry, I meant xyz' usually resolved the issue.
Definitely keep trying bud.

I'm going to try GPT Engineer soon, also from HuggingFace

Wow that GPT Engineer thing looks amazing. I won't get any of my work done if I jump into that rabbit hole now :D

This post has been supported by @Terraboost with a 20% upvote! Delagate HP to Terraboost to Earn Daily HIVE rewards for supporting the @Terracore community!

Play Terracore | Delegate HP | Join Discord

Congratulations @frugal-fun! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You received more than 1250 upvotes.
Your next target is to reach 1500 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP