Developers Forum for XinFin XDC Network

ruslan wing
ruslan wing

Posted on

How to use XinFin’s Open API to Build Your First DApp on XDC Network

Continuous innovation in blockchain technology has seen it become more mainstream. Particularly, advances in blockchain and distributed ledger technologies (DLTs) have pushed the technology beyond the disillusionment trough of the hype cycle, and are driving real productivity in major industries — -including finance and trade. Fundamentally, blockchain and DLTs are changing the nature of doing business across organizational boundaries, helping companies reimagine how they make and manage a variety of tangible and digital assets.

Image description

And, whilst there are many blockchains, each blockchain protocol comes with unique features and capabilities. With organizations seeking the best combination of the blockchain space, the demand for hybrid blockchains has risen, amidst the boom in blockchain demand. Taking the case of finance and trading industries, it’s evident that such industries need a hybrid system that allows them to reap benefits associated with public and private blockchain networks. And, these benefits are: improving access to a mass audience of adopters and protecting sensitive data

Combining attributes of public and private blockchains, hybrid blockchains provide some game-changing benefits, especially in the global trade and finance industries. The networks are considerably efficient and interoperable, supporting the development of highly scalable decentralized apps (DApps) and blockchain-powered platforms.

In alignment with the shift towards hybrid blockchain networks, the XDC Network employs the XDC delegated proof of stake (XDPoS) blockchain protocol. The protocol promotes decentralization across numerous industries. With highly interoperable smart contracts, instant block finality, low energy consumption, and low network congestion, the XDC network provides a conducive environment for DApp development.

Having these insights in mind, let’s discuss how to use XinFin API when building your first blockchain app. Key areas to cover:

  1. What’s a DApp?
  2. Why develop DApps on the XinFin Network?
  3. What tools do you require to deploy a DApp on the XinFin Network?
  4. What is XinFin’s API, and how does it work?

a). What’s a DAPP

A decentralized application (dApp) is an application built on Xinfin’s decentralized network. The application combines a frontend user interface and a smart contract. Within the XinFin network, smart contracts are accessible and transparent — -like open APIs. This makes it possible to incorporate smart contracts developed elsewhere — -or by someone else — — in your dApp.

What’s more, the DApps backend code runs on a decentralized peer-to-peer XinFin network. This is in contrast to conventional apps where the back-end code runs on centralized servers. Note: a dApp can have a frontend code and user interface that’s written in an array of languages — just like an app —, and that can make calls to its back end. And, its front end can be hosted on decentralized storage like the InterPlanetary File System (IPFS).

With the unique features, DApps remain:

  • Decentralized, meaning that they are independent, and no one can control them as a group.
  • Deterministic, meaning they perform the same function irrespective of the environment in which they are executed.
  • Turing is complete, meaning the dapp can perform any action given the required resources.
  • Isolated, which means that they are executed in a virtual environment known as Ethereum Virtual Machine so that if the smart contract happens to have a bug, it won’t hamper the normal functioning of the blockchain network

On smart contracts:

To have a better understanding of DApps, you need to know what are smart contracts — a dApp’s backend, for lack of a better term.

A smart contract is a code that lives on the XinFin blockchain and runs exactly as programmed. Once deployed on the network, you can’t change them. DApps are decentralized because they are controlled by the logic written into the contract, rather than an individual or company. This implies that you should design your smart contracts with care and test them extensively to eliminate bugs.

