Integration RESTful API – Documentation

No Comment Yet

1. Introduction

Welcome to the party you never knew you were missing – the documentation of our fabulous Integration API for the very first decentralized operating system – GRIDNET OS. Now, before you yawn and consider clicking away, let’s give you a mental image.

Imagine a world where intrepid node operators are deploying new nodes left, right, and center. They’re earning these shiny, new-fangled digital assets. Great, right? But wait, what do they do with these assets? Stack them up into a digital Scrooge McDuck-like money bin and take a swim? That might be fun in the cartoon world, but we live in a reality bound by the cold, hard rules of economics. There would be no incentive for our brave node operators if they couldn’t exchange, trade, or use these assets in the real world.

The system is ‘good’ when it’s decentralized.

This is where our Integration API steps onto the scene, like a super-hero with an ability to build bridges between different dimensions. Mainly used by cryptocurrency exchanges (our unsung heroes who make the world of digital asset trading possible), it enables these platforms to list, trade, and manage the assets earned by the node operators. But the Integration API is not an exclusive club for exchanges. No, sir! It swings open its digital doors to any entity willing to deploy software such as blockchain explorers, further expanding the ecosystem and empowering the community. So, buckle up, dear reader, and prepare for a thrilling journey into the world of our Integration API. We promise it will be an informative, possibly hilarious, and absolutely necessary ride. Let’s go!

1.1 If you are an exchange

Alright, dear cryptocurrency exchanges, pull up your chairs and listen closely. If you’ve ever been frustrated with clunky, complex APIs that make you feel like you’re trying to decipher ancient hieroglyphs, boy, do we have news for you! Our Integration API is smoother than a fresh jar of skippy, and we’ve put ease of use right at the top of our priority list, like the cherry on top of your favorite sundae.

Imagine this scenario: You need to create a new wallet for one of your users, and you need to do it pronto. No worries! We’ve got your back. All you need to do is set up a node (it’s a breeze, we promise!) and point your browser towards this nifty little link right here – https://test.gridnet.org/api/genAddress. Now here’s where the magic happens. Every time you refresh that page, a shiny new wallet pops into existence. Yes, you heard that right. Refresh = New wallet. How’s that for easy? Now, you might be thinking, ‘Okay, generating wallets is all well and good, but what about transactions? Surely, those are going to be a hassle.’ Well, brace yourself because we’re about to blow your socks off. Issuing transactions and checking their results is as easy as pie. And not one of those complicated pies either, we’re talking a straightforward, delicious apple pie.

 

So, let’s recap. Wallets flying out left, right, and center with every refresh, transactions as easy as 1,2,3, and all of this wrapped up in the most user-friendly package imaginable. We hope you’re as excited about this as we are. Welcome to the future of API integration!

1.2 Preface

GRIDNET is a pioneering achievement in the field of distributed computing, representing the very first usable manifestation of the concept of a Decentralized Operating System (DOS). The system is powered by a network of independently operated nodes, GRIDNET OS has been ingeniously designed to foster a robust and highly flexible computing landscape. The nodes that constitute this intricate network operate in a random graph configuration, resulting in an efficient and resilient structure that is highly resistant to single points of failure, while ascertaining that there is not a single point of trust for all the services provided atop of the system.

 

One of the most innovative aspects of GRIDNET lies in its architecture. Each node within the network houses a collection of intricate subsystems, many of which are designed to offer interfacing capabilities with the external digital environment. One such crucial interface is the integrated RESTful API (Representational State Transfer Application Programming Interface), which provides a powerful medium for seamless integration with external systems. This system is intended to be used by developers rather than end users.

Getting to know what is contained within the system is one thing (..)

The Integration RESTful API, inherently present in every node, is built upon an internal web-server subsystem, a testament to the comprehensive design of GRIDNET OS, which promtes both ease of use and configuration. This web-based API plays a critical role in bridging the gap between the GRIDNET OS and third-party platforms, making it possible for them to effectively communicate and interact.

The Integration RESTful API is available by default and does not require any additional configurations, thereby promoting easy adoption and accessibility.

As an enabler of streamlined interactions, the Integration RESTful API is an indispensable component of GRIDNET, underpinning the system’s commitment to openness, flexibility, and seamless interoperability. Thanks to this powerful API, GRIDNET can effectively operate as part of a larger digital ecosystem, offering a wide range of benefits, from executing trades to managing state-domains, and much more. By offering such a comprehensive and accessible interface, GRIDNET OS not only encourages third-party integrations but also reinforces its position as a progressive, inclusive, and forward-thinking decentralized platform.

1.3 Overview – Basic Concepts

The GRIDNET OS API offers a wide range of functions that are particularly relevant for third parties such as cryptocurrency exchanges. By using this API, these entities can integrate seamlessly with the decentralized GRIDNET OS, thereby opening up a world of opportunities for sophisticated and decentralized trading activities. The choice of a REST interface stems from the intention of minimizing integration costs while also maximizing interpretability and platform independence.

The support of HTTP protocol, the support of GET requests is all that is evert needed on the client system to support seamless integration. The client does not need to be capable of any cryptographic computations or encoding schemas – the season is – all the required coefficients such as wallets’ identifiers, private/public key-pairs may be generated through this very API itself.

 

Let’s now take a look at some of the basic concepts involved.

  • Executing Trades: Trades are executed through the ‘sendTX’ function, which is designed for initiating transactions within the decentralized GRIDNET system. A transaction request would return a receipt identifier that can be used to track the status of the transaction. As transactions are processed asynchronously in this fully decentralized network, it’s advisable for issuers to wait for multiple blocks (3+ is recommended) before considering a transaction concluded.
  • Querying Results: The receipt identifier returned from a transaction request can be used to query the result of the transaction using the ‘getTX’ function. As the processing is asynchronous, this allows issuers to track when a transaction is concluded and ensure that the expected actions have taken place.
  • Registering State-domains: State-domains, which are analogous to accounts in a traditional financial system, can be registered through the API. These state-domains serve as entities for executing trades and managing balances within the GRIDNET system.
  • Creating Key Pairs: The API provides the ‘genAddress’ function for generating new private and public key pairs. These key pairs are essential for managing identities within the GRIDNET system and for creating state-domains.
  • Verifying State-domain Addresses: The ‘checkAddress’ function can be used to validate state domain addresses. This helps ensure that transactions are being sent to valid destinations and protects against possible errors or malicious activities.
  • Browsing Transaction and Block History: The API provides functions (‘getTX’ and ‘getBlock’) for retrieving detailed information about specific transactions and blocks. This allows issuers to track the history of events within the GRIDNET system, which is crucial for auditing and record-keeping purposes.
  • Querying Balances: The ‘getBalance’ function allows issuers to retrieve the balance associated with a particular state-domain. This is crucial for managing account resources and making informed trading decisions.
  • Estimating Transaction Costs: The API allows issuers to estimate the costs of transactions before they are executed. This helps issuers to manage their resources more effectively and avoid unexpected costs.
  • Validating Data: The GRIDNET API is equipped with robust data validation mechanisms. Before a transaction is processed, the node validates all the arguments and returns errors if any inconsistencies are found. This helps ensure the integrity and reliability of transactions within the GRIDNET system.

 

All these functions are made available through the API’s HTTP GET requests, which are standard in RESTful interfaces and should be familiar to most developers. Binary data is expected to be base64 encoded, while private and public key-pairs should be base58-check encoded.

Allowing for a seamless and easy integration is a yet another story! Task accomplished.

Crypto exchanges can benefit from these capabilities in particular –  as these allow them to interact directly with the GRIDNET operating system, enabling for a more transparent, secure, and decentralized trading capabilities to their customers. It is however highly recommended for exchanges to run their own GRIDNET node for executing transactions, to maintain the confidentiality of their private keys and to assure uninterrupted services at all times.

2. Prerequisites

In a decentralized system like GRIDNET, security is paramount. While the RESTful API can be accessed through any public node, a key exception is made for the ‘sendTX’ function, which is responsible for initiating transactions. For the purpose of executing transactions, it is highly recommended for exchanges or other entities to deploy a private node. The reason behind this is the need to ensure the confidentiality and integrity of your private keys. The private key is a critical component that secures your transactions and identifies you on the network. Sharing a private key is equivalent to giving someone full access to the state-domain (or account) associated with that key.

Given the importance of private keys, they should be kept private and secure at all times.

Consequently, when it comes to executing transactions that require the use of a private key, these operations should be carried out on a trusted, private node under your control. Using a private node also provides you with more control over the processing and management of transactions. The ‘sendTX’ function, therefore, expects a private key that should not be shared or exposed to public nodes or any third-party entities. Providing your private key to public nodes would compromise the security of your transactions and the state-domain associated with the key. Always ensure to maintain strict control over your private keys and use your private node for transactions. Remember, the security of your interactions with the GRIDNET OS and the safety of your assets significantly depends on how securely you manage your private keys and where you choose to execute your transactions.

 

3. Understanding Error Handling

One of the robust design features of the GRIDNET Operating System’s RESTful API is its comprehensive error handling and reporting mechanism. The API performs a thorough check and validation on the arguments passed to it in each call and also ensures that the node has the required network connectivity to perform the requested operation.

Argument Validation

Before proceeding with the operation, the API validates the arguments received in the HTTP GET request. This validation ensures that the arguments conform to the expected formats and types, are within expected ranges, and adhere to any predefined constraints. In case of an invalid argument, the operation is halted and an HTTP error response is returned. The error response details the nature of the validation error, helping you identify the problem and fix it accordingly.

Network Connectivity Check

In addition to argument validation, the API also ensures the node has sufficient connectivity with the rest of the network. This is especially important for operations that affect the state of the network, such as transactions. If the API detects limited or no connectivity, it refuses to process the operation and returns an error message indicating the connectivity issue.

Interpreting Error Responses

When an error is encountered during the operation, the API responds with an HTTP error status code and a human-readable error message.

 

Error codes follow the standard HTTP status code conventions:

  • Codes in the 400 range indicate a client error. This could mean that the request was malformed, or that the operation could not be performed due to an error condition on the client’s side (such as invalid arguments or insufficient balance).
  • Codes in the 500 range indicate a server error. This means something unexpected happened on the server’s side when processing the request.

Accompanying these status codes is a human-readable error message that provides further information about the nature of the error. This message can be used to debug the issue and take corrective action.

Error handling in GRIDNET’s API is designed to be as transparent and helpful as possible. This allows you to build more resilient and reliable systems when interacting with the GRIDNET Operating System. Always pay attention to the returned error codes and messages to ensure smooth operation.

4. API Endpoint and Request Format

The API of the GRIDNET Operating System is designed to provide seamless integration with third-party systems and is structured around RESTful principles. This section will provide you with a brief overview of the endpoint and request format that you need to use when interacting with this API.

4.1  HTTP GET Parameters

All requests to the API are made using the HTTP GET method. This means that all parameters you wish to pass to the API should be included in the URL of your request as query parameters. This query string begins with a “?” after the URL path, and each parameter is formatted as a key-value pair. Multiple parameters are separated by an “&”. For example:
http://node-ip>:<port>/api/api-function?param1=value1&param2=value2

4.2 Binary Data Handling

When you need to pass binary data to the API, it must be encoded to ensure it can be transported safely over HTTP. This encoding converts the binary data into a format that consists only of printable characters, which are not going to be misinterpreted by the systems and protocols handling the HTTP request.

For most binary data, the API expects it to be base64 encoded. Base64 encoding is a widely used binary-to-text encoding scheme that transforms binary data into an ASCII string format:

Param=<base64-encoded-data>

4.3 Base58-check Encoding for Key Pairs

There is an exception when it comes to passing private and public key pairs to the API. Key pairs should be base58-check encoded. Base58-check is a modified version of base58 encoding, used for Bitcoin addresses and other similar use-cases, that includes built-in error checking. It’s designed to avoid visual confusion between similar-looking characters (like 0 and O, l and I, etc.) and provide a safeguard against typing mistakes. Besied that, the encoding contains an error detection code. http://<node-ip>:<port>/api/api-function?binary

A more concrete example, with arguments set:
http://<node-ip>:<port>/api/api-function?publicKey=<base58-encoded-public-key>&privateKey=<base58-encoded-private-key>

Do notice that your code may not, and most likely does not, need to implement handling of Base58-check since all the arguments expected in this encoding may be generated through this API (private-keys and public-keys).

5. API Methods

The RESTful API of the GRIDNET Operating System offers a comprehensive set of functions that allow you to interact with the system in various ways. Each function provided by the API constitutes a method, which has its own specific purpose, parameters, return types, error messages, and use cases.

This section will delve into the details of each API method. For each method, we will provide:

  • Method Overview: A brief description of what the method does.
  • Parameters: The expected input parameters for the method.
  • Return Types: The data types that the method returns.
  • Error Messages: Any error messages that the method might return.
  • Specific Use-Cases: Practical examples of when and how to use the method.
  • Possible Outcomes and Their Meanings: Description of the different outcomes you can expect when calling the method and what they imply.

 

This in-depth exploration of each API method should provide a thorough understanding of how to make the most out of the GRIDNET OS’s RESTful API. Whether you’re checking balances, processing transactions, or generating new key pairs, the provided methods are designed to support your integration needs.

As we go through each function, remember that all parameters are passed as HTTP GET parameters, with binary data being base64 encoded (unless it’s a private or public key, in which case it should be base58-check encoded). Please note, the execution of each function happens in the context of the decentralized GRIDNET system. This means that outcomes can vary depending on the state of the network at the time of the function call. We will now proceed with exploring each API function in detail.

5.1 Retrieving Balance with getBalance

The getBalance function is used to query the balance of a specific address on the GRIDNET OS. It expects the address as an input parameter and returns the balance associated with the address.

5.1.1 Method Overview

This function takes an address as an input parameter and returns a JSON object containing the balance of the given address. The JSON object includes a result field indicating the success or failure of the operation, an errorDescription field containing a human-readable error description if an error occurs, and a balance field showing the balance for the provided address.

5.1.2 Parameters

Input: The function expects a single parameter, address. This is passed as an HTTP GET parameter.

5.1.3 Return Types

Output: The function returns a JSON object with the following fields:

  1. result: An integer that indicates the status of the operation. A value of 0 indicates success, while any other value represents an error code.
  2. errorDescription: A string with a human-readable error description. This field is only present if an error occurs.
  3. balance: A string representation of the balance for the provided address. This field is only present if the operation is successful.
  4. nonce: an unsigned 64-bit number representing current nonce value (vector IV) associated with an account. The purpose of this value is to thwart reply attacks. This ‘nonce’ value is expected by some of the other RESTful functions as an optional argument. Usually, if nonce value is not provided – the system would retrieve the value automatically.

5.1.4 Error Messages

The function may return the following error messages:

  1. Service is temporarily unavailable due to maintenance. Please try again later.: This indicates that the Blockchain Manager is not running or is not available. The status code returned is 503.
  2. Invalid address: This indicates that the provided address does not exist in the system. The status code returned is 400.
  3. Missing parameter: 'address': This indicates that the address parameter was not provided in the request. The status code returned is 400.

5.1.5 Specific Use-Cases

This function is typically used when you need to check the balance of a specific address on the GRIDNET OS. Do notice that the returned value is stored within the ‘GNC’ file in the root folder of a State Domain.  Thus, the value may be returned by omitting the Integration API entirely and accessing its contents from the Web3 interface by going to https://NODE-IP/s/STATE_DOMAIN/GNC
Do notice that in such a case STATE_DOMAIN may be a friendly identifier registered through an Identity Token.

An example omitting the Integration API : https://test.gridnet.org/s/Alpacalypse/GNC

5.1.6 Possible Outcomes and Their Meanings

Upon calling this function, one of three things can happen:

  1. The function successfully retrieves the balance of the provided address and returns it in a JSON object with a result value of 0.
  2. The function cannot retrieve the balance because the address provided does not exist in the system. In this case, the JSON object returned will contain an errorDescription with the value Invalid address and a non-zero result.
  3. The function cannot process the request because the address parameter was not provided. In this case, the JSON object returned will contain an errorDescription with the value Missing parameter: 'address' and a non-zero result.

Remember, all of these outcomes are based on the assumption that the Blockchain Manager is running and available. If it’s not, a Service is temporarily unavailable due to maintenance. Please try again later. message is returned with a 503 status code.

Example of successful getBalance function call:

Request: GET /api/getBalance?address=address_stringResponse:
{
"result": 0,
"balance": "1000"
}

Example of unsuccessful getBalance function call:

Request: GET /api/getBalance?address=invalid_address_stringResponse:
{
"result": 1,
"errorDescription": "Invalid address"
}

5.2 Checking blockchain height with getHeight

The getHeight function is crucial in GRIDNET OS for obtaining the blockchain’s current height. It accepts an optional boolean parameter keyHeight and returns the blockchain height.

GRIDNET OS’s consensus algorithm incorporates three block types:

  • Data blocks: Contain the actual transactions.
  • Key blocks: Include Proof-of-Work and represent Operators’ Rewards, akin to Miners’ Rewards in earlier decentralized systems.
  • Hard-fork blocks: A special key-block type that expedites convergence and ensures Liveness post-Hard-Fork, without involving rewards.

Differentiating between blockchain height (including key and data blocks) and key height (only key blocks) is essential. The key height is always less than the height. This distinction is crucial in contexts like Operators’ Rewards’ vesting rules, where rewards are locked based on key blocks duration, not data blocks.

5.2.1 Method Overview

The getHeight function, with the optional keyHeight parameter, returns a JSON object indicating the blockchain’s height. This object includes result (operation success or failure), errorDescription (error details, if any), and height (blockchain height).

5.3 Consensus Mechanism and Block-Based Time Measurements

GRIDNET OS employs a unique consensus mechanism that utilizes block-based time measurements. This approach is grounded in the principle that key blocks emerge at consistent time intervals, governed by physical laws. This regularity in key block generation facilitates a reliable measure of time, enhancing the network’s ability to synchronize and maintain consistency.

Block-based timing is a cornerstone in preventing certain types of attacks, such as double-spending and timing-based manipulations. By ensuring a predictable and immutable sequence of block generation, GRIDNET OS maintains a high level of security and integrity in its transaction processing.

5.4 Enhanced Transaction Efficiency

Compared to systems like Bitcoin or Ethereum, GRIDNET OS achieves a significantly higher transaction rate. This efficiency is primarily due to its unique block structure and consensus algorithm. By separating transaction data and proof-of-work validations into different block types, GRIDNET OS streamlines processing and reduces bottlenecks typically found in traditional blockchain systems.

The dedicated data blocks allow for rapid and frequent transaction processing, while the key blocks maintain network security and consensus. This separation not only enhances throughput but also minimizes the latency often seen in networks like Bitcoin and Ethereum, where every block must perform dual roles.

Consequently, GRIDNET OS provides a robust, secure, and highly efficient platform for decentralized applications, outperforming older blockchain architectures in both security and transaction processing speed.

5.2.2 Parameters

Input: The function expects a single optional parameter, keyHeight. This is passed as an HTTP GET parameter.

5.2.3 Return Types

Output: The function returns a JSON object with the following fields:

  1. result: An integer that indicates the status of the operation. A value of 0 indicates success, while any other value represents an error code.
  2. errorDescription: A string with a human-readable error description. This field is only present if an error occurs.
  3. height: An unsigned integer representing the blockchain height. This field is only present if the operation is successful.

5.2.4 Error Messages

The function may return the following error messages:

  1. Service is temporarily unavailable due to maintenance. Please try again later.: This indicates that the Blockchain Manager is not running or is not available. The status code returned is 503.
  2. Invalid parameter: 'keyHeight' (expected 'true' or 'false'): This indicates that the provided value for the optional keyHeight parameter is not either true or false. The status code returned is 400.

5.2.5 Specific Use-Cases

Recall that each new block might contain additional transactions or code bundles that are executed by the network.

This function is typically used when you need to check the height of the blockchain on the GRIDNET OS.In addition, new blocks may be used to measure time flow or serve as a source for randomness. Indeed, there are many side-channel use case scenarios for blockchain technology. One of the most popular use case scenarios would be for the issuer of transaction to wait for a predefines amount of time (measured in the amount of consecutive blocks) before assuming a transaction as irreversible.

Do notice that the function allows for checking for both the current key-block height and the overall height. The key-block height returns height taking into account only key-blocks which are blocks containing the actual Proof-of-Work. A leader may issue an arbitrary number of consecutive data-blocks after being elected.  For security-related guarantees, measure time in key-blocks only.

5.2.6 Possible Outcomes and Their Meanings

Upon calling this function, one of two things can happen:

  1. The function successfully retrieves the height of the blockchain and returns it in a JSON object with a result value of 0.
  2. The function cannot process the request because the keyHeight parameter provided is not either true or false. In this case, the JSON object returned will contain an errorDescription with the value Invalid parameter: 'keyHeight' (expected 'true' or 'false') and a non-zero result.

Remember, all of these outcomes are based on the assumption that the Blockchain Manager is running and available. If it’s not, a Service is temporarily unavailable due to maintenance. Please try again later. message is returned with a 503 status code.

Example of a successful getHeight function call:

Request: GET /api/getHeight?keyHeight=trueResponse:
{
"result": 0,
"height": "2000"
}

Example of an unsuccessful getHeight function call:

Request: GET /api/getHeight?keyHeight=invalid_valueResponse:
{
"result": 1,
"errorDescription": "Invalid parameter: 'keyHeight' (expected 'true' or 'false')"
}

5.3 Retrieving Block Data with getBlock

The getBlock function retrieves details of a specific block on the GRIDNET OS blockchain. It requires a blockIndex parameter representing the block’s height and can optionally include transaction data and decompiled GridScript code.

5.3.1 Method Overview

This function takes a required blockIndex parameter and can optionally include transaction details and decompile GridScript source code within transactions. It returns a JSON object containing block details and, optionally, detailed transaction data.

5.3.2 Parameters

Input:

  • blockIndex: The height of the block to be retrieved. Required.
  • includeTX: A boolean indicating if transaction details should be included. Optional.
  • decompile: A boolean indicating if the GridScript source code within transactions should be decompiled. Optional.

5.3.3 Return Types

Output:

  • A JSON object containing:
    • result: An integer indicating the operation status. A value of 0 indicates success; other values represent error codes.
    • errorDescription: A human-readable error description if an error occurs.
    • block: An object representing the block, including details like block ID, type, key height, and more.
    • transactions: An array of transactions included in the block, each with detailed information, present if includeTX is true.

5.3.4 Error Messages

The function may return the following error messages:

  1. Service is temporarily unavailable due to maintenance. Please try again later.: Indicates the Blockchain Manager is not running or unavailable. Status code: 503.
  2. No block header found for the provided index: No block header found for the given blockIndex. Status code: 404.
  3. Invalid 'blockIndex' parameter - expected an unsigned integer: The blockIndex value is not an unsigned integer. Status code: 400.
  4. Block index out of range (expected uint64_t): The blockIndex value is out of range. Status code: 400.
  5. Missing parameter: 'blockIndex' (an unsigned integer): The required blockIndex parameter is missing. Status code: 400.

5.3.5 Specific Use-Cases

This function is used to fetch details of a specific block on the blockchain. It is especially useful for external systems that need detailed block information, including transactions and optionally decompiled GridScript code.

5.3.6 Possible Outcomes and Their Meanings

  1. The function successfully retrieves block details, including optional transaction data, and returns a JSON object with a result value of 0.
  2. The function returns an error with an appropriate error message and error code. The result will not be 0, and the errorDescription field will describe the error.
  3. If the Blockchain Manager is not running, a 503 status code is returned with an appropriate error message.

5.4 Issuing Transactions with getTX

The getTX function is used to get the details of a particular transaction on the blockchain on the GRIDNET OS. It expects a receiptID parameter representing the ReceiptID as a string and returns a JSON object containing the transaction representation.

Notice: In the nomenclature of GRIDNET OS, a transaction is an arbitrary, ordered and authenticated sequence of instructions processed by the System. This does not necessarily imply a value transfer. For this very reason, invocation of this function MAY imply invocation of GridScript decompile – once the decompile argument is set.

5.4.1 Method Overview

This function takes a required receiptID parameter and returns a JSON object with the following fields: a result field indicating the success or failure of the operation, an errorDescription field containing a human-readable error description if an error occurs, and a transaction field showing the transaction representation.

5.4.2 Parameters

Input: The function accepts the following arguments:

  • receiptID: The Receipt identifier (Required). This is passed as an HTTP GET parameter.
  • decompile

5.4.3 Return Types

Output: The function returns a JSON object with the following fields:

  1. result: An integer that indicates the status of the operation. A value of 0 indicates success, while any other value represents an error code.
  2. errorDescription: A string with a human-readable error description. This field is only present if an error occurs.
  3. transaction: A JSON object representing the transaction. This field is only present if the operation is successful. The transaction object includes the following fields:
    • ERGUsed: The amount of ERG used by the transaction.
    • result: The result of the transaction.
    • blockHeight: The height of the block in which the transaction is included.
    • verifiableID: The unique identifier of the transaction.
    • sacrificedValue: The value sacrificed in the transaction.
    • sourceDomain: The state-domain in the name of which the transaction was authenticated.
    • sourceCode: The decompiled GridScript source code. Each transaction has byte-core representation when stored by the decentralized state machine. This byte-code would be decompiled as part of invocation to this very method.
    • ERGLimit: The ERG Limit set by transaction’s originator.
    • nonce: The nonce  value specified within of the transaction. Recall that nonce needs to be +1 compared to value associated with source state-domain for the transaction to be processed.
    • confirmedTimestamp: The confirmed timestamp (UNIX Epoch) – the timestamp set by node confirming the transaction.
    • unconfirmedTimestamp: The timestamp set by the originating wallet – presumably the user.
    • confirmedTime – human readable representation of the confirmedTimestamp in UTC time.
    • unconfirmedTime – human readable representation of the unconfirmedTimestamp in UTC time.
    • log: An array representing the transaction log. Each entry in the array is a string. Typically, when there were no errors, the log would be empty to so to save on storage of the decentralized state machine. Otherwise, errors retrieved from the GridScript VM stack would make their way over here. Recall that invocations of GridScript instructions might be causing data alongside meta data being put onto the stack. Recall that the GridScript VM has a separate stack especially to accommodate meta-data. The error logs made available here are bases on information available in the meta-data stack.

5.4.4 Error Messages

The function may return the following error messages:

  1. Service is temporarily unavailable due to maintenance. Please try again later.: This indicates that the Blockchain Manager is not running or is not available. The status code returned is 503.
  2. Invalid Receipt Identifier ('receipt' argument) - expected a valid base58-check encoded receipt: This indicates that the provided value for the receiptID parameter is not a valid base58-check encoded receipt. The status code returned is 400.
  3. This sub-net is not supported by this node.: This indicates that the requested subnet is not supported by the node. The status code returned is 503.
  4. TX result not yet available.: This indicates that the transaction result is not yet available. The status code returned is 404.
  5. No receipt identifier provided (use the 'receipt' argument).: This indicates that the required receiptID parameter is missing. The status code returned is 400.

5.4.5 Specific Use-Cases

This function is typically used when you need to fetch the details of a specific transaction on the blockchain on the GRIDNET OS.

5.4.6 Possible Outcomes and Their Meanings

Upon calling this function, one of three things can happen:

  1. The function successfully retrieves the details of the transaction and returns it in a JSON object with a result value of 0.
  2. The function returns an error with an appropriate error message and error code. The result value will not be 0 and the errorDescription field will contain a description of the error.
  3. If the Blockchain Manager is not running, a 503 status code is returned with an appropriate error message.

5.5 Value Transfers with sendTX

The sendTX is used to create and register a transaction on the GRIDNET OS. It takes various transaction parameters, creates a transaction, and registers it in the system. As of now, it is the most security critical function of the entire Integration API.

IMPORTANT: call this mehod only on Core Nodes which are under your control. Otherwise, your private key would be compromised.

5.5.1 Method Overview

This function accepts a set of required and optional parameters representing various aspects of the transaction to be created. It returns a JSON object containing the receipt ID of the processed transaction, as well as a result field indicating the success or failure of the operation, and an errorDescription field containing a human-readable error description if an error occurs.

Recall: 1 GRIDNET Coin (GNC) = 1000000000000000000 GRIDNET Basic Units (atto units)

The method allows for value to be specified in following ways:

  • in GRIDNET Coins (GNC).
  • in GRIDNET Basic Units (GBUs, from mathematical perspective – these are ‘atto’ units).
  • when using GNC denomination, value may be provided as a decimal number (for instance as ‘1.5’).

5.5.2 Parameters

Input: The function expects the following parameters:

  • destination: The recipient’s state-domain’s identifier. Required.
  • value: The value to be transferred. It could be provided either in Atto units (the smallest unit in GRIDNET) or in GNC (1 GNC = 10^18 Atto units) when inGNC is set to true. Required.
    IMPORTANT:  the value argument MAY be specified as a double floating point value. For instance “1.5” could be used and if isGNC argument set the value would be converted to GRIDNET Basis Units (GBUs). If a decimal value is provided but isGNC is set, then all decimal places would be dropped. That is because 1 GBU (Atto Unit) is the smallest amount which is not dividable.
  • ERGLimit: The maximum limit of ERG that the transaction can consume. ERG (Energy) is a computational unit in GRIDNET. Required.
  • ERGPrice: The price per ERG for the transaction. Required.
  • privKey: The private key associated with the source state-domain. Required.
  • source: The source state-domain’s identifier. Optional.
  • sourcePubKey: The public key of the source state-domain. Optional.
  • nonce: A unique identifier used to prevent double-spending attacks. It needs to be equal to CURRENT_VALUE+1, where CURRENT_VALUE is associated with the source state-domain. Optional.
  • onlyCalculateFee: If set to true, the function only calculates the resulting processing fee and does not issue a transfer. Optional.
  • inGNC: If set to true, the provided value is assumed to be in GNC instead of Atto units. Optional.

