/ Smart Contracts

How to Create a Codius Contract from Scratch and Upload it to a Host.

Cale Robertson

An avid FPS gamer and game developer. ILP/XRP/Codius developer.

Read More

Codius is gaining traction in the community like an out of control steam train, but it's still hard to figure out how to go about developing for the platform. This tutorial aims to fix that.

This tutorial will be using the Windows 10 operating system.

I have also created a video tutorial that you can use instead or to aid in following this tutorial - https://youtu.be/Fo0_7CvULA0

There are four main dependencies we'll need before we can start developing the contract. Each of which we will install during this tutorial:

  • NodeJS
  • Moneyd - Requires a wallet with at least 16 XRP available (in addition to reserve)
  • Codius CLI
  • Docker


Step 1 - Install NodeJS:

NodeJS is what all the codius related tools are reliant on, it allows Javascript to be run on a computer/server as opposed to in a browser.

Let's download it from here: https://nodejs.org/en/download/

nodescreen

Run the downloaded package and go through the steps to install NodeJS (all defaults should be fine).


Step 2 - Install Moneyd:

Moneyd is what we use to create an uplink to the Interledger Protocol, in order to be able to send packets of money over the internet.

To install it we use the npm commands that come packaged with NodeJs.

Open a Command Prompt console and enter the following:

npm install -g moneyd moneyd-uplink-xrp

This installs Moneyd as well as the uplink required to use XRP as our currency of choice.
Using -g makes it a global install as opposed to localized in the current folder.


Step 3 - Configure Moneyd:

Now that Moneyd is installed, we need to configure it.

For this you'll need the secret/private key for your XRP wallet. This wallet needs to have at least 16 XRP available in addition to the base reserves. This is to cover additional reserves and channel creation funds.

In the console run the following:

moneyd xrp:configure

You'll be prompted for your XRP wallet secret (private key). It should start with an 's'.

  • Type or paste in your private key and press the Enter key.

Moneyd should now be configured, and you can start it up to ensure it works properly.

moneyd xrp:start

You should be greeted with something similar to the below:

moneyd2

The last line connector:app info connectory ready is what you're looking for to make sure Moneyd is starting up correctly. It may take a few moments before it appears.

Now that we know Moneyd is working, hit CTRL + C a few times to stop the process, as we won't need it for a little while.


Step 4 - Install Codius CLI:

CLI stands for Command Line Interface, and is a tool we run using a console (like Command Prompt) to make use of various Codius tools, like the pod upload command.

Once again we make use of the npm suite.

npm install -g codius

We can make sure the Codius CLI installed correctly using:

codius --version



Step 5 - Install Docker CE:

Docker is what we will use to create a virtualized container image containing our application.

Download the Docker CE (Community Edition): https://store.docker.com/editions/community/docker-ce-desktop-windows
You will need to create an account before you can download. This account will be used later on as each image you create is hosted on your personal Docker repository.

  • Note: If running Win7 (not officially supported) you'll need to download Docker Toolbox instead (and you may not see a Whale in the System Tray)

Run the installer you just downloaded:

  • When it's complete, you should see this symbol in the System Tray: whale-x-win-1-

If it's not in your System Tray just open:

  • Docker for Windows from your Start Menu.

Once Docker is running, it might give you a big popup saying "Enable Hyper-V". I would suggest NOT clicking enable. Instead, hit cancel to close Docker. The reason I say to do this is from my experience allowing Docker to enable Hyper-V can cause issues.
Only do this if Docker is complaining about Hyper-V not being enabled! If it's already enabled, just skip the the highlighted *.

Instead, we will do it manually through PowerShell.

  • Type PowerShell into the Start Menu
  • Right-Click and hit Run as Administrator
  • Hit Yes/Allow if prompted with a security popup.
  • Run the following command (it will require your machine to restart)
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All

Once your machine restarts, and goes through a Windows Update styled process:

  • Open Docker for Windows from the Start Menu again.

You should be greeted with a cute little whale again: whale-x-win-1-

*

Now that Docker is installed, we're finally ready to create our contract!

Step 6 - Create our Contract Application:

In this instance, our contract is going to be a basic web server, and will host a single index page so we can see it working from the browser.

Create a new folder on your computer, I called mine my-first-contract, and created it on my Desktop.

desktop

Open your favourite text editor, I use Notepad++ : https://notepad-plus-plus.org/download/v7.5.7.html

The first file we'll create is a package.json. This is what npm uses as a list of dependencies our application uses.

Copy and paste the below into the text editor:

{
    "name": "first-contract",
    "main": "server.js",
    "dependencies": {
        "ejs": "^2.5.5",
        "express": "^4.6.1"
    }
}

Save it in the my-first-contract folder as package.json (make sure the type is set to All types (*.*)):

filetype

Our folder now looks like this:

folder1

Let's create our main application now. This will be the http server that will host a web page.

Create a new file in your text editor and paste the following:

// server.js

// Load any dependencies
const express = require('express');
const app = express();

// Set the view engine to ejs
app.set('view engine', 'ejs');

// Use res.render to serve our index page on URL root / GET request
app.get('/', function(req, res) {
	res.render('pages/index');
});

// Make our server listen for requrests on port 1337
app.listen(1337);
console.log('1337 is the best port');

Save the file as server.js and ensure it's saved as All types (*.*):

serverFile

Our folder now looks like this:

firstPath

The last file we'll need is the actual web page our server will be hosting.

Create a new file in your text editor and paste the following:

<!DOCTYPE html>
<html lang=en>
<head>
	<meta charset="UTF-8">
	<title>My First Codius Contract</title>
</head>
<body>
	<h1> This is my Index page </h1>
	<p> Hopefully this will be running on a codius host shortly! </p>