b). Why develop DApps on the XinFin Network

  1. Zero downtime — -Once you deploy the smart contract at the core of your DApp that’s on the XinDin blockchain, the network is able to serve clients seeking to interact with the contract. Therefore, malicious actors cannot launch denial-of-service attacks targeting your DApps.

  2. Privacy — -When developing on the XinFin Network, you don’t need to provide real-world identity to deploy or interact with a DApp. Your XDC account is your login, and you just need a wallet to gain access.

  3. Resistance to censorship — — Within the XinFin Network, no single entity can block users from submitting transactions, deploying DApps, or reading data from the XinFin blockchain.

  4. Complete data integrity — — Thanks to the network’s cryptographic primitives, data stored on the XinFin blockchain is immutable and indisputable. As such, malicious actors cannot forge transactions or other data that has already been made public.

  5. Trustless computation/verifiable behavior — — Smart contracts on the network can be analyzed and are guaranteed to execute in predictable ways, and without the need to trust a central authority. This is unlike traditional models where we need to trust a central authority to protect vital information. A great example is the online banking system, where we have to trust that financial institutions won’t misuse or tamper with our financial information. Or, in some cases, get hacked by malicious actors.

  6. Numerous APIs — -The XinFin Network has 10 Different types of API, which can help developers build DApps on the Network.

c). What tools do you require to Deploy a Dapp on the XinFin Network

To deploy a DApp on the XinFin network, you’ll need several tools. These are:

  1. XinPay: The extension wallet allows users to store and manage account keys, broadcast transactions, send and receive Ethereum-based cryptocurrencies and tokens, and securely connect to decentralized applications. These transactions take place through a compatible web browser or the mobile app’s inbuilt browser.

  2. XinFin-Remix IDE: Thanks to a rich set of plugins that have intuitive GUIs, the open-source web and desktop application fosters a fast development cycle. The remix plays a key role in the entire contract development journey and serves as a safe playground for learning and teaching on the XinFin Network.

For more details on XDC chain network tools and documents, kindly refer to the detailed document, here.

Having understood more about DApps and let’s dig deeper into XinFin API and how it works

d). What’s XinFin’s API, and how does it work

XinFin’s API comprises accounts, transactions, and blocks involved in

allowing DApps to access data and interact with external software components, operating systems, and microservices.

1)XinFin Accounts:

A XinFin account is an entity with an (XDC) balance that can send transactions on a XinFin Network. Accounts can be user-controlled or deployed as smart contracts.

On the XinFin Network, there are two types of accounts:

  • Externally owned — controlled by anyone with the private keys
  • Contract — a smart contract deployed to the network, controlled by code.

Both account types have the ability to:

  • Receive, hold and send XDC and XRC-20 tokens
  • Interact with deployed smart contracts

To check out the list of all the accounts through the API, you just need to change the page number and you’ll get all the account information. Visit this page and change the page number to check out a specific account.

Given the accounts on XinFin’s network, what are the key differences:

  • With externally-owned accounts, creating an account costs nothing, and transactions between externally-owned accounts can only be XDC or XRC-20 transfers. As well, externally-owned accounts can initiate transactions.
  • With contract accounts, creating accounts has costs since you’re using network storage, transactions from an external account to a contract account can trigger code that can execute many actions, such as transferring tokens or even creating a new contract. And, the account can only send transactions in response to receiving a transaction.

What’s more, XinFin accounts have four fields that demonstrate some uniquenesses in the two types of accounts. They include:

  • Nonce — a counter that indicates the number of transactions sent from the account. This ensures transactions are only processed once. In a contract account, this number represents the number of contracts created by the account

  • Balance — the number of Wei owned by this address. Wei is a denomination of XDC, and there are 1e+18 Wei per XDC.

  • CodeHash — this hash refers to the code of an account on the (EVM). Contract accounts have code fragments programmed in that can perform different operations. This EVM code gets executed if the account gets a message call. It cannot be changed, unlike the other account fields. All such code fragments are contained in the state database under their corresponding hashes for later retrieval. This hash value is known as a codeHash. For externally owned accounts, the codeHash field is the hash of an empty string.

  • StorageRoot — Sometimes known as a storage hash. A 256-bit hash of the root node of a Merkle Patricia trie that encodes the storage contents of the account (a mapping between 256-bit integer values), encoded into the trie as a mapping from the Keccak 256-bit hash of the 256-bit integer keys to the RLP-encoded 256-bit integer values. This trie encodes the hash of the storage contents of this account and is empty by default.

More details on externally-owned accounts and contract accounts:

  • Externally-owned accounts and key pairs — -An account is made up of a cryptographic pair of keys: public and private. They help prove that a transaction was actually signed by the sender and prevent forgeries. Your private key is what you use to sign transactions, so it grants you custody over the funds associated with your account. You never really hold cryptocurrency, you hold private keys — the funds are always on the XinFin ledger. This prevents malicious actors from broadcasting fake transactions because you can always verify the sender of a transaction.

Let’s look at an example:

  • If Sam wants to send XDC from his externally-owned account to Billy’s account, Sam needs to create a transaction request and send it out to the XinFin network for verification. XinFin’s usage of public-key cryptography ensures that Sam can prove that he originally initiated the transaction request. Without cryptographic mechanisms, a malicious adversary Eve could simply publicly broadcast a request that looks something like “send 5 XDC from Sam’s account to Billy’s account,” and no one would be able to verify that it didn’t come from Sam.

To check out the Address balance through the API (https://xdc.blocksscan.io/api/accounts/xdc8332dfdcec18d974eeac6bb2f84d571cac925511), you just need to change the address and you can view the information about the address

On account creation for externally owned accounts:

To create an account most libraries will generate a random private key. The private key is made up of 64 hex characters and can be encrypted with a password.

For example:

fffffffffffffffffffffffffffffffebaaedc96af48a01aram82q3de025823g

Enter fullscreen mode Exit fullscreen mode

Here’s an example of creating an account in the console using XDC

personal_newAccount

personal.newAccount()

Passphrase:

Repeat passphrase:

“xdc2253a4A9Ae8dC13eE94E600e7AeA54FF70bd55c2”

Enter fullscreen mode Exit fullscreen mode

It is possible to derive new public keys from your private key but you cannot derive a private key from public keys. This means it’s vital to keep a private key safe and, as the name suggests, PRIVATE.

You need a private key to sign messages and transactions which output a signature. Others can then take the signature to derive your public key, proving the author of the message. In your application, you can use a javascript library to send transactions to the network.

  • Contract accounts

Contract accounts also have a 43 character hexadecimal address:

Example:

Xdc3b31ded686558655abc5a2b581790a19904a341e
Enter fullscreen mode Exit fullscreen mode

The contract address is usually given when a contract is deployed to the XinFin Blockchain. The address comes from the creator’s address and the number of transactions sent from that address (the “nonce”)

Kindly Note: An account is not a wallet. A wallet is a key pair associated with a user-owned account, which allows a user to make transactions from or manage the account.

You can also get the contract address detail through API https://xdc.blocksscan.io/api/contracts/xdc5d5f074837f5d4618b3916ba74de1bf9662a3fed.

Equipped with insights on how an account is generated on the XinFin Hybrid Blockchain, let’s look at how Transactions work.

  1. Transactions:

Transactions are cryptographically signed instructions from accounts. An account will initiate a transaction to update the state of the XinFin network. The simplest transaction is one that involves transferring XDC or any XRC-20 tokens from one account to another

On the XinFin network, a transaction is an action that’s initiated by an externally-owned account. In other words, an account is managed by a human, not a contract.

For example, if Sam sends Billy 100 XDC, Sam’s account must be debited and Billy must be credited. This state-changing action takes place within a transaction.

Transactions, which change the state of the EVM, need to be broadcast to the whole XinFin network. Any Masternode can broadcast a request for a transaction to be executed on the EVM. And, after this happens, a Masternode will execute the transaction and propagate the resulting state change to the rest of the XinFin network.

A submitted transaction includes the following information:

  • Recipient — the receiving address (if an externally-owned account, the transaction will transfer value. In a contract account, the transaction will execute the contract code.

  • Signature — the identifier of the sender. This is generated when the sender’s private key signs the transaction and confirms the sender has authorized the transaction.

  • Value — the amount of XDC to transfer from sender to recipient (in WEI, a denomination of XDC).

  • Data — an optional field to include arbitrary data

  • GasLimit — the maximum amount of gas units that can be consumed by the transaction. Units of gas represent computational steps.

  • MaxPriorityFeePerGas — the maximum amount of gas to be included as a tip to the Masternode.

  • MaxFeePerGas — the maximum amount of gas willing to be paid for the transaction (inclusive of baseFeePerGas and maxPriorityFeePerGas).

Gas is a reference to the computation required to process the transaction by a Masternode. Users have to pay a fee for this computation. The gasLimit, and maxPriorityFeePerGas determine the maximum transaction fee paid.

The transaction object will look a little like this:

{
from: “xdcEA674fdDe714fd979de3EdF0F56AA9716B898ec8”,
to: “xdcac03bb73b6a9e108530aff4df5077c2b3d481e5a”,
gasLimit: “21000”,
maxFeePerGas: “300”
maxPriorityFeePerGas: “10”
nonce: “0”,
value: “1000”,
}
Enter fullscreen mode Exit fullscreen mode

But a transaction object needs to be signed using the sender’s private key. This proves that the transaction could only have come from the sender and was not sent fraudulently.

Example: XinFin-JSON-RPC call:

{
“id”: 2,
“jsonrpc”: “2.0”,
“method”: “account_signTransaction”,
“params”: [
{
“from”: “xdc1923f626bb8dc025849e00f99c25fe2b2f7fb0db”,
“gas”: “0x55555”,
“maxFeePerGas”: “0x1234”,
“maxPriorityFeePerGas”: “0x1234”,
“input”: “0xabcd”,
“nonce”: “0x0”,
“to”: “xdc07a565b7ed7d7a678680a4c162885bedbb695fe0”,
“value”: “0x1234”
}
]
}
Enter fullscreen mode Exit fullscreen mode

Example response:

{
“jsonrpc”: “2.0”,
“id”: 2,
“result”: {
“raw”: “0xf88380018203339407a565b7ed7d7a678680a4c162885bedbb695fe080a44401a6e4000000000000000000000000000000000000000000000000000000000000001226a0223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20ea02aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663”,
“tx”: {
“nonce”: “0x0”,
“maxFeePerGas”: “0x1234”,
“maxPriorityFeePerGas”: “0x1234”,
“gas”: “0x55555”,
“to”: “xdc07a565b7ed7d7a678680a4c162885bedbb695fe0”,
“value”: “0x1234”,
“input”: “0xabcd”,
“v”: “0x26”,
“r”: “0x223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20e”,
“s”: “0x2aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663”,
“hash”: “0xeba2df809e7a612a0a0d444ccfa5c839624bdc00dd29e3340d46df3870f8a30e”
}
}
}
Enter fullscreen mode Exit fullscreen mode

Note: The raw is the signed transaction in Recursive Length Prefix (RLP) encoded form, while the tx is the signed transaction in JSON form.

On gas:

As mentioned, transactions cost gas to execute. Simple transfer transactions require 21000 units of Gas.

So for Billy to send Sam 1000 XDC at a baseFeePerGas of 190 gwei and maxPriorityFeePerGas of 10 gwei, Billy will need to pay the following fee:

(190 + 10) * 21000 = 4,200,000 gwei

— or —

0.0042 XDC

Billy account will be debited -1,00042 XDC

Sam account will be credited +1,000 XDC

The base fee will be burned -0.003735 XDC

Masternode keeps the tip +0.000197 XDC

Gas is required for any smart contract interaction too.

What is the transaction lifecycle?

Once the transaction has been submitted, the following happens:

  • Once you send a transaction, cryptography generates a transaction hash:
    0x97d99bc7729211111a21b12c933c949d4f31684f1d6954ff477d0477538ff017

  • The transaction is then broadcast to the network and included in a pool with lots of other transactions.

  • Your transaction will also get a block confirmation number. This is the number of blocks created since the block that your transaction was included in. The higher the number, the greater the certainty that the transaction was processed and recognized by the network. This is because sometimes the block your transaction was included in may not have made it into the chain.

  • The larger the block confirmation number, the more immutable the transaction is. So for higher value transactions, more block confirmations may be desired.

3). Blocks

Blocks are batches of transactions with a hash of the previous block in the chain. The blocks are linked together into a chain because hashes are cryptographically derived from the block data. This prevents fraud because one change in any block in history would invalidate all subsequent blocks as all subsequent hashes would change and everyone running the blockchain would notice.

By changing the block number through the API(https://xdc.blocksscan.io/api/blocks/2304) you will get all the details on the specific block number.

And, why are blocks important?

To ensure that all participants on the XinFin network maintain a synchronized state and agree on the precise history of transactions, we batch transactions into blocks. This means dozens (or hundreds) of transactions are committed, agreed on, and synchronized all at once.

By spacing out commits, we give all XinFin network participants enough time to come to a consensus: even though transaction requests occur dozens of times per second. Worth noting, blocks on the XinFin Network are committed approximately once every two seconds.

How do blocks work?

To preserve the transaction history, blocks are strictly ordered (every new block created contains a reference to its parent block). And, transactions within blocks are strictly ordered as well. Except in rare cases, at any given time, all participants on the network are in agreement on the exact number and history of blocks and are working to batch the current live transaction requests into the next block.

What is in a block?

Several components are included in a block. These include:

  • Timestamp — the time when the block was created.
  • BlockNumber — the length of the blockchain in blocks.
  • BaseFeePerGas — the minimum fee per gas required for a transaction to be included in the block.
  • Difficulty — the effort required to create the block.
  • MixHash — a unique identifier for that block.
  • ParentHash — the unique identifier for the block that came before (this is how blocks are linked in a chain).
  • Transactions — the transactions included in the block. StateRoot — the entire state of the system: account balances, contract storage, contract code, and account nonces that are inside.
  • Nonce — a hash that, when combined with the mixHash, proves that the block has gone through XinFin Delegated Proof of Stake (XDPoS).

What is a block size?

Worth noting, blocks themselves are bound in size. Each block has a target size of 15 million gas, but the size of blocks will increase or decrease in accordance with network demands, up until the block limit of 30 million gas (2x target block size). The total amount of gas expended by all transactions in the block must be less than the block gas limit. This is important because it ensures that blocks can’t be arbitrarily large.

If blocks could be arbitrarily large, then less performant full nodes would gradually stop being able to keep up with the network due to space and speed requirements

Important Resources on API

a). For more API you can refer to https://explorer.xinfin.network/publicAPIDoc where you’ll all the APIs. You can also find the XinFin API docs https://apidocs.xinfin.network/docs/#xinfin-apis. You can also check out the XinFin Docs for more info.

b). You can also check out XinFin Network JSON-RPC at https://apidocs.xinfin.network/ and check out the third party Explorer API at https://xdc.blocksscan.io/docs/

c). Are you interested in multiple SDK written in Go, Rust, Java, and XDC3 Android which can be used for mobile development? You can study multiple API Developed by XDC Foundation, in collaboration with LeewayHertz. Visit the XDC Foundation Github page to have a better understanding of SDK in DApp development.

d). To build a DApp with XinFin and Tatum — -which is a Next-gen blockchain infrastructure —, you can check the XinFin API at: https://tatum.io/apidoc

e). And to use Tatum API on your DApp or application, check out the step-by-step article https://blog.tatum.io/build-global-trade-and-finance-applications-on-the-xdc-network-with-tatum-993e9c75a289

Discussion (0)