Connecting AlphaDEX to your Svelte app.

Fred Liebenberg
AlphaDEX XRD

--

This is a quick tutorial on how to connect your Svelte app to the AlphaDEX decentralized exchange platform on Radix DLT. You can find more AlphaDEX related tutorials like this here.

This tutorial assumes you have a basic knowledge of how Svelte apps work. If you don’t, then you can learn more about Svelte at svelte.dev.

You will need Node.js installed on your machine to follow this tutorial. If you do not have it installed yet, you can follow the instructions to do so on their website nodejs.org.

Note about using Svelte-Kit vs standard Svelte

This tutorial was specifically done with Svelte-Kit (kit.svelte.dev) rather than standard Svelte. I chose to use Svelte-Kit as it seemed to have a few more nuances that needed to be addressed to use the AlphaDEX SDK. I will specifically make mention of these during the tutorial. The tutorial should be very easy to follow in standard Svelte with the only difference being the main working file changing from +page.svelte in the src/routes folder to App.svelte in the src folder.

Set up a new Svelte app

If you have an existing Svelte app already, you can jump straight to the “Install AlphaDEX SDK” step.

Create a new app

The fastest way to create a new Svelte app is to use the Node Package Manager (NPM). To use it, move to the folder in which you want to create your new app and run the following command:

npm create svelte@latest hello-alphadex-svelte

You will be prompted with a few questions about the type of svelte app that you want to create. For the purposes of this tutorial I selected:

  • Library project
  • Add type checking with TypeScript
  • Add ESLint for code linting, Add Prettier for code formatting

Although you are free to select other options, it will be easiest to follow along with this tutorial if you make the same selections for your project.

Once you have made your selections a new Svelte app will be created in a new folder called hello-alphadex-svelte which contains all the files needed for a new Svelte app.

Run your new app

Move to the newly created app directory with this command:

cd hello-alphadex-svelte

Install all the necessary dependencies for the app using NPM again with the following command:

npm install

This will take a couple of seconds to run and download the necessary files for your app.

Once the installation is done, you can now run your new app with this command:

npm run dev

You now have a development server running for your new Svelte app. To see the output of your app, you can enter the address shown in the message in your browser address bar. It should be something like http://localhost:5173/. Once you have entered the address in your browser, you should see a message welcoming you to your new project.

Clean up the app

For this tutorial, we want a clean slate to work with, so open the +page.svelte file in the src/routes folder and change it to look like this:

<h1>Hello AlphaDEX</h1>

Save the file with your changes and the browser window will automatically be updated to only show “Hello AlphaDEX” on a blank screen. Not the prettiest screen, but we now have a blank slate to show you how to connect your app to AlphaDEX.

Install AlphaDEX SDK

Before we can connect to AlphaDEX, we need to install the SDK in our project. To do this, make sure you are in your project directory and run the command:

npm install alphadex-sdk-js

This will install the AlphaDEX SDK files in your project’s node_modulesdirectory, ready to be used in your project.

Import the AlphaDEX SDK

OK, we are ready to connect our app with AlphaDEX (finally!).

In order to use the functionality in the SDK, you need to import the required functionality into your app. You can do this in two ways:

Method 1 (Import functionality as needed)

This method does not work with Svelte-Kit

With this method you only import the functions and variables that you will need for a specific task e.g. if we only want to import the init function and clientState variable, we will do it like this:

import {init, clientState} from "alphadex-sdk-js"

Now you can access the imported functions/variables directly using their name. E.g. I can call the init function and access the clientState variable like this in my code:

init();
const myOwnVariable = clientState;

Method 2 (Import all functionality at once)

With this method you import all the SDK functions, variables and types at once into a reference variable like this: (I called the reference variable adex below, but you can call it anything you like.)

import * as adex from "alphadex-sdk-js"

Using this method you use the reference variable to get access to the SDK functions, variables and types. E.g. to call the init function and access the clientState variable in your code, you would do it like this:

adex.init();
const myOwnVariable = adex.clientState;

Only Method 2 works when using Svelte-Kit

It seems only Method 2 works with Svelte-Kit so we will use this method for the rest of the tutorial. For standard Svelte, both methods work equally well.

Import the SDK into your app

To import all the SDK functions, variables and types at once into a reference variable add these lines at the top of your +page.svelte file.

<script lang="ts">
import * as adex from "alphadex-sdk-js"
</script>

Initialize the SDK

In order to connect to the AlphaDEX exchange (we are actually connecting to an AlphaDEX API/Websocket server), we need to run the init function of the SDK once somewhere near the start of our application.

In our example we are going to run the init function in our +page.sveltefile as this is the first component in our app. Add the following line below your import statement in your +page.svelte file:

adex.init();

If you save the changes, you application will attempt to connect to the AlphaDEX exchange. You wont see any changes on the screen yet, but if you want you can go into the “Developer Tools” section of your browser, you should see a message like below on the Console:

Websocket connection 1 established with AlphaDEX server ws://ws.alphadex.net

This confirms that you are now connected to AlphaDEX.

We have a problem!

The problem described below will only happen if you are using Svelte-Kit. If you are using standard Svelte, you can skip to the “Display AlphaDEX information” section.

You might have run into problems when you tried to initialize the AlphaDEX SDK in the step above (if you did not, just try to refresh your browser). You should see the error below on your console:

ReferenceError: WebSocket is not defined.

The reason for this error is that Svelte-Kit automatically tries to do server side rendering of your app pages and currently the AlphaDEX SDK is not suitable for running on the server. Don’t worry if you don’t know what this means, here is how you fix it.

Switch off server side rendering for your app.

Create a new file in the src/routes folder called +layout.server.js and add the following content in the file:

export const ssr = false; // switch off server side rendering

Save the file and run the following command in your console again:

npm run dev

Refresh your browser and you should see the very welcoming “Hello AlphaDEX” message again.

There might very well be better ways to solve this, so please let me know in the comments if you know how.

Display AlphaDEX information

Now that you are connected to AlphaDEX, you can access all the different variables made available by the SDK in your app.

Displaying SDK Status

We can very easily show the status of the SDK using the clientState.status variable. To add this to our app, add the following line directly below the init(); line in your +page.svelte file:

let sdkStatus = adex.clientState.status

And to display the status, add the following line underneath the “Hello Alphadex” heading in the same file:

<p>SDK Status: {sdkStatus}</p>

You should see the current SDK status displayed on your screen.

We have another problem

If you refresh you browser screen, you should see the status showing as “LOADING”. This is indeed the initial status of the SDK when it first tries to establish a connection with AlphaDEX, but it should change very quickly to “READY” to indicate that it has successfully established a connection. But we are not seeing it change to “READY”…yet.

What is happening is that although the SDK has made a connection to AlphaDEX and the clientState.status variable has changed to “READY”, Svelte does not know that the variable has changed and therefore does not know that it should update its display to show the new value.

One way to test this is to add a button that we can press that explicitly tells Svelte to update the display for a new value. Lets do it quickly by adding the following lines to the +page.svelte file:

...
let sdkStatus = adex.clientState.status;
//start of new lines to add
function showStatus() {
sdkStatus = adex.clientState.status;
}
// end of new lines to add
...
<p>SDK Status: {sdkStatus}</p>
//start of new lines to add
<button on:click={showStatus}>
Click to show current status
</button>
// end of new lines to add

What the code above does is it adds a button that calls the showStatus function. The showStatus function simply re-assigns the clientstate.status value to sdkStatus and when this happens, Svelte knows that it needs to update the display because a displayed variable sdkStatus has been changed.

If you save this, you should now see a button that you can press to update the status shown on the screen to its current value. If you reload the browser screen, the status should initially show “LOADING”. When you press the button, it should update the display and show status as “READY”.

Although it might feel awkward, this is just a way we use to get around Svelte’s way of deciding when to refresh the screen when variables change. It is not very practical to press a button every time we want the latest data though, so lets explore a better way to deal with this problem.

How to always display the latest data

To get around problems like this, the AlphaDEX SDK offers an observable version of each variable indicated by a $ at the end of the variable name. E.g. the observable version of the status variable we have been using would be called status$.

I am not going to go into the detail of observables in this tutorial, but all you need to understand is that an observable variable allows you to subscribe to it so that you can receive a notification (and new value) every time it changes.

Lets implement it in our app and you will understand.

Add the following code to your +page.svelte file:

...
let sdkStatus = adex.clientState.status;
// add the lines below
adex.clientState.status$.subscribe((newStatus) => {
sdkStatus = adex.clientState.status;
// for the same result we could also have used the
// newStatus value that we receive from the subscription
// sdkStatus = newStatus;
})
...

Lets quickly review what the new code does. We call the subscribe function of the status$ observable variable (all observables have this function) and pass as our only argument a function that should be called every time the status$ observable emits a new value.

The function we pass as an argument will take the value emitted by the status$ observable as an input which I called newStatus, but you could call it anything. The only thing this function does is assign the current value of the clientState.status variable to the sdkStatus variable.

Notice that what we are doing in the function is exactly what we do when the button gets pressed.

So now, the sdkStatus variable will get updated every time the status$ observable emits a new value and Svelte will know that it needs to update the display.

Save your changes and see what happens in the browser. Refresh the page a couple of times and you should briefly notice the status showing “LOADING” before changing to “READY”.

The same principle applies to any of the other variables provided by the SDK. All the variables have an observable version available that you can subscribe to to make sure you always display the latest value of that variable in your app.

Using Svelte stores to store the SDK variables

Another popular way to make variables available across multiple components in Svelte is to use stores. In fact, store variables also work on the principle of sending a notification to their subscribers whenever they are updated, so lets see how we could make our clientState variable available using a store.

First you need to create a new file called store.ts in the src/lib folder and enter the following code:

import { writable } from 'svelte/store';
import * as adex from 'alphadex-sdk-js';
adex.init();export const adexState = writable(adex.clientState, function start(set) {

// start function that runs with first subscription
const sub = adex.clientState.stateChanged$.subscribe(() => {
set(adex.clientState);
});
// stop function that runs when last subscription closes
return function stop() {
console.log('Stopping clientState sub...');
sub.unsubscribe();
};
});

I will not go into all the details of how stores work in Svelte, but lets quickly review what the code does:

  • we import all the AlphaDEX SDK variables and functions into a reference variable called adex like before
  • we call the init() function to make sure the SDK is initialized before creating our store variable. Note that we will remove the init() function from our +page.svelte file in the steps below.
  • we then export a store variable we called adexState.
  • we create our adexState store variable by calling the writable function and passing it two arguments:
  1. the initial value of the store variable — adexState.clientState
  2. a start function that gets called when the store variable gets its first subscriber
  • the start function itself takes a set (function) argument and returns a stop function. The stop function will be called when the last subscriber unsubscribes from the store variable.
  • within the start function we only do one thing, we subscribe to the SDK’sclientState.stateChanged$ observable. This observable emits a new value every time any of the variables in the clientState object changes. When this happens we use the set function that was passed as an argument to set the value of our store variable to the latest clientState value.
  • within the stop function we also do only one thing. We unsubscribe from the clientState.stateChanged$ observable to make sure we don’t create hanging subscriptions.

That is the complicated stuff done! If you did not exactly follow what we were doing, don’t worry. You can always learn more about Svelte stores later. For now, lets focus on how this makes your life easier in your components.

In your +page.svelte file, delete everything and enter the following code:

<script lang="ts">
import { adexState } from "../lib/store.js";
</script>
<h1>Hello AlphaDEX</h1>
<p>SDK Status: {$adexState.status}</p>

Our component code looks much simpler now.

  • In the <script> tags we simply import our store variable adexState.
  • We can then use our store variable anywhere by putting a $ in front of the variable name. The $ at the front is a special Svelte character that tells Svelte that this is a store variable. Svelte will automatically subscribe to such variables when your component is loaded and will automatically unsubscribe when the component is destroyed.

Save your files and make sure everything works as expected. You should again see the status changing when you refresh the page.

Showing more interesting information

Now that the hard work is done, you can let your creativity run free and display all kinds of live data from the AlphaDEX exchange.

Display all AlphaDEX pairs

Lets see if we can display the pairs that are available on the AlphaDEX exchange.

Add the following lines of code to your +page.sveltefile:

<p>SDK status: {$adexState.status}</p>
// new code to add start here
<h3>AlphaDEX Pairs</h3>
<ul>
{#each $adexState.pairsList as pair}
<li>
{pair.name}
</li>
{/each}
</ul>
// new code to add ends here

Save your file and you should now see a list of names of the pairs available on AlphaDEX.

Create a separate PairsList component

Lets rather move our list of pairs into its own component so we can re-use it in our app.

Delete the code you added to +page.svelte in the previous section to display the list of pairs and replace it with this line:

<PairsList/>

Add the import of the PairsList component (we will create it next) below the other imports in the +page.sveltefile:

import PairsList from "../components/PairsList.svelte";

Create a new folder called components in the src folder and create a new file called PairsList.svelte in this folder with the following code:

<script lang="ts">
import { adexState } from "../lib/store.js";
</script>
<ul>
{#each $adexState.pairsList as pair (pair.address)}
<li>
{pair.name}
</li>
{/each}
</ul>

Notice that we import the adexState store variable again here to use in our PairsList component.

Save your new PairsList.svelte file as well as the changes to your +page.svelte file and you should again see the list of pairs just like you did before, but now they are displayed in their own separate component.

Changing AlphaDEX variables

So far we have only been reading variables with AlphaDEX data, but the AlphaDEX SDK also have some variables that you can change that will affect the data that is available through the SDK (see a full list of these variables in the SDK documentation).

For example, the AlphaDEX SDK only keeps a fully updated order book and order history for one pair at a time (it will take way too much bandwidth and memory to keep this information for all pairs on AlphaDEX). This pair is specified by the currentPairAddress field in the clientState object. If you change this field, the SDK will automatically update a number of other variables to reflect the newly selected pair. Lets incorporate this functionality in our app.

Update the PairsList component

First, lets update our PairsList component to enable the user to select a specific pair and set it as the current pair of the SDK.

Change your PairsList.svelte file to look like this:

<script lang="ts">
import { adexState } from "../lib/store.js";
import { clientState } from "alphadex-sdk-js";
  function selectPair(pairAddress) {
clientState.currentPairAddress = pairAddress;
}
</script><ul>
{#each $adexState.pairsList as pair (pair.address)}
<li>
<button on:click={selectPair(pair.address)}>
{pair.name}
</button>
</li>
{/each}
</ul>

Lets quickly run through the changes.

  • We added an import of the clientState object from the AlphaDEX SDK. We need to update the fields in this object when we want the SDK to fetch new information from the AlphaDEX exchange. We cannot use the store variable to change values in clientState.
  • We added a new function called selectPair to our component. This function takes a pairAddress parameter and then sets the clientState.currentPairAddress field to the new pair address. This will prompt the SDK to update all the other fields in the clientState object that are related to the currently selected pair.
  • We also changed our list of pairs to now consist of buttons that will call the selectPair function with the appropriate pair address when they are clicked.

Once you save your new PairsList.js file, you will notice the list now consist of buttons that you can click.

Add a PairInfo component

At the moment we can’t see any changes when we select a new pair, so lets add a component to show the details of the currently selected pair.

Create a file called PairInfo.svelte in your src/components folder and add the following lines of code to the file:

<script lang="ts">
import { adexState } from "../lib/store.js";
</script>
<h3>Information for currently selected pair</h3>
<p>Name: {$adexState.currentPairInfo.name}</p>
<p>Radix Address: {$adexState.currentPairInfo.address}</p>
<p>Last Price: {$adexState.currentPairInfo.lastPrice}</p>
<p>No of sell prices in orderbook: {$adexState.currentPairOrderbook.sells.length}</p>
<p>No of buy prices in orderbook: {$adexState.currentPairOrderbook.buys.length}</p>

This file adds no new functionality to what we have learned so far. It uses the AdexState store variable to access the AlphaDEX data and then displays a number of data points related to the currently selected pair.

Add the PairInfo component to your +page.svelte file by importing it and adding it as a component :

...
// add the following line below the other import statements
import PairInfo from "../components/PairInfo.svelte";
...
// add the following line below the <PairsList/> line
<PairInfo/>

Save the PairInfo.svelte and +page.svelte files and you should now see a display of the currently selected pair’s info on the screen. The info should change when you click on another pair in the list.

Can you build your own exchange?

Congratulations! You now know how to display live exchange information in a Svelte app. At the moment it might not look like the information is live as there is still very little activity on the AlphaDEX test instance, but rest assured that your application will automatically update every time there is a change on the AlphaDEX exchange.

We only touched on the very basics of what the AlphaDEX SDK allows you to do. If you want to find out more about what information is available through the SDK, you can find its developer documentation here.

The only aspect we have not touched on is how to submit a transaction to the AlphaDEX on-ledger component, but we will leave that for another tutorial.

Can you build the best looking exchange front-end for the Radix network? We are keen to see what you come up with and remember, you can earn a fee for all orders that get placed through your app, so there is a real incentive to build you own exchange using the AlphaDEX SDK.

If you get stuck on this tutorial or have any further questions about AlphaDEX, give us a shout on our telegram channel.

--

--