GetCoding
  • Home
  • Courses
  • Contact
Category:

Featured

BlockchainFeaturedTechnologiesThought Provoking

Web3 RPC Nodes

by Matt Heff 1 year ago
written by Matt Heff

In this article we will look at Web3 RPC Nodes, Initially we shall explain remote procedure calls ( RPC ) in both web2 and web3. After this you will get a chance to interact with an RPC and dive into the internet of blockchains ( Cosmos ), The purpose of this is to help you understand the role of RPC Nodes in Web3 and highlight the caveat of centralised RPC infrastructure in decentralised network. Finally we will look at a hot new solution to this problem!

What is RPC?

Remote Procedure Calls are used in Client – Server systems, the behavioral flow is the client will send a request to the server and the server will respond with a result. During this exchange the client may specify a particular function or procedure and pass relevant parameters with it. 

Web 2 RPC’s

Let’s look at an example with two systems, Wordpress (CMS) and Moodle (LMS). We want to automatically enroll a customer in a Moodle course ( and create their account if it does not already exist ) after they purchase a course from Wordpress. In Moodle we configure the default provided RPC options or write some custom functionality if needed.  In wordpress we write or find a plugin for Moodle integration and then configure the Moodle Server RPC particulars. The systems can securely communicate via the security token generated in Moodle, and for specified functions such as userExists, createUsers, authUser. getUser courseList, enrollUser. 

RPC’s allow us to integrate with systems and easily read/change data within it for an intended purpose. It affords simpler integration with many systems through a system defined interface.

But what about Web3 RPC Nodes, you ask? Let’s get into that, if you are new to the space the term node is used instead of server.

Web 3 / Blockchain RPC Nodes 

RPC Nodes are our gateway to read from and interact with the blockchain through their exposed API interface. With the blockchain we cannot communicate directly with it as we can a database. These RPC Nodes are essential for our dApps and anything else want interact with the blockchain need to use these to interface with it. From the clients perspective they must submit our transaction with their wallet and this has a configured RPC Node, their transaction will be submitted through that access point. This action could be to transfer some tokens, interact with some smart contracts, trade, yield farm, stake or some other feature offered by a dApp. 

What if the RPC is offline?

If our configured RPC node is offline then our wallet should return some error and inform us, at this point a lot of people will be left scratching their head and unsure what to do. Perhaps they would just try again later. Searching for an RPC for your chosen blockchain may net you an alternative. Do you need to trust it?  Are all of them good actors?

If we have a dApp that we have built and it uses the RPC Nodes API for regular operations, you will be out of action unless you have incorporated a list of trusted backup RPC Nodes and the functionality to iterate through the list in the event of failure. The uptime and reliability of RPC Nodes are essential to the services provided and for the user experience.

How can we trust RPC?

This is one of the achilles heels of web3 at the moment, let’s say someone runs a RPC Node with the intention of theft. They download the source code and make some modifications to it. And convince users to configure this inside their wallets. Perhaps instead of processing a transaction they throw an error message and suggest a user go to their own phishing site where they have the user sign a transaction and drain their wallet. 

A similar event happened this year, a RPC Node became compromised and the attackers did this very ploy to phish users to their own website to deprive them of their assets.

Cosmos RPC Nodes & Tendermint

Cosmos is an Internet of blockchains as such there are a multitude of blockchain that exist and are interoperable. Tendermint allows for the integration of any blockchain into this ecosystem, it frees up application developers to be able to focus on their creations and not have to concern themselves with the gargantuan task of building a network or deciding on and implementing consensus methods. This modularity ( separation of application, network and consensus layer) is already the reason this network is growing at a breakneck speed. As more and more chains decide to take advantage of the Cosmos architecture and interoperability there becomes a large target placed upon these RPC Nodes for attacks, if this infrastructure exists on centralised services then there becomes a honeypot and compromises will have wide scale impacts.


Explore Cosmos via Tendermint RPC

Lets get our hands a little dirty!

If you are new to blockchain there is no better way to get familiar with it then getting your hands dirty. Take a look at the latest COSMOS block

View Latest Cosmos Block

If you prefer to look at this inside postman, below is a collection to get you started.

Tendermint RPC – SwaggerDownload

Now that you are interacting with data from the blockchain save the link below to explore more!

Tendermint RPC – Full API Description


Critical Infrastructure –  Should it be decentralized?

When we have billions of dollars and services that hundreds of millions use the underlying infrastructure, its reliability, security, transparency and motivations need to be considered. In the last two years their explosive growth has resulted in a lot of centralization of services which offer fast and quick results for developers and users ( a short term win! ), In the medium term this introduces risks and dilutes some of the founding principle cores. A core tenet of Web3 is decentralization, if that becomes diluted to the point where it barely exists at all levels then what is Web3? With that in mind can we trust centralized services to be the gatekeepers of a decentralized system?  

If you looked at the current cosmos block using the links or postman file above how do you know the data that is returned to you is accurate? What is stopping a centralised service from misrepresenting the chains state.

Will they restrict access arbitrarily upon government request?

Will they censor or curate information in ways that are not representative of the blockchains actual state?

Will they serve as a focal point for attacks to compromise networks and harm users?

If they go out of business will all the services built relying on them also disappear?

Many of us have been happy to forget about the value of decentralization especially when we are not encountering any of the downsides that come with centralisation. This is a core part of Web3 though not an immediately obvious one. When this matters it can be the difference of you having access to your assets or not. Being able to use the services built on blockchains or not.

It seems to me that now is the time to re-evaluate our relationship with how we interact with blockchains via RPC Nodes. As we move towards an interoperable ecosystem within cosmos. Centralized services create a single point of failure, that impact ripples to all chains which become part of the Cosmos ecosystem, such an expansive network which in time could include all chains. After all it is the internet of blockchains.

The solution – LAVA

In 2022 a visionary team was established to revolutionize the way we interact with blockchains. To ensure centralization and the points of failure they introduce do not go without challenge and are stopped before their corrosive impacts on decentralization become widespread, ingrained and exploited regularly.

It is my desire to be at the forefront of this mission, to help guide developers coming into the space in a way that promotes and spreads the core values of Web3, removes barriers of entry, resolve development issues and foster a community that will lead the whole industry into the next era. An era in which those who thrive will be decentralised and censorship resistant. It’s time to take the discussion beyond a network of value transfers, and bring it full circle to the values which established this entire space.  The future is hot, The future is liquid, The future is LAVA!

1 year ago 0 comment
TwitterLinkedin
BlogFeaturedJavaScriptNodeJSProgrammingTutorial

Create a RESTful API in NodeJS

by Matt Heff 1 year ago
written by Matt Heff

Ever wanted to create your very own API or do you just need some syntax for something that you are currently working on? Well we have you covered!

Tools you will need

  • Visual Code
  • Command line
  • Node / npm installed
  • Postman ( or some way to interact with the API)

Navigate to the directory you want to set up this project in

cd /home/heff/Code/NodeJS/ApiTutorial-Simple
npm init
npm install express cors
code .

Create Products.JSON

Create a file name products.json in the root directory and put the following JSON into it, this is a simple product database that we will read/update/create/delete ( get, put, post, delete ).

I have no intention of permanently altering this data, we will load it into the memory of the service and then modify it but after the service is terminated nothing will be retains. This is especially helpful once we start deleting.

[
  {
    "id": "Prod1",
    "name": "Online Product #1",
    "type": "online",
    "qty": null,
    "price": 10.5
  },
  {
    "id": "Prod2",
    "name": "Shipping Product #2",
    "type": "physical",
    "qty": 55,
    "price": 17.5,
    "shipping_price": 10
  },
  {
    "id": "Prod3",
    "name": "Online Course Product #3",
    "type": "physical",
    "qty": 55,
    "price": 17.5,
    "shipping_price": 10
  }
]

Create a Server.js file

Create a server.js file and this is the one we will be having node execute for us we will put together in sections and test along the way the sequence will be

  • Load the Products Data
  • Initialise the API Service
  • Create GET
    • Get All
    • Get by ID
  • PUT
  • POST
  • DELETE

ok now we are ready to GetCoding!

Load the Products Data

Run: node server.js

let products = require("./products.json");

console.log(products)

use the command node sever.jsAfter that you should see the products JSON object written to the console like in the image below

Great! Now lets make a service that will listen to us

Initialise the API Service

Add the following code to your server.js file what we are doing here is getting our service setup and configured so it will sit and listen for instruction i have included some CORS handling incase anyone tries to do test this via their browser console instead of postman

const express = require("express");
const cors = require("cors");
const app = express();

var corsOptions = {
  origin: "http://localhost:9999",
};

app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));


////////////////////////////////////////
//Insert GET/PUT/POST/DELETE functions in this section

//Get functions
app.get("/product", function (req, res) {
  res.json(products);
});

app.get("/product/:id", function (req, res) {
  let item = products.find((product) => product.id === req.params.id);
  res.json(item);
});

//put functions

// post functions

// delete functions

////////////////////////////////////////


var server = app.listen(9999, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log(`Simple API listening on host: ${host} with port: ${port} `);
});

if you run this now you will have a service start up and sit there listening on port 9999, how cool is that!

