Tutorial - DSteem - Basic Paid Voting Bot
Repository
https://github.com/jnordberg/dsteem/
Outline
This tutorial is part of the DSTEEM series. We’re digging into DSteem javascript library and make small projects. Learn to interact with the Steem blockchain from your browser using Javascript.
Today we’ll be creating a simplified paid bot service. Users send SBD/STEEM in return they receive a vote on a selected post. Making use of the code we created in the previous tutorial we’ll listen for transactions on the blockchain. When our bot receives a transfer
we’ll check the data and broadcast a response.
👨🏼💻 The full code for the script can be found on Github & CodePen 🚀
Requirements
- A plain text editor (I use VS Code)
- A browser (I use Brave)
- Difficulty
- Beginner
Learning Goals
- Inspect the transfer transaction type
- Create rules for deciding how much our vote is worth
- Send votes on a permlink from a memo
Step 1 - Setup
We’re working from the same code we created in the previous tutorial. Grab the code from Github to get started. If you’re finding this tutorial to start with consider following the previous post before starting this one.
Alternatively you can work in codepen.io - Fork/Save this Pen to get started
Add your posting key and username for an account you’ll be testing with.
const POSTING_KEY = dsteem.PrivateKey.fromString('') // add private posting key
const USERNAME = '' // add username
Step 2 - Update processBlock()
& processTransaction()
functions
First Step we’ll change out filter function to filter for transfer
transactions instead of comments
.
.filter( tx => filterTransaction(tx, ‘transfer’) )
let’s go ahead and check that works by inspecting the console.
function processTransaction(txData){
console.log(txData)
}
You’ll notice a transfer transaction contains to
, from
, amount
and memo
properties.
We can make use of the to
property to make sure we only watch for transactions that relate to the selected user. Adjust the processTransaction
function to make use of our bot. To see transactions send a test transfer to your selected test account.
function processTransaction(txData){
if(txData.to === USERNAME) {
console.log(`Transfer sent to bot account`)
console.log(txData)
}
}
Step 3 - Create calcVoteWeight()
In the previous tutorial we broadcast a vote over the blockchain using DSteem. We set the voteWeight to 10000
which is a full 100% vote. In this paid voting bot we’ll want to check the amount a user sent, setting a rule for what percentage a user should receive.
To make it simple for this tutorial I’m going to set the price as 1SBD is equal to 100% upvote. You can of course come up with some more complicated rules.
Out calculation functions should take the amount a user paid and return a vote weight based on set rules.
function calcVoteWeight(amountPaid) {
const fullVoteCost = 1
}
As users can send SBD or STEEM we’ll need to split the amount sent and check the token type. Split the array and save the separate parts.
function calcVoteWeight(amountPaid) {
const fullVoteCost = 1
const transfer = amountPaid.split(' ')
const tokenType = transfer[1]
const tokenValue = transfer[0]
}
With our data set it’s time to make a calculation. We work out a percentage based on the amount a user sent. For example if a user sends 0.2SBD they’ll get (0.2/1)*100 = 20%
function calcVoteWeight(amountPaid) {
const fullVoteCost = 1
const transfer = amountPaid.split(' ')
const tokenType = transfer[1]
const tokenValue = transfer[0]
let weight;
// bid calculation
if (tokenValue >= fullVoteCost) {
weight = 100
} else {
weight = (tokenValue/fullVoteCost) * 100
}
}
With this calculation we’re close but we need to also check the type of token sent. Steem/SBD are current different values, if a user sends STEEM it should be worth proportionally less. We also return the value multiplied by 100 as the blockchain full vote is 10000 not 100.
let steemToSbdRatio = 0.4
if( tokenType == 'STEEM') {
return (weight * steemToSbdRatio) * 100
} else {
return weight * 100
}
Step 4 - Create permlinkFromMemo(memo)
If a user is paying for a vote from our bot we’ll need to also know which post to update. The typical format for this behaviour is to include the post link in the memo. We can create a helper function here that takes the raw memo data and splits it at a slash. Take the final part of the array created form split, this will be the permlink part of the url.
// get the permlink part of a url from memo
function permlinkFromMemo(memo){
return memo.split('/').pop()
}
Step 5 - Update SendVote()
broadcasting function
Pulling all of this together we’ll first need to update our sendVote
function. Switch out the hardcoded weight value with a variable and pass that as a parameter to the function. Also update the logged response as a result.
// Broadcast vote using DSteem
function sendVote(author, permlink, weight) {
client.broadcast.vote({
voter: USERNAME,
author: author,
permlink: permlink,
weight: weight
}, POSTING_KEY)
.then( (result) => {
console.log(`${author} Paid for a ${weight/100}% vote on ${permlink}`)
console.log(result)
})
}
Finally stitch our helpers together from with the processTransaction()
call
function processTransaction(txData){
// example txData - {from: "username", to: "username", amount: "0.000 STEEM", memo: "...."}
if(txData.to === USERNAME) {
// pass amount value to calculation function
let voteWeight = calcVoteWeight(txData.amount)
// get the permlink property from the memo data with the helper
let permlink = permlinkFromMemo(txData.memo)
// broadcast the vote with relevant data
sendVote(txData.from, permlink, voteWeight)
}
}
Okay. With that you’re paid voting bot is ready to roll! Go ahead and send some test transfers with memo’s 🙌.
You can adjust the rules within calcVoteWeight()
to be as complex as needed. You may decide certain hashtags or users get a better rate (to do that you would need to look up the data relevant to the permlink).
I hope you found this small project helpful for getting to grips with DSteem and making scripts that interact with the blockchain.
👨🏼💻 The full code for the script can be found on Github & CodePen 🚀
Series - DSTEEM Tutorials
000 - Steem Post Feed With DSteem & Vue
001 - Getting Started With DSTeem - Auto Vote Bot
Thank you for your contribution. Below is our review:
Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.
To view those questions and the relevant answers related to your post, click here.
Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]
Hey, thanks for the review and detailed feedback!
Totally realise there is a number of similar DSteem tutorials out there. Working to create a consistent catalogue that anyone who follows the tutorials can know and recognise my style. Hopefully there is not too much crossover along the way. No need to re-invent the wheel and all that. I like to think making these more accessible by setting the code up on Codepen.io adds a unique offering too.
Would have liked to add dynamic ratios, task queue and some extra rules for paid votes too but felt a tad too much for this one. With out a doubt there are plenty of ways to improve this script.
Thank you for your review, @mcfarhat! Keep up the good work!
Hi @codewithsam!
Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server
Hey, @codewithsam!
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!
Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!
Congratulations @codewithsam! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :
Click here to view your Board of Honor
If you no longer want to receive notifications, reply to this comment with the word
STOP
To support your work, I also upvoted your post!
Congratulations @codewithsam! You received a personal award!
Click here to view your Board
Do not miss the last post from @steemitboard:
Congratulations @codewithsam! You received a personal award!
You can view your badges on your Steem Board and compare to others on the Steem Ranking
Vote for @Steemitboard as a witness to get one more award and increased upvotes!