6

How to Fetch Data From the Ethereum Blockchain Using Swift

 1 month ago
source link: https://swiftsenpai.com/development/fetch-data-from-ethereum/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to Fetch Data From the Ethereum Blockchain Using Swift

Ever since the introduction of the Ethereum blockchain in the year 2015, it has revolutionized the entire software development industry. It is the first blockchain that has smart contract capability, allowing developers to create and deploy decentralized applications (dApps) that interact with the Ethereum blockchain.

Nowadays most dApps are web-based applications. However, I do believe that mobile native dApps will become more and more popular when blockchain technology gets greater adoption over time.

In this article, I will show you how to create a simple dApp that fetches the latest gas price from the Ethereum Mainnet. Throughout the process, you will learn how to gain access to a public node, what library you should use in your Xcode project, and how to connect & fetch data from the Mainnet.

Without further ado, let’s jump right in!


The Basic Concept

If you are reading this article, I assume you already have some basic idea of what a blockchain is. If you don’t, you can think of it as a gigantic server consisting of thousands of nodes hosted all around the world.

Pro tip:

Check out this page for all the Ethereum nodes currently available around the globe.

The way to fetch data from the Ethereum blockchain is very similar to how you fetch data from a centralized server. Instead of connecting to a centralized server, we will connect to an Ethereum node that exposes a list of JSON-RPC methods (API endpoints). By using the provided API endpoints, we can then perform actions such as getting the current gas price or getting the balance of an address.

Does this mean that we need to set up our own Ethereum node in order to get started? Well, not necessary.

There are third-party services out there such as Infura and Alchemy that provide APIs to a public node. All we need to do is subscribe to their free tier service, then we are good to go. For this article, Infura will be our main focus, but you can definitely use Alchemy if that’s your preferred choice.

Once we have the node in place, fetching data from the Ethereum blockchain is just a matter of calling the API endpoints. For our sample app, we will be using a web3.swift library developed by Argent Labs to ease us in interacting with the Ethereum blockchain.

With the basic concept out of the way, let’s head over to Infura and get things started.


Working with Infura

As you might have guessed, the first thing you need to do is to create an Infura account. You can do it here.

Once you gets your account up and running, head over to the dashboard and create a new project:

Using Infura for iOS dApp development
Infura dashboard

In the new project dialog, choose “Ethereum” as product and fill in the project name you desire:

Create a new project in Infura for iOS dApp development
Create new project in Infura

Once the project is created, you will be redirected to the project settings page. This is where you can get the JSON-RPC endpoint of your project:

Obtaining JSON-RPC endpoint in Infura for iOS dApp development
Getting project endpoint in Infura

If you do not want to test your dApp on the Ethereum Mainnet, you can use the dropdown menu to switch to testnets such as Ropsten and Rinkeby to get their respective endpoints.

Switching endpoint in Infura
Switching endpoint in Infura

With that, we have successfully set up Infura and can now start using the given endpoint to interact with the Ethereum blockchain.


Fetching Data From the Ethereum Blockchain

The JSON-RPC method that we can use to get the current Ethereum gas price is eth_gasPrice. If you take a look at the API specification of the method, you will notice that the response body is as follow:

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": "0x12a05f200"
}

where the gas price (result) is represented by a hex code of an integer.

You can definitely perform a post request to the eth_gasPrice method and manually parse the given hex code back to an integer, but that is way too troublesome! Let me introduce you to a much better way to deal with such a situation — by using the web3.swift library.

The web3.swift Library

As mentioned earlier, the web3.swift library is developed by Argent Lab, the team behind the famous mobile DeFi wallet “Argent“. Their primary goal of open-sourcing the library is to facilitate easy access to the Ethereum blockchain via a Swift native library, mainly for the creation of decentralized iOS apps. Therefore, if you like the library and would like to support what the team is doing, feel free to give them your feedback and contribute to the library.

Now back to the library itself, it is basically a wrapper class for some of the most commonly used methods of the Ethereum blockchain. It takes care of all those heavy lifting tasks such as API calling and JSON parsing for us. The best part is that it even supports the new Swift Concurrency (async/await) syntax.

Pro Tip:

After you installed the library, check out EthereumClientProtocol defined in EthereumClient.swift to see all the JSON-RPC methods supported by the library.

To get the gas price from the Ethereum blockchain, all we need to do is to create an instance of the EthereumClient using the endpoint we obtained from Infura, and call the respective client method accordingly.

import web3

// Create an Ethereum client URL using the endpoint URL from Infura
guard let clientUrl = URL(string: "https://mainnet.infura.io/v3/<infura_project_id>") else {
    return
}

// Create an Ethereum client
let client = EthereumClient(url: clientUrl)

Task {
    
    // Get gas price in wei
    let gasPrice = try await client.eth_gasPrice()
    
    // Convert gas price from wei to Gwei
    let converted = gasPrice.quotientAndRemainder(dividingBy: 1000000000)

    print("Current gas price: \(gasPrice) wei")
    // Output: Current gas price: 37354545651 wei
    
    print("Current gas price: \(converted.quotient) Gwei")
    // Output: Current gas price: 37 Gwei
}

One thing to take note of is that the eth_gasPrice() method returning type is BigUint, which is an integer type that is wider than UIntMax. Therefore, we can use the quotientAndRemainder(dividingBy:) function provided by BigUint to convert the given gas price from wei to Gwei.

With that, you have successfully created your first decentralized iOS app that runs on the Ethereum blockchain. Way to go! 🥳


Wrapping Up

In this article, I only cover the bare minimum of what you need to know in order for you to get started with dApp development using Swift. There are still lots of topics surrounding mobile dApp development such as connecting to a wallet, handling transactions, etc. that I have yet to cover.

At this moment, I am still at the stage of exploring and learning. I will continue to share what I’ve learned here on this blog, so please stay tuned for more articles like this in the near future.

In the meantime, you can follow me on Twitter and check out my other articles related to Swift and iOS development.

Thanks for reading. 👨🏻‍💻


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK