GetCoding
  • Home
  • Courses
  • Contact
Category:

Blockchain

BlockchainFeaturedTechnologiesThought Provoking

Web3 RPC Nodes

by Matt Heff 10 months 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!

10 months ago 0 comment
TwitterLinkedin
BlockchainBlog

What is an AMM ( Automated Market Maker)

by Matt Heff 11 months ago
written by Matt Heff

With the explosion of DEFI onto the world its time to pull it apart and make sense of what it is and what it offers us now that yet another crypto Djinn is out of the bottle.

Summary

Automated market makers (AMMs) are a major part of the decentralised finance ( DeFi ) ecosystem. These forms of magic allow crypto currencies and other digital assets to be traded in a permissionless and automated way. They use pools of liquidity rather than requiring a seller and buyer in a market place. The prices are worked out via math. Liquidity can be provided by any one and incentives are offered for doing so, keep in mind they are not risk free.

Topics covered

  • What is an AMM
  • How do they work?
  • Liquidity Providers and Liquidity Pools
  • Slippage
  • The Math!

What is an AMM

Automated Market Makers ( AMM ) allow crypto currencies/digital assets to be traded in a permissionless way and automatically using liquidity pools, these differ to traditional markets because both buyers and sellers are not needed, in these markets the buyer and seller agree upon a price and then the transation takes place. With AMM’s transactions can take place at anytime so long as the buyer is happy with the rate that is currently available.

Decentralised Exchanges that us AMM’s

With Decentralised Exchanges ( DEX ), there is not 3rd party that mediates the exchahge. With AMM’s the algorithm will utilise the liquidity form that which is provided to settle the transaction at the current rate. The algorithms can vary between dex’s but the intention is to have deep liquidity, cheap to use and be available all the time.


Liquidity Providers and Liquidity Pools ( Yeild farming )

Liquidity relates to how easy it is to buy/sell or convert an asset. A house is not very liquid as it takes a long time to sell it and for the asset to be transferred. Cash is liquid, you can take it and convert it to many assets / goods or services and requires little time to settle the transaction. As Decentralised Finance started out it was difficult to find people on the network to trade crypto currencies with, so there was a liquidity problem. Finding a person that wanted to trade the same crypto currencies and also the same amount was a task in itself, AMM’s fix this but creating liquidity pools of assets, the users who provide liquidity are offered rewards and incentives for doing so, the greater the amount of assets in the pool the deeper the liquidity and the easier it is to trade on DEX’s

With traditional exchanges users buy and sell with other users, these AMM’s allow users to trade against the pool of tokens. the pools usually consists of two tokens eg BTC and USDC and this is used for people wanting to trade BTC for USDC or USDC for BTC. The price is worked out by a formula and these forumulas can be different between different DEX even between different pools on a single DEX.

When a users alters the amount of tokens in the pool the ratio changes and as result the price does.

Anyone who has tokens ( usually ERC-20) is able to provide liquidity and earn for doing some, incentives come in the form of trading fees ( typically 0.1% per trade ) and bonus rewards usually in the dex’s native tokens or some other offering to entice people to provide liquidity. this is known as Yield farming

Slippage

When going to use a DEX and trade one token for another depending on how deep the liquidity is and the size of the trade you will encounter slippage, this is the deviation of the current price to the price you will pay per token. This is a result of you moving the market and if the slippage quite is high your trade will be large relative to the pools liquidity.

A simple example here is lets say you want to swap USDC for USDT, both are USD Stable coins so equal to $1. If we swap 100 USDC and have a slippage of 5% then we can expect to get 95 USDT. So 1 USDC will trade for 0.95 USDT.

If that same pool had a lot more liquidity then we may get a slippage of 0.1% (basically just the AMM trading fee ) and in that case 100 USDC would get is 99.99 USDT.

Constant Price Formula

The elegance of math and what allowed this bit of technology to be unleashed is the following simple fomula:

Constant product formula

x * y = k

Here X represents the amount of AssetX in the pool and Y represents AssetY whilst K is a constant. If someone buys AssetY and sells AssetX for it then the relative price of AssetY to AssetX will change. We remove some AssetY and add some AssetX more X and less Y results in Y relative price increasing and X decreasing to equate the constant K.

I like to think about it as a see saw, as there are more X its price goes lower, less Y so it goes higher ( relative to each other). This creates arbitrage opportunities for traders and keeps the pools close to the values on exchanges.

There are a range of formula to equate values of tokens in pools.

Constant sum formula

x + y = k

Constant mean formula

 (x1 * x2 * … * xn)(1/n) = k

There are many more and each variation tries each tries to achieve an outcome, an edge for their users. Lower slippage, lower impermanent loss or even to increase slippage for very large orders that will unbalance the pool.

Conclusion

AMM’s have been wildly successful and are one of the bedrock technologies of decentralise finance. They are not risk free but they also off there average person to participate in financial market services and make yield when providing liquidity.

11 months ago 0 comment
TwitterLinkedin
BlockchainBlogTutorial

Install Metamask and get Testnet Tokens

by Matt Heff 12 months ago
written by Matt Heff

This article will cover

  • Installing the MetaMask Extension in your browser
  • Creating a wallet
  • Getting Testnet ETH tokens

What is Metamask

Metamask is arguably the most populate cryptocurrency wallet which allows you to store Ether and other ERC-20 tokens, it will also let you interact with decentralised applications ( dapps).

Installing Metamask

Navigate to the MetaMask Download page select your supported browser ( if you are using a different browser, then its best to get one of these to follow on with the rest it ). Allow the prompt to install the extension.

Once it is installed you will see a icon in your browser

Click on the icon, if MetaMask does not open up on its own.

When you see this page click on Get Started

At this point we need to create a New Wallet so click on “Create a Wallet”

Select “Create a Wallet”

If you want to help improve metamask you can agree to the request, or decline. It makes no difference with what we will be doing.

Next you get prompted to create a new password, do so and click create. You will need this address each time you start a metamask session ( it is not the private key to your wallet, we will get to that shortly!)

Secret Recovery Phrase

You can watch a short video on what this is, this super important to keep for your wallet that has real crypto funds in it!. For our dev one we will need is if we look to use this same wallet outside of MetaMask, so make a note of it. If you don’t, then don’t sweat it, we can get it from metamask later on.

Record the secret recovery phrase

When you see this screen, click on the grey box with a lock on it and you will find 12 words in there, this is your mnemonic, it is they key to your wallet. The keys to your vault if you consider yourself the bank. For your real wallet keep them safe and away from prying eyes.

Click Next once you are done here and re-enter the words to verify you have them. After this you are done!

You have now installed Metamask and have your very own Crypto Wallet!

Let’s get some Testnet Tokens!

First you may be asking, what the hell is a testnet? In sort it is a network where we can play around and not need to spend any money to test our code or play with crypto. The testnets do not have anywhere near the same amount of toys to play with as the mainnet.

There are a few Testnets for ETH you will need to enable show/hide Testnets in metamask. To do this click on Ethereum Mainnet and then click on the link Show/Hide test networks.

Click on Ethereum Mainnet then Show/hide test network
You are taken to config page and need to enable Show test networks

You can now see the test networks

Free Tokens from the faucet

A faucet is a place we can be drip fed some ETH for our transactions. we are going to get them from Kovan Faucet

Go to the Kovan Faucet and click on Connect Wallet, there is a button in upper right or in the main box on the screen. Once you click you get asked if you want to use Metamask or other wallets, select MetaMask

MetaMask will pop up and ask which wallets you want to allow to connect to this site & to authorise connection for those wallets

Cick on Next, then click on Connect

Error!!!

If you see this message after connecting your wallet then we need to change the network MetaMask is connected to.

Change Metamask to the Kovan Test Network

Click on the Metamask Icon, the wallet will pop up and then click on Ethereum Mainnet, you get presented with a list of networks select Kovan.

Select the Kovan Network
When you have selected the Kovan Network metamask will look like this

This Faucet is very smart and detects this change, you will see a page like the image below, you need to prove you are not a robot and then can click send request and the faucet will initiate the transaction to send you 0.1 test ETH and 20 test LINK ( uncheck link this if you dont want the link )

Faucet detects we are on the kovan network and is ready to drip feed us.

Initiate the drip feeding! once you click on Send request you will need to wait whilst the transaction process’s on the blockchain. it will go through a few phases and at the end you will see some ETH in your metamask wallet

Show me the ETH!

Open up MetaMask and you will see you now havev 0.1 eth, if you are wondering

There you have it! You have setup metamask and have some ETH for the testnet!

If you decided to get some LINK as well and are wondering where it is? Well dont fear it is in your account on the blockchain, but metamask does not know about this token yet. you can use the import tokens link and paste (0xa36085F69e2889c224210F603D836748e7dC0088) this in to the Token Contract Address field, MetaMask will detect the other values needed.

Add the tokens contract
Import the token in to MetaMask
See it in your balances

You are now ready to play in the testnet! woo hoo.

If you are stuck thinking what you can do,

  • Try setting up a 2nd account and sending some value ( ETH or LINK )to yourself!
  • Write your first smart contract
12 months ago 1 comment
TwitterLinkedin
BlockchainBlogFeaturedTutorial

Writing your first Ethereum Smart Contract

by Matt Heff 12 months 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.

12 months 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

    12 months ago
  • 2

    Create your own JSON.stringify() function

    11 months ago
  • 3

    Install Metamask and get Testnet Tokens

    12 months ago
  • 4

    Introduction to JSON with Examples

    12 months ago
  • 5

    What is an AMM ( Automated Market Maker)

    11 months 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

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

    6 months ago
  • Web3 RPC Nodes

    10 months ago

Featured Posts

  • How to read environment variables with Node.js

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

    6 months ago
  • Web3 RPC Nodes

    10 months 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