/koios-rest-go-client

Go Client library for Koios API and CLI app to query koios.rest endpoints.

Primary LanguageGoApache License 2.0Apache-2.0

Koios API Client Library for Go

⚠️ UNTIL v1.0.0 RELEASE THIS LIBRARY MAY GET BREAKING CHANGES

license

  • before updating e.g. go get -u check for changes to prevent inconveniences.
  • v1.0.0 enhancements are tracked under following issue

Koios API is Elastic Cardano Query Layer!

A consistent query layer for developers to build upon Cardano, with
multiple, redundant endpoints that allow for easy scalability.

Koios API Client Library for Go

PkgGoDev Go Report Card

go get github.com/howijd/koios-rest-go-client
...
import (
  "github.com/howijd/koios-rest-go-client" // imports as package "koios"
)
...

CLI Application to interact with Koios API from Command-line see

See installing instruction

Build Status

linux macos windows

Development Status

GitHub last commit coverage codeql misspell



Usage

See Godoc PkgGoDev Additionally you can find all usecases by looking source of koio-rest Command-line application source which utilizes entire API of this library.

NOTE

Library normalizes some of the API responses and constructs Typed response for each end point. If you wish to work with *http.Response directly you can do so by using api client GET,POST, HEAD methods.

Basic usage

package main

import (
	"context"
	"fmt"
	"log"

	koios "github.com/howijd/koios-rest-go-client"
)

func main() {
  // Call to koios.New without options is same as calling it with default opts.
  // See godoc for available configuration options.
  // api, err := koios.New(
  // 	koios.Host(koios.MainnetHost),
  // 	koios.APIVersion(koios.DefaultAPIVersion),
  // 	koios.Port(koios.DefaultPort),
  // 	koios.Schema(koios.DefaultSchema),
  // 	koios.HttpClient(koios.DefaultHttpClient),
  // ).
  api, err := koios.New()
  if err != nil {
    log.Fatal(err)
  }

  res, err := api.GetTip(context.Background())
  if err != nil {
	  log.Fatal(err)
  }
  fmt.Println("status: ", res.Status)
  fmt.Println("statu_code: ", res.StatusCode)

  fmt.Println("abs_slot: ", res.Tip.AbsSlot)
  fmt.Println("block_no: ", res.Tip.BlockNo)
  fmt.Println("block_time: ", res.Tip.BlockTime)
  fmt.Println("epoch: ", res.Tip.Epoch)
  fmt.Println("epoch_slot: ", res.Tip.EpochSlot)
  fmt.Println("hash: ", res.Tip.Hash)
}

Concurrency using goroutines

This library is thread-safe so you can freerly use same api client instance passing it to your goroutines.

Following example uses goroutines to query chain tip from different endpoints.

func main() {
  api, _ := koios.New(
    // limit client request 1 per second even though 
    // this example will send requests in goroutines.
    koios.RateLimit(1),
  )
  ctx := context.Background()
  defer cancel()
  var wg sync.WaitGroup
  servers := []string{
    "api.koios.rest",
    "guild.koios.rest",
    "testnet.koios.rest",
  }

  // Thanks to rate limit option requests will be made
  // once in a second.
  for _, host := range servers {
    wg.Add(1)
    go func(ctx context.Context, host string) {
      defer wg.Done()
      // switching host. all options changes are safe to call from goroutines.
      koios.Host(host)(api)
      res, _ := api.GET(ctx, "/tip")
      defer res.Body.Close()
      body, _ := ioutil.ReadAll(res.Body)
      fmt.Println(string(body))
    }(ctx, host)
  }
  
  wg.Wait()
  fmt.Println("requests done: ", api.TotalRequests())
}

Lovelace (math on ada, assets and tokens).

Liprary uses for most cases to represent lovelace using Lovelace data type.

This library uses forked snapshot of github.com/shopspring/decimal package to provide
JSON and XML serialization/deserialization and make it ease to work with calculations
and deciimal precisions of ADA lovelace and native assets.

For decimal package API see

FORK: https://github.com/howijd/decimal
issues and bug reports are welcome to: https://github.com/howijd/decimal/issues.

Implemented Endpoints

endpoint Go API CLI command API Doc
NETWORK
/tip *.GetTip(...) *TipResponse tip
/genesis *.GetGenesis(...) *GenesisResponse genesis
/totals *.GetTotals(...) *TotalsResponse totals
EPOCH
/epoch_info *.GetEpochInfo(...) *EpochInfoResponse epoch-info
/epoch_params *.GetEpochParams(...) *EpochParamsResponse epoch-params
BLOCK
/blocks *.GetBlocks(...) *BlocksResponse blocks
/block_info *.GetBlockInfo(...) *BlockInfoResponse block-info
/block_txs *.GetBlockTxs(...) *BlockTxsResponse block-txs
TRANSACTIONS
/tx_info *.GetTxsInfos(...) *TxsInfoResponse txs-infos
*.GetTxInfo(...) *TxInfoResponse tx-info
/tx_utxos *.GetTxsUTxOs(...) *TxUTxOsResponse tx-utxos
/tx_metadata *.GetTxsMetadata(...) *TxsMetadataResponse txs-metadata
*.GetTxMetadata(...) *TxMetadataResponse tx-metadata
/tx_metalabels *.GetTxMetaLabels(...) *TxMetaLabelsResponse tx-metalabels
/submittx *.SubmitSignedTx(...) *SubmitSignedTxResponse tx-submit
/tx_status *.GetTxsStatuses(...) *TxsStatusesResponse txs-statuses
*.GetTxStatus(...) *TxStatusResponse tx-status
ADDRESS
/address_info *.GetAddressInfo(...) *AddressInfoResponse address-info
/address_txs *.GetAddressTxs(...) *AddressTxsResponse address-txs
/address_assets *.GetAddressAssets(...) *AddressAssetsResponse address-assets
/credential_txs *.GetCredentialTxs(...) *CredentialTxsResponse credential-txs
ACCOUNT
/account_list *.GetAccountList(...) *AccountListResponse account-list
/account_info *.GetAccountInfo(...) *AccountListResponse account-info
/account_rewards *.GetAccountRewards(...) *AccountRewardsResponse account-rewards
/account_updates *.GetAccountUpdates(...) *AccountUpdatesResponse account-updates
/account_addresses *.GetAccountAddresses(...) *AccountAddressesResponse account-addresses
/account_assets *.GetAccountAssets(...) *AccountAssetsResponse account-assets
/account_history *.GetAccountHistory(...) *AccountHistoryResponse account-history
ASSET
/asset_list *.GetAssetList(...) *AssetAddressListResponse asset-list
/asset_address_list *.GetAssetAddressList(...) *AssetAddressListResponse asset-address-list
/asset_info *.GetAssetInfo(...) *AssetInfoResponse asset-info
/asset_summary *.GetAssetSummary(...) *AssetSummaryResponse asset-summary
/asset_txs *.GetAssetTxs(...) *AssetTxsResponse asset-txs
POOL
/pool_list *.GetPoolList(...) *PoolListResponse pool-list
/pool_info *.GetPoolInfos(...) *PoolInfoResponse pool-infos
*.GetPoolInfo(...) *PoolInfoResponse pool-info
/pool_delegators *.GetPoolDelegators(...) *PoolDelegatorsResponse pool-delegators
/pool_blocks *.GetPoolBlocks(...) *PoolBlocksResponse pool-blocks
/pool_updates *.GetPoolUpdates(...) *PoolUpdatesResponse pool-updates
/pool_relays *.GetPoolRelays(...) *PoolRelaysResponse pool-relays
/pool_metadata *.GetPoolMetadata(...) *PoolMetadataResponse pool-metadata
SCRIPT
/script_list *.GetScriptList(...) *ScriptRedeemersResponse script-list
/script_redeemers *.GetScriptRedeemers(...) *ScriptListResponse script-redeemers

CLI Application

source of cli: ./cmd/koios-rest.

List of all commands

koios-rest --help
NAME:
   koios-rest - CLI Client to consume Koios API https://api.koios.rest

USAGE:
   koios-rest [global options] command [command options] [arguments...]

VERSION:
   (devel)

AUTHOR:
   The Howijd.Network Authors

COMMANDS:
   help, h  Shows a list of commands or help for one command
   ACCOUNT:
     account-list       Get a list of all accounts returns array of stake addresses.
     account-info       Get the account info of any (payment or staking) address.
     account-rewards    Get the full rewards history (including MIR) for a stake address, or certain epoch if specified.
     account-updates    Get the account updates (registration, deregistration, delegation and withdrawals).
     account-addresses  Get all addresses associated with an account payment or staking address
     account-assets     Get the native asset balance of an account.
     account-history    Get the staking history of an account.
   ADDRESS:
     address-info    Get address info - balance, associated stake address (if any) and UTxO set.
     address-txs     Get the transaction hash list of input address array, optionally filtering after specified block height (inclusive).
     address-assets  Get the list of all the assets (policy, name and quantity) for a given address.
     credential-txs  Get the transaction hash list of input payment credential array, optionally filtering after specified block height (inclusive).
   ASSET:
     asset-list          Get the list of all native assets (paginated).
     asset-address-list  Get the list of all addresses holding a given asset.
     asset-info          Get the information of an asset including first minting & token registry metadata.
     asset-summary       Get the summary of an asset (total transactions exclude minting/total wallets include only wallets with asset balance).
     asset-txs           Get the list of all asset transaction hashes (newest first).
   BLOCK:
     blocks      Get summarised details about all blocks (paginated - latest first).
     block-info  Get detailed information about a specific block.
     block-txs   Get a list of all transactions included in a provided block.
   EPOCH:
     epoch-info    Get the epoch information, all epochs if no epoch specified.
     epoch-params  Get the protocol parameters for specific epoch, returns information about all epochs if no epoch specified.
   NETWORK:
     tip      Get the tip info about the latest block seen by chain.
     genesis  Get the Genesis parameters used to start specific era on chain.
     totals   Get the circulating utxo, treasury, rewards, supply and reserves in lovelace for specified epoch, all epochs if empty.
   POOL:
     pool-list        A list of all currently registered/retiring (not retired) pools.
     pool-infos       Current pool statuses and details for a specified list of pool ids.
     pool-info        Current pool status and details for a specified pool by pool id.
     pool-delegators  Return information about delegators by a given pool and optional epoch (current if omitted).
     pool-blocks      Return information about blocks minted by a given pool in current epoch (or _epoch_no if provided).
     pool-updates     Return all pool updates for all pools or only updates for specific pool if specified.
     pool-relays      A list of registered relays for all currently registered/retiring (not retired) pools.
     pool-metadata    Metadata(on & off-chain) for all currently registered/retiring (not retired) pools.
   SCRIPT:
     script-list       List of all existing script hashes along with their creation transaction hashes.
     script-redeemers  List of all redeemers for a given script hash.
   TRANSACTIONS:
     txs-infos      Get detailed information about transaction(s).
     tx-info        Get detailed information about single transaction.
     tx-utxos       Get UTxO set (inputs/outputs) of transactions.
     txs-metadata   Get metadata information (if any) for given transaction(s).
     tx-metadata    Get metadata information (if any) for given transaction.
     tx-metalabels  Get a list of all transaction metalabels.
     tx-submit      Submit signed transaction to the network.
     txs-statuses   Get the number of block confirmations for a given transaction hash list
     tx-status      Get the number of block confirmations for a given transaction hash
   UTILS:
     get   get issues a GET request to the specified API endpoint
     head  head issues a HEAD request to the specified API endpoint

GLOBAL OPTIONS:
   --port value, -p value  Set port (default: 443)
   --host value            Set host (default: "api.koios.rest")
   --api-version value     Set API version (default: "v0")
   --schema value          Set URL schema (default: "https")
   --origin value          Set Origin header for requests. (default: "https://github.com/howijd/koios-rest-go-client")
   --rate-limit value      Set API Client rate limit for outgoing requests (default: 5)
   --no-format             prints response json strings directly without calling json pretty. (default: false)
   --enable-req-stats      Enable request stats. (default: false)
   --testnet               use default testnet as host. (default: false)
   --help, -h              show help (default: false)
   --version, -v           print the version (default: false)

COPYRIGHT:
   (c) 2022

Example Usage

Example to query mainnet tip from cli

koios-rest --enable-req-stats tip

response

{
  "request_url": "https://api.koios.rest/api/v0/tip",
  "request_method": "GET",
  "status_code": 200,
  "status": "200 OK",
  "date": "Mon, 07 Feb 2022 12:49:49 GMT",
  "content_range": "0-0/*",
  "stats": {
    "req_started_at": "2022-02-07T12:49:48.565834833Z",
    "req_dns_lookup_dur": 1284269, // dns lookup duration in nanosecons.
    "tls_hs_dur": 208809082, // handshake duration in nanosecons.
    "est_cxn_dur": 159857626, // time it took to establish connection with server in nanosecons.
    "ttfb": 998874037, // time since start of the request it took to recieve first byte.
    "req_dur": 999186595, // total request duration in nanoseconds
    "req_dur_str": "999.186595ms" // string of req_dur
  },
  "data": {
    "abs_slot": 52671876,
    "block_no": 6852764,
    "block_time": "2022-02-07T12:49:27",
    "epoch": 319,
    "epoch_slot": 227076,
    "hash": "1dad134750188460dd48068e655b5935403d2f51afaf53a39337a4c89771754a"
  }

Example to query testnet tip from cli

koios-rest --enable-req-stats --testnet tip
# OR
koios-rest --enable-req-stats --host testnet.koios.rest tip

response

{
  "request_url": "https://testnet.koios.rest/api/v0/tip",
  "request_method": "GET",
  "status_code": 200,
  "status": "200 OK",
  "date": "Mon, 07 Feb 2022 12:50:04 GMT",
  "content_range": "0-0/*",
  "stats": {
    "req_started_at": "2022-02-07T12:50:03.98615637Z",
    "req_dns_lookup_dur": 1383437,
    "tls_hs_dur": 69093093,
    "est_cxn_dur": 43733700,
    "ttfb": 167423049,
    "req_dur": 167738287,
    "req_dur_str": "167.738287ms"
  },
  "data": {
    "abs_slot": 49868948,
    "block_no": 3300758,
    "block_time": "2022-02-07T12:49:24",
    "epoch": 185,
    "epoch_slot": 318548,
    "hash": "d7623e68cb78f450f42ba4b5a169124b26677f08f676ca4241b27edb6dbf0071"
  }
}

Install

It's highly recommended installing a specific version of koios-rest available on the releases page.

Install from Source

Installing from source requires a working Go environment. See the install instructions for Go.

Since koios-rest cli application uses replace in ./cmd/koiso-rest/go.mod. Then go install won't work. To install it from source use following commands.

  1. git clone git@github.com:howijd/koios-rest-go-client.git
  2. cd ./koios-rest-go-client/cmd/koios-rest
  3. go install .

verify installation

koios-rest --version