IMPORTANT: Custom explicit Nonce can be used to dispatch multiple transactions rapidly without waiting for results of consecutive transactions. Be aware though that the correct order of transactions arriving at nodes is not guaranteed. While Core nodes incorporate mechanics which allow them to keep transactions, with nonce values  higher than expected, within of the memory pool while waiting for transactions with a lower nonce value to arrive before processing the former –  the overall Liveness guarantees would be lower than when using dedicated GridScript code targeting multiple recipients.  Processing of arbitrary GridScript code be achieved trough the processCode RESTful function.

5.5.3 Return Types

Output: The function returns a JSON object with the following fields:

  1. result: An integer that indicates the status of the operation. A value of 0 indicates success, while any other value represents an error code.
  2. errorDescription: A string with a human-readable error description. This field is only present if an error occurs.
  3. receiptID: A string representing the receipt ID of the processed transaction. This field is only present if the operation is successful and onlyCalculateFee is not set to true.
  4. fee: The calculated fee for the transaction. This field is only present if onlyCalculateFee is set to true.

5.5.4 Error Messages

The function may return the following error messages:

        1. Service is temporarily unavailable due to maintenance. Please try again later.: This indicates that the Blockchain Manager is not running or is not available. The status code returned is 503.
        2. Service is temporarily unavailable due to the network sub-system being inactive. Please try again later.: This indicates that the Network Manager is not running or is not available. The status code returned is 503.
        3. Service is temporarily unavailable due to no network connectivity. Please try again later.: This indicates that there is no network connectivity. The status code returned is 503.
        4. Invalid private key: This indicates that the provided private key is invalid. The status code returned is 400.
        5. Invalid source public-key: This indicates that the provided source public key is invalid. The status code returned is 400.
        6. Invalid source domain: This indicates that the provided source domain is invalid. The status code returned is 400.
        7. No nonce provided and source domain unknown: This indicates that no nonce was provided and the source domain is unknown. The status code returned is 400.
        8. Invalid recipient: This indicates that the provided recipient is invalid. The status code returned is 400.
        9. Failed to prepare transaction: This indicates that there was a failure in preparing the transaction. The status code returned is 500.
        10. Failed to register transaction: This indicates that there was a failure in registering the transaction. The status code returned is 500.
        11. Transaction exceeds provided ERG limit: This indicates that the transaction cost more ERGs to process than the user allowed with the ERGLimit parameter. The status code returned is 400.
        12. Invalid ERG price: This indicates that the provided ERG price is invalid. The status code returned is 400.
        13. Invalid value: This indicates that the provided transfer value is invalid. The status code returned is 400.

      5.6 Generating Wallets with genAddress

      The genAddress function is a versatile tool for generating cryptographic key-pairs, used by State-Domains oftentimes simply used as ‘wallet addresses’. This method can create a new High Definition (HD) key chain or derive an offspring identity (wallet address and the corresponding private/public key pair) from an existing Master Private Key. This function is a fundamental component of the RESTful API and is crucial for secure wallet management.

      IMPORTANT: Call this method only on Core Nodes which are under your control to prevent compromising your private key.

5.6.2 Use Case Scenarios

From the perspective of a Centralized Exchange (CEX), the `genAddress` method offers a streamlined and secure approach to manage user accounts.

By generating a single High Definition (HD) Key-Chain, a CEX can continuously create offspring wallets, each linked to individual user accounts.

This structure allows users to deposit assets into their designated offspring accounts, while the exchange retains full control and oversight. This methodology not only simplifies the management of numerous user accounts but also enhances security.

Since each user’s assets are held in a separate offspring wallet derived from the master key, it isolates potential risks and prevents a single point of failure. Moreover, the CEX can efficiently monitor and manage transactions across all user accounts, ensuring a secure and seamless trading experience for its clients.

5.6.1 Method Overview

This function is capable of operating in two distinct modes:

      1. Generating a new HD key chain along with the first offspring identity.
      2. Generating an offspring identity from an existing master private key (part of an exiting HD key chain provided to this method).

It returns a JSON object containing a Base58-check encoded private key, public key, wallet address, and wallet information including the master private key and the identity index.

5.6.2 Parameters

Input:

The function can accept the following optional parameters:

      • wallet: A base58-check encoded Master Private Key. If provided, an offspring identity is derived based on this key.
      • index: An unsigned integer representing the index of the offspring identity. Defaults to 0 if not provided.

5.6.3 Return Types

Output:

The function returns a JSON object with the following fields:

      1. result: An integer indicating the status of the operation. A value of 0 indicates success, while any other value represents an error code.
      2. errorDescription: A human-readable error description, present only if an error occurs.
      3. privateKey: A Base58Check encoded private key for the generated identity. The value is used by other API methods such as sendTX or processCode.
      4. publicKey: A Base58Check encoded public key for the generated identity.
      5. address: A Base58Check encoded address corresponding to the public key.
      6. wallet: This is the High Definition Wallet. It is comprised of a base58-check encoded Master Private Key along with a current identity index. This value is returned upon each valid invocation. When generating sub-identities the wallet contains the currently generated identity set at the active identity. Thus when imported to other components the identity would be used by default.
      7. index: The identity index used for generating the offspring identity, included if a master key is used.

5.6.4 Error Messages

The function may return the following error messages:

      1. Crypto Factory Service is temporarily unavailable. Please try again later.: Indicates the Crypto Factory is not available, returning status code 503.
      2. Invalid master private key: Indicates that the provided master private key is invalid, returning status code 400.
      3. Failed to generate address: Indicates a failure in generating the address, returning status code 500.

5.6.5 Usage Examples

Example 1: Generating a New HD Key Chain
GET /api/genAddress
This request generates a new HD key chain with the first offspring identity set as active.

Example 2: Generating an Offspring Identity from an Existing Master Key
GET /api/genAddress?wallet=Base58EncodedMasterKey&index=5
This request generates the fifth offspring identity based on the provided master private key.

5.6.6 Security Considerations

The genAddress function handles sensitive cryptographic materials. It is crucial to ensure secure transport (e.g., HTTPS) and to treat all cryptographic keys and wallet information with the highest level of security.

5.7 Executing GridScript with processCode

The processCode function is designed to process transactions that include arbitrary custom GridScript source code. In the nomenclature of GRIDNET OS, transaction is an arbitrary authenticated instruction set, broadcasted an processed by the system. This method is particularly useful for complex transactions where direct scripting is required. It is also useful for entities who require bulk processing of value transfers. A simple example would be a transaction targeting multiple recipients. The corresponding GridScript source code would include multiple lines, each line containing invocation of the GridScript ‘send’ instruction. Each such invocation would instruct system to issue value transfer to a particular independent recipient. This would allow for extremely fast transfers to multiple recipients at once. Notice that you need to remember whom the transaction was to target as there no more would be a one to one relationship between the recipient and sender. There would be a one to many relationship instead, in this example use case scenario.

Sample GridScript source code targeting multiple recipients could thus look like follows:
send Allice 10 -gnc
send Bob 5 -gnc
send Eve 500000

The result would be a transaction attempting:

  • delivery of 10 GBC to Allice
  • delivery of 5 GNC  to Bob
  • delivery of just 500000 GBUs to Eve
  • Notice that by default the sender’s main State-Domain (account) is used. Should sender be in control of multiple domains, one would first need to invoke the cd YOUR_ADDRESS command to get in scope of the appropriate account first. Replace `ADDRESS` with the actual wallet address or relevant Friendly Identifier.The source code would then look like follows:
    cd YOUR_ADDRESS
    send Allice 10 -gnc
    send Bob 5 -gnc
    send Eve 500000

    IMPORTANT:  If any sub-instruction fails, the entire transaction would fail as well. This method should only be called on Core Nodes that are under your control, as it involves sensitive cryptographic operations and your private key.

    5.7.1 Method Overview

    This function accepts a set of parameters, including GridScript source code, to create a transaction. The provided source code would be compiled into byte-code on the fly and should any error occur, the fact would be reported before an attempt to broadcast a transaction is made. It returns a JSON object containing the receipt ID of the processed transaction, a result field indicating operation success or failure, and an errorDescription field with a human-readable error description if an error occurs.

    5.7.2 Parameters

    Input: The function expects the following parameters:

    • sourceCode: The GridScript source code to be executed in the transaction. Required.
      Notice: this argument may be provided as either a POST or GET parameter.  With source codes longer than 2048 characters you need to use POST.
    • privKey: The private key associated with the source state-domain, base58check encoded. Required.
    • pubKey: The public key of the source state-domain, base58check encoded. Optional.
    • ERGLimit: The maximum limit of ERG that the transaction can consume. Required.
    • ERGPrice: The price per ERG for the transaction. Required.
    • nonce: A unique identifier used to prevent double-spending attacks. Optional. If not provided nonce currently associated with source account would be retrieved and incremented by one.
    • source: The source state-domain’s identifier. Optional. If not provided, the source state domain would be calculated based on private key.
    • onlyCalculateFee: If set to true, only the processing fee is calculated; no transaction is executed. Optional.

    5.7.3 Return Types

    Output: The function returns a JSON object with the following fields:

    1. result: An integer indicating the status of the operation. A value of 0 indicates success; any other value represents an error code.
    2. errorDescription: A string with a human-readable error description. Present only if an error occurs.
    3. receiptID: A string representing the receipt ID of the processed transaction. Present only if the operation is successful and onlyCalculateFee is not true.
    4. fee: The calculated fee for the transaction. Present only if onlyCalculateFee is true.

    5.7.4 Error Messages

    The function may return the following error messages:

    • Service is temporarily unavailable due to maintenance. Please try again later.: Indicates that the Blockchain Manager is not running or unavailable. Status code: 503.
    • Service is temporarily unavailable due to the network sub-system being inactive. Please try again later.: Indicates that the Network Manager is not running or unavailable. Status code: 503.
    • Service is temporarily unavailable due to no network connectivity. Please try again later.: Indicates that there is no network connectivity. Status code: 503.
    • Invalid private key: Indicates that the provided private key is invalid. Status code: 400.
    • Invalid source public-key: Indicates that the provided source public key is invalid. Status code: 400.
    • Invalid source domain: Indicates that the provided source domain is invalid. Status code: 400.
    • No nonce provided and source domain unknown: Indicates that no nonce was provided and the source domain is unknown. Status code: 400.
    • Failed to prepare transaction: Indicates a failure in preparing the transaction. Status code: 500.
    • Failed to register transaction: Indicates a failure in registering the transaction. Status code: 500.
    • Invalid ERG price: Indicates that the provided ERG price is invalid. Status code: 400.
    • InvalidERG Limit: Indicates that the provided ERG limit is invalid. Status code: 400.
    • GridScript source code was not provided: Indicates that the required GridScript source code was not provided. Status code: 400.
    • Provided GridScript source code is invalid: Indicated an error within the provided GridScript source code.

     

    5.8 Validating Wallets with checkAddress

    The checkAddress function is used to verify the validity of a given address in the GRIDNET OS. This is a crucial function for operations that require a valid address such as transactions.

    5.8.1 Method Overview

    This function takes in an address parameter, checks its validity, and returns a JSON object that reflects the status of the operation.

    5.8.2 Parameters

    Input: The function expects a single parameter, address. This parameter, passed as an HTTP GET parameter, represents the address that needs to be validated.

    5.8.3 Return Types

    Output: The function returns a JSON object with the following fields:

    1. result: An integer that indicates the status of the operation. A value of 0 indicates that the address is valid, while any other value represents an error code.
    2. errorDescription: A string with a human-readable error description. This field is only present if an error occurs.

    5.8.4 Error Messages

    The function may return the following error messages:

    1. Invalid address: This indicates that the provided address is not valid. The status code returned is 400.
    2. Missing required parameter: 'address' - use it to provide wallet's address which is to be looked up.: This indicates that the address parameter was not provided. The status code returned is 400.

    5.8.5 Specific Use-Cases

    This function is primarily used for validating an address before a transaction. It can also be used to verify if an address is correctly formatted and exists in the GRIDNET OS.

    5.8.6 Possible Outcomes and Their Meanings

    Upon calling this function, one of two things can happen:

    1. The function successfully validates the provided address and returns a JSON object with a result value of 0.
    2. The function fails to validate the address due to an invalid or missing address parameter. In this case, the JSON object returned will contain an errorDescription with the appropriate error message and a non-zero result.

    Example of a successful checkAddress function call:

    Request: GET /api/checkAddress?address=valid_addressResponse:
    {
    "result": 0
    }

    Example of an unsuccessful checkAddress function call:

    Request: GET /api/checkAddress?address=invalid_addressResponse:
    {
    "result": 1,
    "errorDescription": "Invalid address"
    }

    6. Sample API Workflow

    This sample workflow demonstrates how a user can use the API to generate a wallet, share the wallet with a third party, periodically check the wallet balance, issue an outgoing transaction, and verify the transaction status.

    Step 1: Wallet Generation

    The user generates a new wallet using the genAddress function.

    GET /api/genAddress
    

    This will return a JSON object that includes the generated address, and the corresponding base58-check encoded private and public keys.

    Step 2: Sharing the Wallet with a Third Party

    The user shares the generated wallet address with a third party. It’s important to note that only the wallet address should be shared, the private key should always remain confidential.

    Step 3: Querying for Wallet Balance

    The user periodically queries for the current balance using the getBalance function by providing the generated wallet address as a parameter.

    GET /api/getBalance?address=generated_address
    

    The returned JSON object will contain the current balance of the wallet.

    Step 4: Issuing an Outgoing Transaction

    Once the user receives the desired amount in their wallet, they can use the sendTX function to issue an outgoing transaction. This requires the recipient’s address, the amount to be transferred, and the sender’s private key as parameters.

    GET /api/sendTX?destination=recipient_address&value=amount_to_send&privKey=private_key
    

    This will return a JSON object that includes the receipt ID of the transaction.

    Step 5: Checking Transaction Status

    The user can use the getTX function to check the status of the transaction by providing the receipt ID as a parameter.

    GET /api/getTX?receiptID=receipt_id
    

    The returned JSON object will contain the transaction details, including its status.

    Step 6: Verifying Confirmation Blocks

    The recipient can use the getBlock function to verify if 3 confirmation blocks have been added after receiving the transaction. This is done by providing the block ID as a parameter.

    GET /api/getHeight

    The returned JSON object will contain the block details, including the number of confirmation blocks.

7. Best Practices

Using the GRIDNET OS RESTful API effectively involves understanding a few best practices. These practices not only aid in maintaining security, but also ensure efficient use of the API and network resources.

  1. Keep private keys private

    Private keys must be treated as confidential information. Never share your private keys and be cautious when using them for transactions. It’s recommended to deploy your own node for executing transactions, so you don’t need to share your private keys with public nodes.

  2. Check for returned codes

    Always check for returned codes and human-readable error messages. They provide insight about the request status and help you handle errors effectively.

  3. Asynchronous processing

    Keep in mind that processing of transactions is asynchronous, thus you should wait for multiple confirmation blocks before assuming the transaction as concluded.

  4. Validate data before submitting

    Perform necessary validations on data before sending it via the API. This can prevent unnecessary network requests and errors.

  5. Efficient use of network resources

    Make sure to send requests only as often as necessary, and avoid making the same request multiple times in a short period. Doing so will help to keep the network less congested and your applications more responsive.

8. Troubleshooting

When encountering issues with the GRIDNET OS RESTful API, a systematic approach to troubleshooting can help identify and resolve problems efficiently. Here are some tips and methods to aid in your troubleshooting process:

  1. Ensure your request format is correct

    Verify that your request follows the correct syntax, parameters, and values. Check your API endpoint, method, headers, and body for any syntax or logical errors. Additionally, ensure your JSON object is correctly formatted.

  2. Interpret HTTP status codes

    Understand the meaning of HTTP status codes. The returned HTTP status code can provide you with clues about what went wrong. For example, a 400 status code means a bad request, indicating that the server could not understand your request.

  3. Inspect returned error codes and messages

    Always check the ‘result’ and ‘errorDescription’ fields in the returned JSON object when a request fails. These fields can provide you with detailed information about the error.

  4. Use REST testing utilities

    Tools like Postman or Insomnia can be extremely useful for testing RESTful APIs. They allow you to easily construct requests, analyze responses, and automate testing.

9. Additional Resources

Here are some additional resources to help you navigate and leverage the GRIDNET OS RESTful API:

Dedicated Support Lines

For exchanges and other organizations in a direct partnership with The Team behind GRIDNET OS, dedicated support lines operating 24/7 are available. Please contact your GRIDNET OS representative for further details. These support lines offer real-time assistance for API implementation and troubleshooting.

GRIDNET Community Forum

GRIDNET OS is all about community. It is all about decentralization. Our active community forum is a place to ask questions, share ideas, and interact with other GRIDNET OS users. You can find answers, share solutions, and stay up-to-date on the latest news and updates. Visit the GRIDNET Community Forum to join the conversation.

We strive to answer all questions within less than 24 hours.

GRIDNET

Author

GRIDNET

Up Next

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *