Tutorial 4 - Running a Pay Server on Bitcoin Testnet

From RunWiki
Jump to: navigation, search

ALERT: This Page is Outdated and Waiting for Update The current way of testing the RUN library to create tokens and jigs is to open the devtools console at Runcraft.io, then head over to creating and loading jigs.


In the previous tutorials, you learned how to fund your purse in Part 1 with WhatsOnChain and how to import your private key in Part 2 with Electrum SV.

You’re about to learn not only how to use RUN on the Bitcoin Testnet, but also how to use a Pay Server to fund the transactions instead of having to use your own purse.

The Bitcoin Testnet acts just like the Mainnet: there are miners with servers around the world that mine bitcoin by packaging up transactions into blocks. The only difference is that the Testnet bitcoins aren’t worth anything on the exchanges, so the mining difficulty is much lower. Developers use the Testnet to make sure that their applications will work correctly before putting any real bitcoin at stake.

Companies will use Pay Servers to comp their customer’s transactions. Think of it like when you go to a store and they don’t charge you anything to use your credit card. The store owner is paying something like 2.5% as a fee to the credit card processor. The store owner eats the cost for your convenience so that you will hopefully shop there more. You could imagine a similar business model working for Bitcoin transactions, especially since the fees are much, much lower—only a fraction of a USD cent.

Imagine a video game company that develops a game that records moves onto the blockchain. The game company would pay for the transactions for all their players because they could make money in other ways like selling game items: potions, armor, weapons.

When you put these two concepts together, the Testnet and the Pay Server, then you get a powerful environment for developing real-world applications that utilize data on the blockchain.

Getting Started

This tutorial builds on the knowledge that you’ve learned from the other three tutorials. Think of this one as intermediate level. We’re going to go quite fast and to try and save space, provide fewer beginner-friendly explanations about the tooling in this one. If you find yourself struggling, try going back to make sure you grok everything in the Intro to Jigs tutorial. But also, don’t be shy about sending us feedback. We love to hear from you and we’re always improving.

To set up your development environment, open the RUN Homepage in the Firefox browser. You'll be coding right on this homepage.

By itself, RUN will upload, read, and call code, then sign and send transactions. But RUN also includes many optional plug-ins you might find useful. The PayServer is one such plug-in, and we’re going to use it in this tutorial. You can already use the BitIndex and WhatsOnChain APIs as alternatives to RUN Connect and you can imagine that as the Bitcoin developer ecosystem expands in the future, other companies will build plug-ins that you can hook into RUN too. You’ll be able to select the most competitive offering that fits your needs. You’ll also be able to write your own Pay Server if you have the know-how to run a server in-house.

Since RUN is being developed as an open-source project, all Bitcoin companies are free to contribute to its development and make use of its ability to interact with jigs.

Connecting to Testnet and the Pay Server

Understanding server APIs

A Pay Server is a remote application programming interface, colloquially known as an API. You send the server requests and it responds with answers. Server APIs will usually require that you use an API Key. The API Key is like your user account with the server so that it knows who you are. If you misbehave by, for example, sending too many requests per second, then your access will get revoked.

Normally you would get your API Key from your User Profile after you had logged in on a website. Since this tutorial is only using the Testnet, the bitcoins are free, so we’ve included a handy widget in the tutorial to generate an API Key.

Click Generate to create an API Key for you to use to connect to the server:

Click here to open the widget

Request an API Key

Pro tip: To select a whole string, double-click it. That makes it easy to copy and paste elsewhere.

Now that you’ve got your API Key, you’re ready to connect the server.

From the getting_started.html tab, open the Developer Tools Console by pressing Control-Shift-K on Windows or Command-Option-K on macOS.

Type this code into the Console, replacing the fill-in-the-blank underscore characters with your actual API Key:

const apiKey = '_YOUR_API_KEY_HERE_'

const run = new Run({ network: 'test', 
                      purse: new Run.plugins.PayServer(apiKey) })

There are a couple of new concepts in that code. You’re connecting to Testnet by passing 'test' as the network parameter. Also, instead of specifying a private key for the purse, you pass a PayServer instance. The Pay Server is replacing the functionality of the standard purse. The Pay Server will return signed transactions and provide funds for the mining fees.

Coding up your digital pets

In the previous tutorials, you stayed close to the basics in your JavaScript code, but this time, your code will become more advanced.

Type this code into the Console:

class Dragon extends Jig {
  // 1
  init(name) {
    this.name = name
    this.flights = []
  }
  // 2
  fly() {
    this.flights.push(this.flights.length + 1)
  }
}
Dragon.icon = { emoji: '🐉' }
// 3
const stevie = new Dragon('Stevie')
const wonder = new Dragon('Wonder')

Here’s what you’re doing with that code:

You use init() to declare all your properties and give them default values. In this case, you provide a convenience initializer that accepts name as a parameter. The fly() method updates the flights property to keep track of how many times you take your dragon out for a ride. After all, every once in a while, it is important to give your dragon some exercise and let him or her breathe some fresh outdoor air. You bring two dragons to life. With two dragons in your service, you’ll be able to assert your authority like Dany over the Seven Kingdoms in Game of Thrones! 🤩

Using the Testnet Explorer

The first thing you’ll want to do is check and make sure the dragons are live on the Testnet. Type this code into the Console to get your dragons’ status:

console.log('Stevie: ', stevie.location)
console.log('Wonder: ', wonder.location)

You’ll see the locations for both of your dragons:

1 stevie-location.png


You can explore locations with the RUN Explorer.

Select Stevie’s location as shown in the screenshot above, and copy it.

From the getting_started.html page, click the Explorer link in the top right corner:

2 explorer.png


Click the network toggle to select Testnet:

3 search-testnet.png


The Mainnet and Testnet are separate networks each with their own blocks and transaction IDs. Since your dragon transactions are on Testnet, you’ll need to make sure you’re looking in the right place for them.

Paste Stevie’s location into the Search box. If everything went according to the plan, then you’ll be able to see the properties for your instance of Dragon. Your location and owner will be different than the ones in the screenshot because you’ve generated your own transactions.

Try searching for Wonder’s location as well.

Now that you’ve confirmed your dragons are alive on Testnet, you can interact with them.

Type this code into the Console:

wonder.fly()

You don’t want to show favoritism to just one dragon, so you need to make sure you take Stevie outside as well. Type this code into the Console:

stevie.fly()

Now that you’ve got both dragons out on the town, you can travel around, put the villagers on high alert, and scare some of your enemies. 🙀

Managing the owner private key

To ensure Wonder and Stevie continue to listen to you, you’ll need to safeguard your owner private key. As long as you possess the owner private key, you can call methods on jigs to give them instructions. But without the owner private key, you would merely become an observer, unable to issue new instructions.

Type this code in the Console to get the owner private key:

run.owner.privkey.toString()

Save the private key string returned by the Console safely encrypted in a password manager app on your computer. Give it a good name: run Pay Server on Testnet: owner. If anyone else gets your private key, they’ll be able to give instructions to your dragons. You certainly don't want that to happen, so take care with how you manage your keys.

Next, copy your API Key from the Generator above and save it using the same method as you did for the private key. Give it a good name as well: run Tutorials: Testnet API Key.

By having both keys, you’ll be able to take a break, close your browser, even restart your computer, and still continue working on your code another day.

Resuming your Testnet session

When you have both keys written elsewhere, hover over the Firefox browser tab and click × to close the tab.

Then open getting_started.html in a new tab.

Open the Console by pressing Control-Shift-K on Windows or Command-Option-K on macOS.

Type the following code into the Console, replacing the fill-in-the-blank underscore characters with your actual API Key and also separately, your actual owner private key:

// 1
const apiKey = '_your_API_Key_here_'
// 2
const run = new Run({ network: 'test', 
                      purse: new Run.plugins.PayServer(apiKey), 
                      owner: '_your_owner_private_key_here_' })
Pro tip: A string with underscore spacers between the words acts like a single word, so you can double-click it to select the whole string. That makes it easy to replace placeholders when copying and pasting.

Here’s what’s happening in that code:

  1. As you might have surmised, apiKey is not something that comes from RUN. Instead, it represents your user account for the RUN Pay Server. When you have a valid API Key, the RUN Pay Server will cover the cost of the transaction fees for your actions in RUN. That way, you don’t need to fund your own purse. The API Key is like your user account from the company. As you become a more experienced developer, API Keys will be a familiar tool you’ll use to get things done. Many companies offer different APIs for your convenience. A good example is the company, Twilio, which has APIs to send phone text SMS messages and start a video call. When you find ways to integrate APIs into your apps, you’ll save yourself development time because the code is written for you so you don’t have to fuss with device compatibility and edge cases.
  2. When you created the Run instance at the beginning of the tutorial, you instructed RUN to assign you a random owner since you did not pass anything for the owner property. But now that you’re restoring your session, this time you passed in your saved owner private key. RUN will use that account instead of a random one.

To check if you still own your dragons, type this code into the Console:

await run.inventory.sync()

run.inventory.jigs

The jigs array get downloaded when you initialize RUN with an owner and call run.inventory.sync().

Jigs will be added and removed from the array as you interact in your RUN session. If you know that updates have happened on the network over time, off of your local client, then you can call await run.inventory.sync() to grab all the latest updates from the network.

Wherever you see await, that is a JavaScript Promise. It will asynchronously, meaning, in the background, fetch all the jigs from the network that are owned by the owner. You use the await keyword to allow the fetch to finish before checking out the result.

If everything went according to plan, you will get back an array with your two dragons.

Click the disclosure triangle for Array [ Proxy, Proxy ] to reveal the contents of the array and then click two more disclosure triangles to reveal the contents of 0: Proxy and then : Object:

4 expand-jig.png


From here you can see the properties that Wonder the dragon has. Notice that the value of origin is different than the value of location because you updated the instance by instructing Wonder to fly().

Select the Transaction ID portion of the location, the bit before the underscore, as shown in the screenshot above.

Copy the Transaction ID.

Open a new browser tab and navigate to WhatsOnChain.com:

5 whatsonchain-testnet.png


Once the page loads:


  1. From the header, navigate to Network ▸ Testnet.
  2. In the Search box, paste the Transaction ID and press Return on your keyboard.

You’ll see the op_return text in the output index, _o0:

6 whatsonchain-transaction.png


The op_return text is encrypted during the Alpha phase, but it basically just contains the method call, fly(). On the left side of the page, the inputs reference the parent transactions.

Coming from the previous Mainnet tutorial, you already knew how to step through forwards and backwards using transaction inputs and outputs. But now, in this tutorial, you’ve seen how to use WhatsOnChain with Testnet transactions too.

Since you’ve successfully restored your RUN Testnet session, you’re the rightful owner of the dragons and you’re ready to use the Pay Server to cover the cost of the next actions you want to take with the dragons.

Where to go from here

You learned how to configure RUN to use Testnet as an alternative to both Mainnet and the local machine Mockchain. While transactions on Testnet do require paying mining fees, you can get Testnet bitcoins for free since they don’t have real-world value on exchanges. Visit a faucet like bitcoincloud.net to acquire Testnet bitcoins. You’ll be able to send those Testnet bitcoins to your purse and operate RUN on Testnet without a Pay Server. As a challenge, see if you can complete this tutorial without using a Pay Server but still using Testnet. To get you started, make sure you know how to use the purse with bitcoin loaded into it, check out: Tutorial 2 - Running jigs on Bitcoin Mainnet, Part 1. You’ll just need to use Testnet bitcoin instead of Mainnet bitcoin.

In this tutorial, you got to see how companies could pay or their customers transactions with a Pay Server. On Testnet, using a Pay Server is not that big of a deal since the Testnet bitcoins don't have an exchange price. But you can imagine a project like this would be a practice session before deploying to Mainnet. On Mainnet, using a Pay Server could save your customers the mining fee, a fraction of a cent, for every action they take. You could build a game that writes data to the Bitcoin blockchain without bundling a bitcoin wallet into the app. The customer wouldn’t even have to necessarily know they are using Bitcoin. 🤩

You’re beginning to see that jigs can be used by many different kinds of businesses, like video game companies and even shipping logistics companies. By using Bitcoin as a neutral datastore, separate companies can collaborate with a single source of truth. With a Pay Server, companies could insert RUN into their existing infrastructure and not require every operator to have a bitcoin wallet. A Pay Server transforms RUN into merely another API like how a shipping company updates your package tracking number each time it reaches a new stage in the shipping process.

When you’re ready to move on, jump into the next lesson, Tutorial 5 - Setting icons for your jigs: emojis and SVG images