</body>
</html>

Due to the way EJS expects the file structure to be, we'll save this file under my-first-contract\views\pages (this means creating two new folders).

Save it as index.ejs and ensure it's set as All types (*.*):

indexFile

Our folder should now look like this:

views
pages

That's it for the application! Those three small files are enough to create a web server and host a page. Now we have to make sure that application works.

Open Command Prompt and navigate to our my-first-contract folder. I saved mine to the Desktop so for me it looks like this:

cd Desktop
cd my-first-contract

We should now see our path is set the the path of our folder:

cd

Before we run our app, we need to install the dependencies (ejs and express). This is where our package.json comes in handy.

Run the following to make npm install any dependencies found in our package.json file:

npm install --save

You should now see a node_modules folder in our applications directory as well as a package-lock.json:

packlock

Step 7 - Test our Application:

In the console we just used (where we cd'd to our app folder), run:

node server.js

You should see something like this:

1337 is the best port

This means our server is up and running on port 1337. Let's browse to it and see if our page is working!

In your browser, browse to:

https://localhost:1337

Voilà, our page is up and running!

index

Now to turn this application into a Docker image so it can be used in a Codius manifest.

Press CTRL + C in the console to stop the application.

Step 8 - Create a Docker Image:

To compile an application into a containerized image, we need to create a Dockerfile, which is what Docker reads prior to compilation so it knows what to do.

Create a new text file in your editor and paste the following:

# Moneyd requires NodeJS 8.9.0 and above
FROM node:8.9.0

# The working/home directory of our application inside the container
WORKDIR /app

# Add the contents of our current directory into the /app folder of our container
ADD . /app

# Install dependencies from package.json using npm
RUN npm install --only=production

# Make port 1337 available to the outside world
EXPOSE 1337

# Run the command 'npm start' which will start our server.js file
CMD [ "npm", "start" ]

Save it as Dockerfile in our application folder remembering to have the type set to All types (*.*). The Dockerfile does not have a file extension.

Your folder should now look like this:

dockertute-1

Back to our Command Prompt. Login to docker using:

docker login
  • I login using my Docker username not email.

Now to compile our app into a docker image. Run the following (ensuring you're still cd'd into my-first-contract):

docker build -t {username}/my-first-contract .
  • Make sure you replace {username} with your docker username, with no brackets either.
  • Also note the space and fullstop at the end of the function; that tells docker the build from the current directory.

Once it's finished the build process we need to upload it to your docker repository. That's so our Codius manifest has somewhere to pull the image from.

Run the following:

docker push {username}/my-first-contract

Copy down the digest that is output at the end of the above command. It should look like:

sha256:7c8b236c5f01e5abc78c9500cce7c974ffcedd980e60c2d3a5f1a44c8455ae2d

That's it for Docker, now to upload it to Codius.

Step 9 - Create a Codius Manifest

When uploading a contract to Codius, we send it a manifest file listing any Docker containers or environment variables we need. Let's create that now!

Create a new file in your text editor and paste the following:

{
  "manifest": {
    "name": "my-first-contract",
    "version": "1.0.0",
    "machine": "small",
    "port": "1337",
    "containers": [{
      "id": "app",
      "image": "{username}/[email protected]{digest}",
  "workdir": "/app"
    }]
  }
}
  • Make sure you replace {username} with your Docker username and {digest} with the digest you copied down in the earlier step.

The image line of the manifest should now look something like this:

"image": "calerobertson/[email protected]:7c8b236c5f01e5abc78c950c2d",

Save as first-manifest.json in an easy location (I used E:\), and as always set type to All types (*.*).

Step 10 - The Upload:

Now for the moment of truth, the upload onto a Codius host!

Open up Command Prompt again and start Moneyd back up:

moneyd xrp:start

You should once again be greeted with some sweet ASCII art, and after a few moments, the line connector:app info connectory ready telling you that we're good to go.

Now open a second Command Prompt, and leave the one running moneyd on in the background.

Modify and enter the following to upload your manifest to a Codius host:

codius upload {manifest filepath} --host https://{hostname} --duration 300
  • Where {manifest filepath} is the full filepath to wherever you saved your manifest file.
  • --host points to whichever host you want to upload to (requires https as the start, which I've already pre-filled).
  • --duration is the duration in seconds (300 will be 5 minutes).

My upload command looks like this:

codius upload E:\first-manifest.json --host https://host1.codius.live --duration 300

You should be seeing some packets (of money) flying down the screen in the Command Prompt that is running Moneyd in the background:

moneydpackers

It can take some time to upload, especially if the manifest contains images that have never been used on the host before.

After no more than about 30 seconds we should be greeted with some output (in the Command Prompt we did the upload from), hopefully showing a successful upload:

Successfully Uploaded Pods:
{
URL:https://l2xvchk27rbrnh3mc3y4p3iaeoonjzur2u24qxuod2iaqd5mlioa.host1.codius.live,
Manifest Hash: l2xvchk27rbrnh3mc3y4p3iaeoonjzur2u24qxuod2iaqd5mlioa,
Host: https://host1.codius.live,
Expiry: 2018-07-07T00:40:48.265Z,
Expiration Date: 07-07-2018 12:40:48 +0000,
Expires: in 5 minutes,
Price Paid: 1142,
}

The above output shows a successful upload, and we can now browse the URL it returned to see our running app.

Go the that URL and you should see your contract running live and securely on the selected host:

codiusupload

Congratulations!

You just created your first smart contract from scratch and uploaded it to a Codius Host.



If your upload failed, try uploading using my tool at Https://upload.host1.codius.live . If an upload from my tool works but yours failed, there might be an issue with the syntax you entered in the upload command.


Did you like this post by Cale Robertson?

Send some love: