Tutorial - DSteem - Basic Paid Voting Bot

View this thread on: d.buzz | hive.blog | peakd.com | ecency.com
·@codewithsam·
0.000 HBD
Tutorial - DSteem - Basic Paid Voting Bot
#### Repository
https://github.com/jnordberg/dsteem/


![tutorialbanner02.jpg](https://files.steempeak.com/file/steempeak/codewithsam/gmChIcIc-tutorial-banner-02.jpg)

## 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](https://steemit.com/dsteem/@codewithsam/tutorial-getting-started-with-dsteem-auto-vote-bot-1544552622646) we’ll listen for transactions on the blockchain. When our bot receives a `transfer` we’ll check the data and broadcast a response.

- [000 - Steem Post Feed With DSteem & Vue ](https://steemit.com/utopian-io/@codewithsam/tutorial-create-a-steem-post-feed-with-vue-and-dsteem-1544114616873)
- [001 - Getting Started With DSTeem](https://steemit.com/dsteem/@codewithsam/tutorial-getting-started-with-dsteem-auto-vote-bot-1544552622646)


> 👨🏼‍💻 The full code for the script can be found on [Github](https://github.com/code-with-sam/dsteem-tutorials/tree/master/02/paid-upvote-bot) & [CodePen](https://codepen.io/code-with-sam/pen/GPJzwK?editors=0010) 🚀

#### 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](https://github.com/code-with-sam/dsteem-tutorials/blob/master/02/paid-upvote-bot/dsteem-tutorial-02-base.html) 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](https://codepen.io/code-with-sam/pen/Xobwwq?editors=0010)

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)
}
```

![screely1544612247232.png](https://files.steempeak.com/file/steempeak/codewithsam/C2kXwzhp-screely-1544612247232.png)

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](https://github.com/code-with-sam/dsteem-tutorials/tree/master/02/paid-upvote-bot) & [CodePen](https://codepen.io/code-with-sam/pen/GPJzwK?editors=0010) 🚀


### Series - DSTEEM Tutorials
[000 - Steem Post Feed With DSteem & Vue ](https://steemit.com/utopian-io/@codewithsam/tutorial-create-a-steem-post-feed-with-vue-and-dsteem-1544114616873)
[001 - Getting Started With DSTeem - Auto Vote Bot](https://steemit.com/dsteem/@codewithsam/tutorial-getting-started-with-dsteem-auto-vote-bot-1544552622646)
👍 , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,