Cryptocurrencies have been in use since 2009, when Bitcoin was officially launched. As a result of its acceptance over time, numerous other cryptocurrencies and tokens have been created and are in use.
Today, people have crypto portfolios where they hold different cryptocurrencies. There is often the need to know the value of one crypto against another. This need has given birth to cryptocurrency converters. Cryptocurrency converters are applications that convert the value of one crypto to another.
In this tutorial, we will build a simple cryptocurrency converter. It will consume external crypto APIs that return real-time cryptocurrency rates. It will be able to convert the value of one coin to another. An example would be converting Bitcoin to Ethereum. If the value of Bitcoin (BTC) is entered, it will calculate and give the equivalent value in Ethereum (ETH). Strapi will be used to build out the application's backend, and Svelte will be used for the front end. With that said, let's get started.
This tutorial has two sections.
Goals of the First Section
By the end of the first section, the reader should understand the following concepts: Strapi, Strapi collection types, Strapi routes, & Strapi controllers and methods, and be able to create the backend of our Cryptocurrency converter using JavaScript in our Strapi controller.
Goals of The Second Section
By the end of the second section, the reader should:
Readers should have a basic knowledge of HTML, CSS, JavaScript, Node.js, Yarn, and ReactJs or VueJs to follow along.
Strapi is an open-source headless CMS built with React and Node. It gives the developers the flexibility of using the technology of their choice in the front end of the application. With a good understanding of Node.js and the React framework, Strapi can be used to build anything. Let's get started building the backend of the application with Strapi.
To get started, let's create a new Strapi project using Yarn like so:
yarn create strapi-app crypto-converter --quickstart
The command above scaffolds a new Strapi project in your preferred directory. The --quickstart
command makes the process even more seamless by handling databases and others
Note that NPM can also be used in place of Yarn. Once the installation is complete, you will be redirected to the page below and prompted to create an admin account needed to access the Strapi admin panel.
After creating the account, you will be redirected to the dashboard like the one in the image below. You have now become the first admin to your Strapi project.
Now we have created our admin user account, let’s proceed to creating our API in the next step below.
Now, we have created our project and an admin account to access the dashboard. Let’s dive into the main business of the day which is creating our crypto convert app. In our Strapi application, we need a Route and a Controller to keep stuff organized. Let’s create a collection type from our dashboard. To create a collection type, follow the steps outlined below on the Strapi admin panel:
If you still need help with creating your collection type, check Strapi documentation.
Creating a collection type in Strapi goes ahead to modify the structure of the codebase of our Strapi project. In our case, this is what our API folder looks like
The collection type we created in the API folder modified the files and folders into an MVC design pattern. Strapi was built this way. Collection types created from the admin dashboard generate new files and folder structures. Next, we need to create a new controller file and a route that will point to the controller where all of our logic and external API calls will be implemented.
Create controller
In Strapi, there are two ways of creating a controller. We can create a controller using the strapi generate
command as we have below:
1 strapi generate:controller my-crypto-converter
or simply create a new JavaScript file in the controller folder (API/crypto-converter/controller). In our case, I chose the second option. I created a new JavaScript file in the project directory named my-crypto-converter.js .
In the newly created controller, let's add a new method like so.
1 'use strict';
2 /**
3 * Read the documentation (https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#core-services)
4 * to customize this service
5 */
6 module.exports = {
7 convert: async ctx => {
8 await ctx.send({
9 message: "controller configured"
10 })
11 },
12 };
Every Strapi controller must be an async
and await
JavaScript function like what we have above. The ctx.send()
method is one of the many Strapi in-built methods. It is used to send responses in message form.
Let us proceed by creating our route. Navigate to the api/crypto-converter/config/routes.json file. You will find already generated routes for our collection type. We will add one more router link pointing to our newly created controller like so:
1 {
2 "method": "POST",
3 "path": "/my-crypto-converter/convert",
4 "handler": "my-crypto-converter.convert",
5 "config": {
6 "policies": []
7 }
8 }
The handler
points to the controller and the method. my-crypto-converter
is the controller while convert
is the method in the controller we need to trigger its action. path
points to the router path.
At this point, we have successfully created our route and controller. We need to grant public access to the route. This will make it accessible publicly. To grant access, navigate to settings→users & permissions plugins→permissions→application and grant public access to the /my-crypto-converter/convert
route.
For more details on setting roles and permissions in Strapi, check the documentation here.
Now we are good to go. We need to make API calls to an external crypto API endpoint (for real time exchange rates). There are plenty of ways we can achieve this but for this tutorial, we will use Axios. To install Axios
in our app use the following command:
yarn add Axios
After installing Axios, we should be ready to make external API calls using it. We need a way to get up-to-date exchange rates of cryptocurrencies. For this, we will consume the nomics.com API. I choose it because of how easy it is to create an account and generate your API key. I have created my account and generated my API key. If you are coding along, you should do the same too. Check the documentation for more details on creating your API key.
We will make an HTTP Get request to the endpoint below to get the exchange rate of any cryptocurrency against US dollars (USD).
1https://api.nomics.com/v1/currencies/ticker?key=YOUR_API_KEY&ids=BTC,ETH,XRP,
The result of the API call will enable us to calculate the rate of one crypto to another.
In my-crypto-converter.js
modify the contents like so:
1 'use strict';
2 const axios = require('axios');
3 /**
4 * Read the documentation (https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#core-services)
5 * to customize this service
6 */
7 module.exports = {
8 convert: async ctx => {
9 //post values
10 const amount = ctx.request.body.amount;
11 const baseCoin = ctx.request.body.baseCoin;
12 const compareCoin = ctx.request.body.compareCoin;
13
14 // fetch all rates in USD
15 const baseCoinRate = await getRate(baseCoin);
16 const compareCoinRate = await getRate(compareCoin);
17 // get rate in crypto currency
18 const exchange = await calculateExchange(baseCoinRate, compareCoinRate, amount);
19 return exchange;
20 },
21
22 };
23 //get exchange rate
24 async function getRate(coin){
25 //API key should be passed along as key in the URL below
26 const { data } = await axios.get(`https://api.nomics.com/v1/currencies/ticker?key=169170*******************90&ids=${coin}`);
27 return data[0].price;
28
29 }
30 // calculate and return result
31 async function calculateExchange (base, compare, amount){
32 const rate = await base/compare;
33 const result = await rate * amount
34 return result;
35 }
36 };
In the code above, we did the following:
I’ll explain every step in detail. In the convert
method in our controller, we accepted a few arguments coming from the Svelte app. These are amount
, baseCoin
, compareCoin
.
baseCoin
is the coin we have possession of and want to confirm its value against another. compareCoin
is the currency we are comparing baseCoin
value against, amount
is the total amount to convert.
We can convert crypto against another by dividing the value of the baseCoin
by the value of compareCoin
and multiplying the result by the value of the amount
. This was done in calculateExchange
function above.
Fetch coin values
We created two additional functions getRate()
and calculateExchange()
. getRate()
fetches the rate of a particular coin using Nomic API. It accepts a parameter coin
. This is the short code of the coin which is passed along with the API call. The function returns the current exchange rate of the coin in question.
1 // fetch all rates in USD
2 const baseCoinRate = await getRate(baseCoin);
3 const compareCoinRate = await getRate(compareCoin);
4
5`calculateExchange()` does the calculation and logic. It returns the final result. This function accepts three parameters `baseCoinRate`, `compareCoinRate`, `amount`. This snippet below shows how we used it.
6
7
8 // calculate and return result
9 async function calculateExchange (base, compare, amount){
10 const rate = await base/compare;
11 const result = await rate * amount
12 return result;
13 }
In convert
, we called all the functions and return a response to our Svelte frontend. Let's proceed to create the Svelte app.
Svelte is a modern-day JavaScript compiler for creating reactive web applications and interfaces. It can be used in parts of an already existing application or in a new single-page application (SPA).
Svelte is very similar to other frontend JavaScript frameworks like React and VueJS but it uses a different approach that avoids a virtual DOM. Svelte compiles your HTML, CSS, and JavaScript into a single build file that can be deployed. This makes it a lot faster and provides a better user experience.
Why use Svelte?
Cons
With that said, let’s proceed by creating the front end of our Cryptocurrency converter application using Svelte. The next step is to create a Svelte app.
To get started, let's create our svelte app using the command below:
1 npx degit sveltejs/template crypto-converter-svelte
2 cd crypto-converter-svelte
3 npm install
4 npm run dev
npx degit sveltejs/template crypto-converter-svelte
scaffolds a Svelte in a directory named crypto-converter-svelte
. cd crypto-converter-svelte
navigates into the project directory of our newly created Svelte app. npm install
installs all the dependencies in the package.json
file of the svelte app needed for the app to function properly.
npm run dev
starts the application in a local development environment making it available at localhost:5000
. The application will automatically reload when we save any change.
Let’s take a closer look at the folder structure of the Svelte application:
1moz-todo-svelte
2├── README.md
3├── package.json
4├── package-lock.json
5├── rollup.config.js
6├── .gitignore
7├── node_modules
8├── public
9│ ├── favicon.png
10│ ├── index.html
11│ ├── global.css
12│ └── build
13│ ├── bundle.css
14│ ├── bundle.js
15│ └── bundle.js.map
16├── scripts
17│ └── setupTypeScript.js
18└── src
19 ├── App.svelte
20 └── main.js
The main.js
file is the main point of entry of the Svelte application. It imports the App.svelte
component which is the main component of our Svelte application like you can see below.
1 import App from './App.svelte';
2 const app = new App({
3 target: document.body,
4 props: {
5 name: 'Moses'
6 }
7 });
8 export default App;
Svelte is a component-based framework. You can think of Svelte components as building blocks of the application. It has a <script></script>
section for writing JavaScript, a mark up section for HTML
and a <style></style>
for writing CSS
. The following is the content of our App.svelte
.
1 <script>
2 export let name;
3 </script>
4 <main>
5 <h1>Hello {name}!</h1>
6 <p>
7 Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn
8 how to build Svelte apps.
9 </p>
10 </main>
11 <style>
12 main {
13 text-align: center;
14 padding: 1em;
15 max-width: 240px;
16 margin: 0 auto;
17 }
18 h1 {
19 color: #ff3e00;
20 text-transform: uppercase;
21 font-size: 4em;
22 font-weight: 100;
23 }
24 @media (min-width: 640px) {
25 main {
26 max-width: none;
27 }
28 }
29 </style>
Let's modify the content of App.svelte
to build out our frontend. Replace the content of App.svelte
with the code below.
1 <script>
2 import Modal, { getModal } from "./Modal.svelte";
3 let amount;
4 let baseCoin;
5 let convertCoin;
6 let result;
7 function handleSubmit(e) {
8 conversion(amount, baseCoin, convertCoin);
9 }
10 async function conversion(amount, baseCoin, convertCoin) {
11 const call = await fetch(
12 "http://localhost:1337/my-crypto-converter/convert",
13 {
14 method: "POST",
15 body: JSON.stringify({
16 baseCoin: baseCoin,
17 compareCoin: convertCoin,
18 amount: amount,
19 }),
20 headers: {
21 "Content-type": "application/json; charset=UTF-8",
22 },
23 }
24 );
25 result = await call.json();
26 //opens modal
27 getModal().open();
28 }
29 </script>
30 <div class="container">
31 <h1>Crypto converter</h1>
32 <form id="surveyForm" class="mt-4" on:submit|preventDefault={handleSubmit}>
33 <div class="form-group">
34 <label for="baseCoin">Choose base currency:</label>
35 <select name="baseCoin" bind:value={baseCoin}>
36 <option value="BTC">Bitcoin</option>
37 <option value="ETH">Ethereum</option>
38 <option value="XRP">Ripple</option>
39 <option value="audi">Audi</option>
40 </select>
41 </div>
42 <div class="form-group">
43 <label for="compareCoin">Choose currency to convert to:</label>
44 <select name="compareCoin" bind:value={convertCoin}>
45 <option value="BTC">Bitcoin</option>
46 <option value="ETH">Ethereum</option>
47 <option value="XRP">Ripple</option>
48 <option value="audi">Audi</option>
49 </select>
50 </div>
51 <div class="form-group">
52 <input
53 type="num"
54 class="form-control"
55 placeholder="Enter amount in coin"
56 bind:value={amount}
57 required
58 />
59 </div>
60 <button class="btn btn-full">Convert</button>
61 </form>
62 <Modal>
63 <h4>Success!!</h4>
64 <h3>
65 <small>You will get</small>
66 {result} <small>in</small>
67 {convertCoin}
68 </h3>
69 </Modal>
70 </div>
71 <!-- the modal without an `id` -->
72 <style>
73 .container {
74 max-width: 1200px;
75 margin: 0 auto;
76 margin-top: 8rem;
77 }
78 h2 {
79 margin-top: 0;
80 }
81 .form-group > *,
82 .btn-full {
83 width: 100%;
84 }
85 .form-control,
86 .btn-full {
87 border-radius: 3px;
88 }
89 .submitted input:invalid {
90 border: 1px solid #c00;
91 }
92 .submitted input:focus:invalid {
93 outline: 1px solid #c00;
94 }
95 .error-alert {
96 border: 1px solid #c00 !important;
97 padding: 6px;
98 text-align: center;
99 color: #c00;
100 border-radius: 3px;
101 }
102 </style>
Let's go over the code above. In the main section, we added an HTML
form to accept the values of the cryptocurrency we want to exchange and the amount. We used svelte bind:value={}
to bind the form input to the variables used in the API call.
In the JavaScript section, we declared amount
, baseCoin
, convertCoin
variables and made our API call to our Strapi backend.
Adding a Modal to our Svelte Application Just to spice it up a little, we added a modal to display the response nicely. Check Svelte documentation for more on creating this simple modal.
getModal().open()
function opens up the modal to display response from the API.
The body of the modal is contained in the code below.
1 <Modal>
2 <h4>Success!!</h4>
3 <h3>
4 <small>You will get</small>
5 {result} <small>in</small>
6 {convertCoin}
7 </h3>
8 </Modal>
The modal component functionality is done in ./Modal.svelte
component. We imported it using this import Modal, { getModal } from "./Modal.svelte";
In the SRC directory, create a Modal.svelte file and add the following code to create a modal.
1 <script context="module" lang="ts">
2 let onTop; //keeping track of which open modal is on top
3 const modals = {}; //all modals get registered here for easy future access
4 // returns an object for the modal specified by `id`, which contains the API functions (`open` and `close` )
5 export function getModal(id = "") {
6 return modals[id];
7 }
8 </script>
9 <script lang="ts">
10 import { onDestroy } from "svelte";
11 let topDiv;
12 let visible = false;
13 let prevOnTop;
14 let closeCallback;
15 export let id = "";
16 function keyPress(ev) {
17 //only respond if the current modal is the top one
18 if (ev.key == "Escape" && onTop == topDiv) close(); //ESC
19 }
20 /** API **/
21 function open(callback) {
22 closeCallback = callback;
23 if (visible) return;
24 prevOnTop = onTop;
25 onTop = topDiv;
26 window.addEventListener("keydown", keyPress);
27 //this prevents scrolling of the main window on larger screens
28 document.body.style.overflow = "hidden";
29 visible = true;
30 //Move the modal in the DOM to be the last child of <BODY> so that it can be on top of everything
31 document.body.appendChild(topDiv);
32 }
33 function close(retVal) {
34 if (!visible) return;
35 window.removeEventListener("keydown", keyPress);
36 onTop = prevOnTop;
37 if (onTop == null) document.body.style.overflow = "";
38 visible = false;
39 if (closeCallback) closeCallback(retVal);
40 }
41 //expose the API
42 modals[id] = { open, close };
43 onDestroy(() => {
44 delete modals[id];
45 window.removeEventListener("keydown", keyPress);
46 });
47 </script>
48 <div id="topModal" class:visible bind:this={topDiv} on:click={() => close()}>
49 <div id="modal" on:click|stopPropagation={() => {}}>
50 <svg id="close" on:click={() => close()} viewBox="0 0 12 12">
51 <circle cx="6" cy="6" r="6" />
52 <line x1="3" y1="3" x2="9" y2="9" />
53 <line x1="9" y1="3" x2="3" y2="9" />
54 </svg>
55 <div id="modal-content">
56 <slot />
57 </div>
58 </div>
59 </div>
60 <style>
61 #topModal {
62 visibility: hidden;
63 z-index: 9999;
64 position: fixed;
65 top: 0;
66 left: 0;
67 right: 0;
68 bottom: 0;
69 background: #4448;
70 display: flex;
71 align-items: center;
72 justify-content: center;
73 }
74 #modal {
75 position: relative;
76 border-radius: 6px;
77 background: white;
78 border: 2px solid #000;
79 filter: drop-shadow(5px 5px 5px #555);
80 padding: 1em;
81 }
82 .visible {
83 visibility: visible !important;
84 }
85 #close {
86 position: absolute;
87 top: -12px;
88 right: -12px;
89 width: 24px;
90 height: 24px;
91 cursor: pointer;
92 fill: #f44;
93 transition: transform 0.3s;
94 }
95 #close:hover {
96 transform: scale(2);
97 }
98 #close line {
99 stroke: #fff;
100 stroke-width: 2;
101 }
102 #modal-content {
103 max-width: calc(100vw - 20px);
104 max-height: calc(100vh - 20px);
105 overflow: auto;
106 }
107 </style>
At this point, if you've followed along effectively, you should have a working crypto converter using Svelte in the front end and Strapi at the backend.
Great job, you’ve made it to the end of this tutorial. If you followed along correctly you should have a working app same as mine by now.
By now, you should be able to create an API to convert from one crypto to another using Nomic API and Strapi. You should have a basic understanding of Svelte enough to get started working with it.
Feel free to play around with what you have, modify it to suit your needs and don’t forget to share your experience with the rest of the community. A good idea might be creating a cryptocurrency blog that has a crypto exchanger built in using Strapi. Here is a link to the Svelte project on Github
Anumadu is a fullstack engineer, but also a technical writer specialized in Laravel, Vue.js, Nuxt.js and Node.js.