/blockfrost_api

Dart wrapper around the Cardano blockfrost REST API.

Primary LanguageDartApache License 2.0Apache-2.0

BlockFrost Service API

INTRODUCTION

This library is for accessing the Cardano blockchain via BlockFrost service nodes. BlockFrost allows access to the blockchain for light clients that do not wish to run a dedicated, resource intensive, Cardano node locally.

This code is available as a package on pub.dev: https://pub.dev/packages/blockfrost

Warning: This library is a minimal unofficial Blockfrost implementation created to support Flutter SDK.

Tests

To run the tests, you must download a apiKey from https://blockfrost.io, then place the key in the parent directory of your project in a file with the name:

    blockfrost_project_id.txt

i.e.

echo "your-project-id" > ../blockfrost_project_id.txt

MyApiKeyAuthInterceptor will read the key on startup and insert it into the REST header requests.

  final instance = Blockfrost(
    basePathOverride: testnet,
    interceptors: [MyApiKeyAuthInterceptor()],
  );

Production

To use this code in production, simply replace MyApiKeyAuthInterceptor with BlockfrostApiKeyAuthInterceptor, passing your project_id key into the constructor:

BlockfrostApiKeyAuthInterceptor(projectId:'your-project-id')

Here is an implemenation - blockfrost_api_key_auth.dart:

import 'package:dio/dio.dart';
import 'package:blockfrost/src/auth/auth.dart';

class BlockfrostApiKeyAuthInterceptor extends AuthInterceptor {
  final String projectId;
  BlockfrostApiKeyAuthInterceptor({required this.projectId});
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    options.headers['project_id'] = projectId;
    super.onRequest(options, handler);
  }
}

Usage

Refer to the generated documentation below and tests for example usage. Be aware, this is very low-level, blockchain-specific code. If you wish to send transactions or work with smart contracts, you'll need a higher level API. The cardano_wallet_sdk (by the same author) is a good resource for code and tests that demonstrate how to use this API to build higher level services.

Status

Five Binaries was granted $10,000 in Fund 6 to implement an official BlockFrost Dart binding:

https://cardano.ideascale.com/c/idea/369239

The source code can be found here:

https://github.com/blockfrost/blockfrost-dart/

When the official implementation matures, this project will be discontinued.

Support

This is not an official blockfrost package so please do not contract BlockFrost with issues specific to this code.

GENERATED DOCUMENTATION - blockfrost (EXPERIMENTAL)

Blockfrost is an API as a service that allows users to interact with the Cardano blockchain and parts of its ecosystem.

Tokens

After signing up on https://blockfrost.io, a project_id token is automatically generated for each project. HTTP header of your request MUST include this project_id in order to authenticate against Blockfrost servers.

Available networks

At the moment, you can use the following networks. Please, note that each network has its own project_id.

NetworkEndpoint
Cardano mainnethttps://cardano-mainnet.blockfrost.io/api/v0
Cardano testnethttps://cardano-testnet.blockfrost.io/api/v0
InterPlanetary File Systemhttps://ipfs.blockfrost.io/api/v0

Concepts

  • All endpoints return either a JSON object or an array.
  • Data is returned in ascending (oldest first, newest last) order.
    • You might use the ?order=desc query parameter to reverse this order.
  • By default, we return 100 results at a time. You have to use ?page=2 to list through the results.
  • All time and timestamp related fields are in milliseconds of UNIX time.
  • All amounts are returned in Lovelaces, where 1 ADA = 1 000 000 Lovelaces.
  • Addresses, accounts and pool IDs are in Bech32 format.
  • All values are case sensitive.
  • All hex encoded values are lower case.
  • Examples are not based on real data. Any resemblance to actual events is purely coincidental.
  • We allow to upload files up to 100MB of size to IPFS. This might increase in the future.

Errors

HTTP Status codes

The following are HTTP status code your application might receive when reaching Blockfrost endpoints and it should handle all of these cases.

  • HTTP 400 return code is used when the request is not valid.
  • HTTP 402 return code is used when the projects exceed their daily request limit.
  • HTTP 403 return code is used when the request is not authenticated.
  • HTTP 404 return code is used when the resource doesn't exist.
  • HTTP 418 return code is used when the user has been auto-banned for flooding too much after previously receiving error code 402 or 429.
  • HTTP 429 return code is used when the user has sent too many requests in a given amount of time and therefore has been rate-limited.
  • HTTP 500 return code is used when our endpoints are having a problem.

Error codes

An internal error code number is used for better indication of the error in question. It is passed using the following payload.

{
  \"status_code\": 403,
  \"error\": \"Forbidden\",
  \"message\": \"Invalid project token.\"
}

Limits

There are two types of limits we are enforcing:

The first depends on your plan and is the number of request we allow per day. We defined the day from midnight to midnight of UTC time.

The second is rate limiting. We limit an end user, distinguished by IP address, to 10 requests per second. On top of that, we allow each user to send burst of 500 requests, which cools off at rate of 10 requests per second. In essence, a user is allowed to make another whole burst after (currently) 500/10 = 50 seconds. E.g. if a user attemtps to make a call 3 seconds after whole burst, 30 requests will be processed. We believe this should be sufficient for most of the use cases. If it is not and you have a specific use case, please get in touch with us, and we will make sure to take it into account as much as we can.

Authentication

This Dart package is automatically generated by the OpenAPI Generator project:

  • API version: 0.1.23
  • Build package: org.openapitools.codegen.languages.DartDioNextClientCodegen For more information, please visit https://blockfrost.io

Requirements

  • Dart 2.12.0 or later OR Flutter 1.26.0 or later
  • Dio 4.0.0+

Installation & Usage

pub.dev

To use the package from pub.dev, please include the following in pubspec.yaml

dependencies:
  blockfrost: 1.0.0

Github

If this Dart package is published to Github, please include the following in pubspec.yaml

dependencies:
  blockfrost:
    git:
      url: https://github.com/GIT_USER_ID/GIT_REPO_ID.git
      #ref: main

Local development

To use the package from your local drive, please include the following in pubspec.yaml

dependencies:
  blockfrost:
    path: /path/to/blockfrost

Getting Started

Please follow the installation procedure and then run the following:

import 'package:blockfrost/blockfrost.dart';


final api = CardanoAccountsApi();
final stakeAddress = stake1u9ylzsgxaa6xctf4juup682ar3juj85n8tx3hthnljg47zctvm3rc; // String | Bech32 stake address.
final count = 56; // int | The number of results displayed on one page.
final page = 56; // int | The page number for listing the results.
final order = order_example; // String | The ordering of items from the point of view of the blockchain, not the page listing itself. By default, we return oldest first, newest last. 

try {
    final response = await api.accountsStakeAddressAddressesAssetsGet(stakeAddress, count, page, order);
    print(response);
} catch on DioError (e) {
    print("Exception when calling CardanoAccountsApi->accountsStakeAddressAddressesAssetsGet: $e\n");
}

Documentation for API Endpoints

All URIs are relative to https://cardano-mainnet.blockfrost.io/api/v0

Class Method HTTP request Description
CardanoAccountsApi accountsStakeAddressAddressesAssetsGet get /accounts/{stake_address}/addresses/assets Assets associated with the account addresses
CardanoAccountsApi accountsStakeAddressAddressesGet get /accounts/{stake_address}/addresses Account associated addresses
CardanoAccountsApi accountsStakeAddressDelegationsGet get /accounts/{stake_address}/delegations Account delegation history
CardanoAccountsApi accountsStakeAddressGet get /accounts/{stake_address} Specific account address
CardanoAccountsApi accountsStakeAddressHistoryGet get /accounts/{stake_address}/history Account history
CardanoAccountsApi accountsStakeAddressMirsGet get /accounts/{stake_address}/mirs Account MIR history
CardanoAccountsApi accountsStakeAddressRegistrationsGet get /accounts/{stake_address}/registrations Account registration history
CardanoAccountsApi accountsStakeAddressRewardsGet get /accounts/{stake_address}/rewards Account reward history
CardanoAccountsApi accountsStakeAddressWithdrawalsGet get /accounts/{stake_address}/withdrawals Account withdrawal history
CardanoAddressesApi addressesAddressGet get /addresses/{address} Specific address
CardanoAddressesApi addressesAddressTotalGet get /addresses/{address}/total Address details
CardanoAddressesApi addressesAddressTransactionsGet get /addresses/{address}/transactions Address transactions
CardanoAddressesApi addressesAddressTxsGet get /addresses/{address}/txs Address transactions
CardanoAddressesApi addressesAddressUtxosGet get /addresses/{address}/utxos Address UTXOs
CardanoAssetsApi assetsAssetAddressesGet get /assets/{asset}/addresses Asset addresses
CardanoAssetsApi assetsAssetGet get /assets/{asset} Specific asset
CardanoAssetsApi assetsAssetHistoryGet get /assets/{asset}/history Asset history
CardanoAssetsApi assetsAssetTransactionsGet get /assets/{asset}/transactions Asset transactions
CardanoAssetsApi assetsAssetTxsGet get /assets/{asset}/txs Asset transactions
CardanoAssetsApi assetsGet get /assets Assets
CardanoAssetsApi assetsPolicyPolicyIdGet get /assets/policy/{policy_id} Assets of a specific policy
CardanoBlocksApi blocksEpochEpochNumberSlotSlotNumberGet get /blocks/epoch/{epoch_number}/slot/{slot_number} Specific block in a slot in an epoch
CardanoBlocksApi blocksHashOrNumberGet get /blocks/{hash_or_number} Specific block
CardanoBlocksApi blocksHashOrNumberNextGet get /blocks/{hash_or_number}/next Listing of next blocks
CardanoBlocksApi blocksHashOrNumberPreviousGet get /blocks/{hash_or_number}/previous Listing of previous blocks
CardanoBlocksApi blocksHashOrNumberTxsGet get /blocks/{hash_or_number}/txs Block transactions
CardanoBlocksApi blocksLatestGet get /blocks/latest Latest block
CardanoBlocksApi blocksLatestTxsGet get /blocks/latest/txs Latest block transactions
CardanoBlocksApi blocksSlotSlotNumberGet get /blocks/slot/{slot_number} Specific block in a slot
CardanoEpochsApi epochsLatestGet get /epochs/latest Latest epoch
CardanoEpochsApi epochsLatestParametersGet get /epochs/latest/parameters Latest epoch protocol parameters
CardanoEpochsApi epochsNumberBlocksGet get /epochs/{number}/blocks Block distribution
CardanoEpochsApi epochsNumberBlocksPoolIdGet get /epochs/{number}/blocks/{pool_id} Block distribution
CardanoEpochsApi epochsNumberGet get /epochs/{number} Specific epoch
CardanoEpochsApi epochsNumberNextGet get /epochs/{number}/next Listing of next epochs
CardanoEpochsApi epochsNumberParametersGet get /epochs/{number}/parameters Protocol parameters
CardanoEpochsApi epochsNumberPreviousGet get /epochs/{number}/previous Listing of previous epochs
CardanoEpochsApi epochsNumberStakesGet get /epochs/{number}/stakes Stake distribution
CardanoEpochsApi epochsNumberStakesPoolIdGet get /epochs/{number}/stakes/{pool_id} Stake distribution by pool
CardanoLedgerApi genesisGet get /genesis Blockchain genesis
CardanoMetadataApi metadataTxsLabelsGet get /metadata/txs/labels Transaction metadata labels
CardanoMetadataApi metadataTxsLabelsLabelCborGet get /metadata/txs/labels/{label}/cbor Transaction metadata content in CBOR
CardanoMetadataApi metadataTxsLabelsLabelGet get /metadata/txs/labels/{label} Transaction metadata content in JSON
CardanoPoolsApi poolsGet get /pools List of stake pools
CardanoPoolsApi poolsPoolIdBlocksGet get /pools/{pool_id}/blocks Stake pool blocks
CardanoPoolsApi poolsPoolIdDelegatorsGet get /pools/{pool_id}/delegators Stake pool delegators
CardanoPoolsApi poolsPoolIdGet get /pools/{pool_id} Specific stake pool
CardanoPoolsApi poolsPoolIdHistoryGet get /pools/{pool_id}/history Stake pool history
CardanoPoolsApi poolsPoolIdMetadataGet get /pools/{pool_id}/metadata Stake pool metadata
CardanoPoolsApi poolsPoolIdRelaysGet get /pools/{pool_id}/relays Stake pool relays
CardanoPoolsApi poolsPoolIdUpdatesGet get /pools/{pool_id}/updates Stake pool updates
CardanoPoolsApi poolsRetiredGet get /pools/retired List of retired stake pools
CardanoPoolsApi poolsRetiringGet get /pools/retiring List of retiring stake pools
CardanoTransactionsApi txSubmitPost post /tx/submit Submit a transaction
CardanoTransactionsApi txsHashDelegationsGet get /txs/{hash}/delegations Transaction delegation certificates
CardanoTransactionsApi txsHashGet get /txs/{hash} Specific transaction
CardanoTransactionsApi txsHashMetadataCborGet get /txs/{hash}/metadata/cbor Transaction metadata in CBOR
CardanoTransactionsApi txsHashMetadataGet get /txs/{hash}/metadata Transaction metadata
CardanoTransactionsApi txsHashMirsGet get /txs/{hash}/mirs Transaction MIRs
CardanoTransactionsApi txsHashPoolRetiresGet get /txs/{hash}/pool_retires Transaction stake pool retirement certificates
CardanoTransactionsApi txsHashPoolUpdatesGet get /txs/{hash}/pool_updates Transaction stake pool registration and update certificates
CardanoTransactionsApi txsHashStakesGet get /txs/{hash}/stakes Transaction stake addresses certificates
CardanoTransactionsApi txsHashUtxosGet get /txs/{hash}/utxos Transaction UTXOs
CardanoTransactionsApi txsHashWithdrawalsGet get /txs/{hash}/withdrawals Transaction withdrawal
HealthApi healthClockGet get /health/clock Current backend time
HealthApi healthGet get /health Backend health status
HealthApi rootGet get / Root endpoint
IPFSAddApi ipfsAddPost post /ipfs/add Add a file or directory to IPFS
IPFSGatewayApi ipfsGatewayIPFSPathGet get /ipfs/gateway/{IPFS_path} Relay to an IPFS gateway
IPFSPinsApi ipfsPinAddIPFSPathPost post /ipfs/pin/add/{IPFS_path} Pin an object
IPFSPinsApi ipfsPinListGet get /ipfs/pin/list/
IPFSPinsApi ipfsPinListIPFSPathGet get /ipfs/pin/list/{IPFS_path}
IPFSPinsApi ipfsPinRemoveIPFSPathPost post /ipfs/pin/remove/{IPFS_path}
MetricsApi metricsEndpointsGet get /metrics/endpoints Blockfrost endpoint usage metrics
MetricsApi metricsGet get /metrics/ Blockfrost usage metrics
NutLinkApi nutlinkAddressGet get /nutlink/{address}
NutLinkApi nutlinkAddressTickersGet get /nutlink/{address}/tickers
NutLinkApi nutlinkAddressTickersTickerGet get /nutlink/{address}/tickers/{ticker}
NutLinkApi nutlinkTickersTickerGet get /nutlink/tickers/{ticker}

Documentation For Models

Documentation For Authorization

ApiKeyAuth

  • Type: API key
  • API key parameter name: project_id
  • Location: HTTP header