paint-brush
How to integrate Scatter with your EOS Front Endby@shankqr
3,019 reads
3,019 reads

How to integrate Scatter with your EOS Front End

by Shankar NathanDecember 31st, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

We are going to build a simple Front End that will use Scatter for logging in and authorising actions on the EOS blockchain

Companies Mentioned

Mention Thumbnail
Mention Thumbnail

Coins Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - How to integrate Scatter with your EOS Front End
Shankar Nathan HackerNoon profile picture

We are going to build a simple Front End that will use Scatter for logging in and authorising actions on the EOS blockchain

Once upon a time, the only wallet I knew was the one that carries my lunch money. Today there are numerous wallets out there, but instead of keeping your money they keep your private keys. Now among all the wallets out there I have chosen to work with Scatter due to it’s popularity among the EOS community. Most of the EOS Dapps being built these days, almost all of them supports Scatter. Scatter has also become increasingly popular among Ethereum and Tron, making it a solid investment for your future Dapp development.

Setting up Scatter

Scatter used to come in the form of a Chrome plugin, but now it has officially dropped that in favour of a full native app. If you have not installed Scatter, the first step you need to do is download it from its GitHub page here.

For the purpose of this guide we are going to import our EOS account we created on the CryptoKylin testnet the other day into our Scatter wallet. If you have no idea on how to create a testnet account, I have already written about it on my first guide under the EOS Account section, click here.

Now once you have your testnet account name and private key, fire up Scatter. On your first run it will ask you to create a password. You will need this password to unlock your wallet when ever you want to use it again at a later time.

Since we are planing to import an EOS testnet account, we must add the testnet details to Scatter first. The way to do this is to go to the Settings -> Networks. You will find the Settings button (shape of a gear icon) on the top right corner. Once again you need to key in your password.

CryptoKylin Testnet details

Under the “Your Networks” tab, click on the Add button. Key-in the details according to the screenshot above. At the time of this writing these inputs are still valid, however to confirm that you have the latest inputs you should always ask in their telegram group here.

Import Keys

Ok now go back to the main interface of Scatter. Click on the “Add Keys” button on the bottom left corner.

Add Keys menu

You will see 3 options, click on the “Import Key” button.

Import Key menu

Another 3 options will be shown, click on the first button “Text” since we have our private key in the text format. Go ahead and paste your testnet private key. Since every account you create on the testnet comes with an Owner and Active key, for simplicity sake you can just import your Active key.

Linked Accounts

Since we have already added the CryptoKylin details under the networks settings, Scatter automatically links your private key to your account name on the CryptoKylin testnet. You can view this under the Linked Accounts tab. Optionally you can give a nicer name for this key under the “Key Name” text box above. I am going to name it youraccname1@active.

At this point, we have completed all the setup necessary for Scatter to work with our Front End. Here is a summary of the main tasks we have accomplished so far:

  1. Created a testnet account
  2. Added the testnet details to Scatter
  3. Imported our testnet private key to Scatter

In the next section we will develop the Front End so it will talk with Scatter nicely. You will want to keep Scatter app running in the background so that our Front End detects it.

Front End

In my previous guide, I have written about building a simple Front End for EOS. It was a simple Dapp that is able to login the user with their account name and private key. To make this Dapp more practical, we are going to modify it so that it can work with Scatter.

When ever an action needs to be performed on the blockchain; for example logging in, with Scatter the user does not need to key in their private key every time. On the front-end side we do not need to cache their private key anymore, as this could cause vulnerability issues.

By using Scatter, this is how it is going to work from now on: every time we need to perform an action, we invoke Scatter from it’s javascript API. Scatter will then request the user for their permission on which key to use to perform the action. After the user has authorised then Scatter will return us a signature object that we can use to sign the transaction on the blockchain. Super simple, clean and more secure!

I have modified our previous front-end to now work with Scatter. Let’s get started by cloning my latest Github project and I will walk you through the main changes. Open terminal and type this:

$ git clone https://github.com/shankqr/eos-scatter.git

Once all the files have been cloned to your local machine. Get into the project directory and install all the dependencies


$ cd eos-scatter$ npm install

To avoid any babel/webpack issues with our Vue project, type this:

npm i -D @babel/runtime

VUEX

The first thing we are going to do is store the status of our login with VUEX. VUEX is quite similar to Redux as it is both inspired by FLUX, accept it’s more suited for Vue. I find overall using VUEX more simpler than Redux, however both these state management framework are equally good in my opinion.



//store.jsimport Vue from 'vue';import Vuex from 'vuex';

Vue.use(Vuex);














export default new Vuex.Store({state: {loggedIn: false},mutations: {loginStatus(state, status) {state.loggedIn = status;}},getters: {loggedIn: state => state.loggedIn},actions: {}});

Here I created a state called loggedIn and set it to false, then I created a mutation called loginStatus that just changes the value for loggedIn. Lastly I added a getter so we can retrieve the value of our loggedIn state.

Ok let’s see how we are going to access this newly created state on the UI part. I have modified the AppTopBar.vue component to include a Logout button.

<!-- AppTopBar.vue -->










<template><span><v-toolbar app color="black darken-4" dark><v-spacer class="hidden-md-and-up"></v-spacer><v-toolbar-title>{{appTitle}}</v-toolbar-title><v-spacer></v-spacer><v-btn @click="handleLogout()" v-if="$store.state.loggedIn">Logout</v-btn></v-toolbar></span></template>
















<script>export default {name: 'AppTopBar',data() {return {appTitle: 'My EOS Dapp'};},methods: {handleLogout: async function() {this.$store.commit('loginStatus', false);this.$router.push('/');}}};</script>


<style scoped></style>

The logout button has been wired to the handleLogout method and it calls the $store mutation named loginStatus. This action will set our loggedIn state to false. Pretty simple logic here. Now let’s go through the most important part which is the API calls to work with Scatter.

Scatter API

From early on I have stored all EOS related methods in a class called EosService. We are going to extend this class so that it is able to talk with Scatter.




//EosService.jsimport { Api, JsonRpc } from 'eosjs';import ScatterJS from 'scatterjs-core';import ScatterEOS from 'scatterjs-plugin-eosjs2';








const endpoint = 'https://api.kylin.alohaeos.com:443'; // kylinconst network = {blockchain: 'eos',protocol: 'https',host: 'api.kylin.alohaeos.com',port: 443,chainId: '5fff1dae8dc8e2fc4d5b23b2c7665c97f9e9d8edf2b6485a86ba311c25639191'};








class EosService {constructor(dappName, contractAccount) {this.dappName = dappName;this.contractAccount = contractAccount;ScatterJS.plugins(new ScatterEOS());this.rpc = new JsonRpc(endpoint);window.ScatterJS = null;}





connect = async () => {await ScatterJS.scatter.connect(this.dappName).then(connected => {if (!connected) return console.log('Failed to connect with Scatter!');this.scatter = ScatterJS.scatter;});





await this.scatter.getIdentity({ accounts: [network] }).then(() => {this.account = this.scatter.identity.accounts.find(e => e.blockchain === 'eos');});

if (this.account === null) return false;


return true;};


transaction = async (action, data) => {this.api = this.scatter.eos(network, Api, { rpc: this.rpc });



























const resultWithConfig = await this.api.transact({actions: [{account: this.contractAccount,name: action,authorization: [{actor: this.account.name,permission: this.account.authority}],data: {...data}}]},{blocksBehind: 3,expireSeconds: 30});console.log(resultWithConfig);return true;};}

export default EosService;

To work with Scatter, we first need to import 2 libraries: ScatterJS and ScatterEOS. We then specify the constants to store the endpoint and network details, in our case we will be using the testnet details. We will be only needing to main methods here, which is the connect and transaction.

Scatter: connect method

In the connect method we simply try to link a Scatter account with our Dapp. Scatter will then prompt the user to select an account they would like to use with our Dapp.

Scatter: transaction method

In the transaction method, we are invoking an action on the EOS smart contract. What Scatter will do in this case is to prompt the user with a dialog to allow or deny this action.

Wrapping Up

For the final section of this guide let’s have a look at the Login page where we use our EosService.

<!-- Login.vue -->























<template><v-container><v-layout row class="text-xs-center"><v-flex xs3 style="background-image: url('http://cdn.wallpapersafari.com/7/86/gqiGH7.jpg')"><v-card height="500px"></v-card></v-flex><v-flex xs4 class="grey lighten-4"><v-container style="position: relative;top: 13%;" class="text-xs-center"><v-card flat><v-card-title primary-title><h4>Login</h4></v-card-title><v-form><v-card-actions><v-btn @click="handleLogin()" primary large block>Login</v-btn></v-card-actions></v-form></v-card></v-container></v-flex></v-layout></v-container></template>


<script>import EosService from '@/eosio/EosService';
















export default {data() {return {accountName: '',privateKey: '',eosio: null};},methods: {handleLogin: async function() {if (this.eosio === null) {this.eosio = new EosService(process.env.VUE_APP_DAPP_NAME,process.env.VUE_APP_SMART_CONTRACT_NAME);}


if (!(await this.eosio.connect()))return console.log('Failed to get Scatter account');










if (await this.eosio.transaction('login', { user: this.eosio.account.name })) {this.$store.commit('loginStatus', true);this.$router.push('home');}}}};</script>

Here we simply import our EosService, initialise our class and pass in the parameters into the class constructor. We then call the connect() method and the transaction() method passing in the name of the action we want to call on the smart contract and it’s input data. If it’s successful the method will return true and we change our loginStatus state to true and route the user to our main page.

Dapp main page, console prints out the transaction details

If you open the chrome developer tools you should be able to see the transaction details printed out on the console.

Congratulations! we have successfully integrated Scatter to your Dapp. We have reached the end of this guide, but I would love to hear what you guys are working on. If you need help don’t be afraid to reach me.