You can use postman now to perform a get on

  • http://localhost:9999/product
  • http://localhost:9999/product/Prod1

Postman gives the following results,

At this stage you now have a very basic API! If this is your first time congratulations! I hope you remember me!

Try out looking for Prod2 & Prod3 even a Prod4 that does not exist to see what happens.

PUT

Add the following code under the comment //PUT functions

Here we need to make sure the data send to us is not empty, from there we look for where our item is in the product list and once we find it ( assuming we do ) we will update it with the JSON sent, the whole record must be sent, sending only partial data will result in data missing.

app.put("/product/:id", function (req, res) {
  if (!req.body) {
    res.status(400).send({
      message: "Content can not be empty!",
    });
  }
  console.log(req.body);
  //find the product by id and update it 
  let index = products.findIndex((x) => x.id == req.params.id);
  products[index] = req.body;

  console.log(products);
  res.json(products);
});

POST

Add the following code under the comment //POST functions

Here we need to make sure the data send to us is not empty, from there we look for where our item is in the product list and if we don’t find it we create a new one otherwise let them know one already exists.

app.post("/product", function (req, res) {
  if (!req.body) {
    res.status(400).send({
      message: "Content can not be empty!",
    });
  }
  // check to see if there is a product that exists with that id
  let index = products.findIndex((x) => x.id == req.body.id);
  if (index !== -1) {
    res.status(400).send({
      message: `Item already exists wth the ID: ${req.body.id}`,
    });
  }
  //add new product to the list 
  products.push(req.body);
  res.json(products);
});

DELETE

Add the following code under the comment //DELETE functions

The code below looks for a matching product with the value that was passed to it and if it finds one it will remove it from the product list.

app.delete("/product/:id", function (req, res) {
  //here we remove the product from our list if it is found
  let tmp = products.filter((item) => item.id !== req.params.id);
  products = tmp;
  console.log(products);
  res.send(products);
});

GITHUB

You can find the code for this in github as well as a collection from postman so you can test out the API

GitHub Repo

NodeJS.postman_collectionDownload
1 year ago 0 comment
TwitterLinkedin
BlockchainBlogFeaturedTutorial

Writing your first Ethereum Smart Contract

by Matt Heff 1 year ago
written by Matt Heff

We are going to go through the steps of creating your very first smart contract on the Ethereum blockchain. We will be using a testnet so you wont need to fork over any money to deploy the contact. Solidity, blockchain and smart contracts can at first seem overwhelming with all the new words and jargon around creating these new services on a decentralised chain ( a public database ).

There are a few things we are going to need first

Remix

Remix is the IDE we are going to use, setting up a decent development environment to work with blockchains and deploying smart contracts to local/test/mainnets requires way more effort that I want you to go through to get that sweet feeling of success with writing your first smart contract.

MetaMask

This is the wallet we will be using to push our contracts to the testnet. So if you are already a developer you likely are familiar with dev / test/ production systems. The same exists with in blockchain, with the testnets we can get free tokens from faucets which will allow us to perform transactions. if you use a dev chain on your local or Javascript VM within Remix then you wont need to get tokens from a faucet.

Important — Do not use your wallet with real funds to do any development work, have a separate browser profile for this.

Faucet

A faucet is where we can get tokens for free on a network, when we want to make transactions on a blockchain we need to pay GAS for it. The way I like to think about it is the cost of renting processing power from a global computer, a simple transaction of sending X amount of tokens to another wallet will have a low cost, Interacting with a smart contract that does lots of calculations, reading, writing can cost a significant amount more. Lucky for us we will be on a test net so cost will only be your time.

How to get ETH – Kovan tokens from a faucet

We have all that we need now.

Lets GetCoding!

Creating the Smart contract

When we first get into Remix you will notice there are a few folders and files already populated for us, Lets get rid of them 🙂

Before Files Removed
After files removed

Adding our Contract

Right click on the contracts folder and select new file, enter the filename SimpleContract.sol

This SimpleContract.sol file is what we will compile and deploy onto the blockchain! Get ready to level up your awesomeness!

First things we need to do are add a license and define what compiler version to use, with out either of these the compiler will complain.

// License in the line below is commented out, but is required. This type is the most appropriate for public works
// SPDX-License-Identifier: MIT

// 1. Pragma -- Compiler version
pragma solidity ^0.8.0;

Once you have this code in your SimpleContract.sol you can git CRTL+S and it will save & compile the contract. You will see a green tick on the side if this has worked.

Green tick visible on the left most column

Now it is time to get our smart contract to do something, What we are going to do is have a variable we can store a number that you will pass to it, you will also be update and retrieve it

// License in the line below is commented out, but is required. This type is the most appropriate for public works
// SPDX-License-Identifier: MIT

// 1. Pragma -- Compiler version
pragma solidity ^0.8.0;

contract SimpleContract{
    uint256 private simpleNumber ; // Declaration of our storage variable

    function setSimpleNumber(uint256 _simpleNumber) public {
        simpleNumber =_simpleNumber;
    }
    function getSimpleNumber() public view returns(uint256){
        return simpleNumber;
    }
}

The above is the complete code we will be working with here, we have our contract declaration, defining our storage variable and then get/set functions for it. Hit CRTL+S and compile the contract.

Deploying the contract

For us to compile our contract we will do the following steps

  1. Navigate to the Deploy and Run transaction item in the left most column ( the one at the bottom )
  2. Select our Environment ( Javascript VM London )
    • Initially we will do this on a local/dev network and after we have success there we will do this on a Ethereum testnet.
  3. Select the Contract SimpleContract to be deployoed
  4. Click Deploy
Arrows point to all the items of interest you need to deploy.

After you have clicked deploy you will see a item underneath the Deployed Contracts area, expand this and you will see two options one is for our setSimpleNumber function and the other is for the getSimpleNumber Function.

Click on getSimpleNumber ( the blue one ) and you will see a value of 0, this is the default value assigned.

Lets update this to a different number, enter 50 into the text box next to setSimpleStorage and then click the orange button. Once this has completed you can click the getSimpleNumber button and you will see the updated value

Congratulations !! your smart contract has worked!

you can stop here if you are satisfied with that. If you want to deploy this to an Ethereum Test net follow on below.

I’m Assuming you already have test net ETH in your wallet. If not go here and follow these instructions — TOCOME —

Set metamask to the Kovan Network , and then change the Environment in remix to Injected Web 3, you wll be prompted to connect your metamask to remix

Set Metamask to Kovan TestNet
Set Environment to Injected Web
Connect with Metamask

Ready to deploy to Ethereum Kovan Testnet

Click on Deploy, you will have meta mask popup OR flash a 1 on the extension icon to indicate you have a transaction to review & approve.

Approve the transaction and wait it to be processed on chain

Assuming everything went well you will see a newly deployed contract, as well as an information in the debug console indicating the transaction has completed

If you copy the transaction hash and navigate to kovans etherscan enter the transaction hash ( tx hash ) and you will see the transaction on the kovan testnet blockchain!

Repeat the steps before where you setSimpleNumber & getSimpleNumber, you will need to sign a transaction for setSimpleNumber as we are writing data to the smartcontract and altering the state of the chain. But to perform a getSimpleNumber you will not need to.

If you got to the end of this well done! You have learned a lot here and are on your path to learn smart contracts and block chain development! Tweet your success and take be @_Matt_Heff to let me know how you went.

1 year ago 1 comment
TwitterLinkedin

Recent Posts

  • How to read environment variables with Node.js
  • AI – What is Natural Language Processing (NLP)
  • Web3 RPC Nodes
  • Drupal 9 – Custom module development – Simple Module
  • Create a RESTful API in NodeJS

About

About

GetCoding is a blog and tech educational resource specialized in programming, Web3, blockchain and everything in between. Follow us to help you understand and GetCoding!

Stay Connect

Twitter Linkedin Youtube Email

Popular Posts

  • 1

    Writing your first Ethereum Smart Contract

    1 year ago
  • 2

    Create your own JSON.stringify() function

    1 year ago
  • 3

    Install Metamask and get Testnet Tokens

    1 year ago
  • 4

    Introduction to JSON with Examples

    1 year ago
  • 5

    What is an AMM ( Automated Market Maker)

    1 year ago

Categories

  • Blockchain (4)
  • Blog (7)
  • Featured (3)
  • Learning (1)
  • Programming (5)
    • JavaScript (3)
    • NodeJS (1)
    • PHP (1)
  • Technologies (2)
    • Drupal (1)
  • Thought Provoking (1)
  • Tutorial (6)
  • Uncategorized (3)

Recent Posts

  • How to read environment variables with Node.js

    6 months ago
  • AI – What is Natural Language Processing (NLP)

    10 months ago
  • Web3 RPC Nodes

    1 year ago

Featured Posts

  • How to read environment variables with Node.js

    6 months ago
  • AI – What is Natural Language Processing (NLP)

    10 months ago
  • Web3 RPC Nodes

    1 year ago

Subscribe Newsletter

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

  • Twitter
  • Linkedin
  • Youtube
  • Email
GetCoding
  • Home
  • Courses
  • Contact