BlockVigil Developer Updates — Kicking off 2020 with Websocket integrations for Ethereum

Anomit Ghosh
BlockVigil
Published in
6 min readFeb 20, 2020

As part of our vision to enable any developer to begin building on blockchain, we have been organizing meetups and developer jams that focus on building out use-cases. The intent so far is to

  • Minimize expenditure of time and effort in learning complexities of the underlying protocol (Ethereum, in this case)
  • Avoid the cognitive bias of feeling accomplished without developing a RealWorld™️ app running on blockchain (toy projects do not run the world)
  • Maximize integration with fullstack development paradigms to help your team build the next generation of applications on blockchain. Just talk to the API gateway and consume blockchain as yet another web service.

Our next developer meetup is due on February 29, 2020 in Bangalore 🇮🇳

It will pick up where we left off from the last workshop and work on extending the functionality of the TODO app.

Details, agenda and RSVP here!

February 08, 2020

We held a coding meetup with an agenda to build a CRUD application on top of the Ethereum blockchain. And what better app to demonstrate this than the famous(or infamous?) TODO app.

The end result of the coding effort can be found on Github. Let’s have a quick review of the codebase.

The smart contract

We are using a smart contract as the intermediary that will store TODO notes as well as hold creation and updation logic “on-chain”. Let us take a look at the specific functions that we were able to cover at the meetup to integrate with a frontend.

➡️ Find the file in the srcdirectory ‒ TODOContract.sol

struct TodoItem {
uint256 id; // internal identifier
string note;
bool status;
}

mapping(uint256 => TodoItem) private items;

➡️ Each TODO entry is mapped against an index value (an unsigned integer) as an object of the structure type TodoItem

function addTodo(string memory item) public

➡️ Calling this stores a new TODO entry in the mapping introduced above

function getAllTodo() public view

➡️ Returns all the TODO entries stored

function removeTodo(uint256 itemId)

➡️ Removes a TODO entry as specified by the index value used to access the mapping.

The interaction with these functions happen via the EthVigil API gateway. Deploy the contract from the EthVigil Web UI or CLI and keep the contract address handy.

The frontend

The frontend is built on Sapper, a Javascript application framework powered by SvelteJS. We decided to go with Svelte to build a dynamic reactive since the components are relatively straightforward to code compared to React or Vue, saving us valuable time coordinating among the participants.

To quote from their article,

Traditional frameworks allow you to write declarative state-driven code, but there’s a penalty: the browser must do extra work to convert those declarative structures into DOM operations, using techniques like that eat into your frame budget and tax the garbage collector.Instead, Svelte runs at build time, converting your components into highly efficient imperative code that surgically updates the DOM. As a result, you’re able to write ambitious applications with excellent performance characteristics.

The credit for the HTML and CSS design goes to https://freshman.tech/todo-list/

The following snippets are from src/routes/todo.svelte

***Loading all TODO entries***

The logic to load all the existing entries lies in calling getAllTodos()inside

onMount(async () => {
initWS();
getAllTodos();
});

Which basically says, every time the todo.sveltecomponent is mounted, load the entries from the smart contract.

What’s going on inside getAllTodos()?

We are calling the getAllTodo()function on the contract by making an HTTP POST request to the API gateway.

const contractResourcePath = evAPIPrefix + '/contract/' + contractAddress + '/getAllTodo';
try {
const response = await axios.get(contractResourcePath);

evAPIPrefixis defined in rollup.config.jsand defaults to https://beta-api.ethvigil.com/v0.1

All deployed contracts on EthVigil and their functions can be accessed as resources with this prefix. You can notice the same within the Swagger UI generated on our web tool.

***Adding a new TODO entry***

<input type=”text” aria-label=”Enter a new todo item” placeholder=”E.g. Build a web app” class=”js-todo-input” bind:value={todoText}>

The input box is where you type out the TODO entry to be created. It automatically updates a variable with the value of your typed out text thanks to this declaration bind:value={todoText}

It is contained within a form

<form class="js-form" on:submit={addTodo}>

and pressing enter in the input box triggers the submit event handler, which is the addTodo()function.

try {
const txhash = await postTodo(todoText);
pendingTx = txhash;
}

postTodo() calls the contract API endpoint {evAPIPrefix}/contract/contractAddress/addTodowith an HTTP POST request.

const response = await axios.post(contractResourcePath, 
{
'item': note
},
{
headers: {
"X-API-KEY": API_KEY
}
}
);

The data parameter item passed corresponds to the expected string parameter in the solidity function:

function addTodo(string memory item) public

Also observe us passing the API key associated with the EthVigil developer account in the HTTP header X-API-KEY:

{
headers: {
"X-API-KEY": API_KEY
}
}

***UI update with Websocket integrations with EthVigil***

Once you add a new TODO entry on the smart contract, the transaction needs to be “confirmed” and become a part of a block on the blockchain network.

This is an asynchronous activity, and blockchain protocol clients do not take responsibility for informing your application about the status of the transaction.

Do read about the ethereum transaction lifecycle posted by Samikshan.

This is where we make your life easier.

Every time you post a TODO entry, we are returned a transaction hash for that activity by the API gateway. We store that so that we can refer to it later when a websocket payload comes in from the API gateway.

const txhash = await postTodo(todoText);pendingTx = txhash;

The relevant parts of communicating with the websocket service offered by EthVigil can be found in common.js

  • initWS() ‒ initializes the websocket connection and maintains the session ID returned
  • heartbeat() — called periodically as a “keep alive” mechanism

We do the work of maintaining the state of delivered updates to you, thanks to the session ID. In case the connection drops or goes unresponsive for a while, when you reconnect with the session ID, you will get the missed updates.

Every time a new payload comes in, we ‘set’ a Svelte store wsTxStoreto hold the JSON payload.

Returning to todo.svelte, every time the store wsTxStore is updated, we check whether the incoming payload corresponds to the transaction that was submitted to add a new entry.

Subsequently, we update the array todoItemswhich triggers a reactive UI update.

const unsubscribeWSTxStore = wsTxStore.subscribe( value => {
if (value && value.type === 'event') {
console.log('Web socket update received', value);
let eventName = value.event_name;
console.log(eventName);
switch(eventName){
case 'TodoItemAdded':
console.log('New item added');
const newItem = {
'id': value.event_data.itemId,
'text': value.event_data.note,
'checked': false
}
todoItems = [...todoItems, newItem];
if (value.txHash == pendingTx) {
pendingTx = null;
}
break;

}
}

The reactive update is powered by Svelte, as noted earlier, and the relevant section looks like the following:

{#each todoItems as item}
<li class="todo-item" data-key="{item.id}" on:click={handleListClick}>
<input id="{item.id}" type="checkbox" />
<label for="{item.id}" class='tick js-tick'></label>
<span>{item.text}</span>
<button class="delete-todo js-delete-todo">
<svg><use href="#delete-icon"></use></svg>
</button>
</li>
{/each}

It iterates over the array and as the array object changes, the list is rendered again.

Voila! The power of real time websocket integrations for blockchain applications.

There are more such meetups lined up in the city of Bangalore 🇮🇳 and we would love to see you take part in one. The use cases will progressively get more RealWorldy™️

If you wish to get started right away, go ahead and sign up on our platform at https://beta.ethvigil.com

Feel free to go through our tutorials as well as docs at https://ethvigil.com/docs

Join our discord chat room if you wish to have your queries answered right away, or just have a discussion with our devs

If you are willing to discover what happens under the hood of the Ethereum blockchain, we have a live-loading, interactive tutorial that will help you on the journey. Do check it out at https://tutorials.ethvigil.com.

Feedback/criticism/appreciation? We would be happy to hear from you!

Email us hello [at] blockvigil[dot]com

--

--